blob: d09b0ee2a501597c12cf8e758f415d38b56911d3 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ 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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000068 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000069 };
Chris Lattner8123a952008-04-10 02:22:51 +000070
Chris Lattner9e979552008-04-12 23:52:44 +000071 /// VisitExpr - Visit all of the children of this expression.
72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000074 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000075 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000076 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000077 }
78
Chris Lattner9e979552008-04-12 23:52:44 +000079 /// VisitDeclRefExpr - Visit a reference to a declaration, to
80 /// determine whether this declaration can be used in the default
81 /// argument expression.
82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000084 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85 // C++ [dcl.fct.default]p9
86 // Default arguments are evaluated each time the function is
87 // called. The order of evaluation of function arguments is
88 // unspecified. Consequently, parameters of a function shall not
89 // be used in default argument expressions, even if they are not
90 // evaluated. Parameters of a function declared before a default
91 // argument expression are in scope and can hide namespace and
92 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000093 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000095 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000096 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000097 // C++ [dcl.fct.default]p7
98 // Local variables shall not be used in default argument
99 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000100 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000101 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000103 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105
Douglas Gregor3996f232008-11-04 13:41:56 +0000106 return false;
107 }
Chris Lattner9e979552008-04-12 23:52:44 +0000108
Douglas Gregor796da182008-11-04 14:32:21 +0000109 /// VisitCXXThisExpr - Visit a C++ "this" expression.
110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111 // C++ [dcl.fct.default]p8:
112 // The keyword this shall not be used in a default argument of a
113 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000114 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 diag::err_param_default_argument_references_this)
116 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000117 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000118
John McCall045d2522013-04-09 01:56:28 +0000119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120 bool Invalid = false;
121 for (PseudoObjectExpr::semantics_iterator
122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123 Expr *E = *i;
124
125 // Look through bindings.
126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127 E = OVE->getSourceExpr();
128 assert(E && "pseudo-object binding without source expression?");
129 }
130
131 Invalid |= Visit(E);
132 }
133 return Invalid;
134 }
135
Douglas Gregorf0459f82012-02-10 23:30:22 +0000136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137 // C++11 [expr.lambda.prim]p13:
138 // A lambda-expression appearing in a default argument shall not
139 // implicitly or explicitly capture any entity.
140 if (Lambda->capture_begin() == Lambda->capture_end())
141 return false;
142
143 return S->Diag(Lambda->getLocStart(),
144 diag::err_lambda_capture_default_arg);
145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146}
147
Richard Smith0b0ca472013-04-10 06:11:48 +0000148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000151 // If we have an MSAny spec already, don't bother.
152 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000153 return;
154
155 const FunctionProtoType *Proto
156 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158 if (!Proto)
159 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000160
161 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000164 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000165 ClearExceptions();
166 ComputedEST = EST;
167 return;
168 }
169
Richard Smith7a614d82011-06-11 17:19:42 +0000170 // FIXME: If the call to this decl is using any of its default arguments, we
171 // need to search them for potentially-throwing calls.
172
Sean Hunt001cad92011-05-10 00:49:42 +0000173 // If this function has a basic noexcept, it doesn't affect the outcome.
174 if (EST == EST_BasicNoexcept)
175 return;
176
177 // If we have a throw-all spec at this point, ignore the function.
178 if (ComputedEST == EST_None)
179 return;
180
181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
183 if (EST == EST_DynamicNone) {
184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
187 }
188
189 // Check out noexcept specs.
190 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198
199 // noexcept(false) -> no spec on the new function
200 if (NR == FunctionProtoType::NR_Throw) {
201 ClearExceptions();
202 ComputedEST = EST_None;
203 }
204 // noexcept(true) won't change anything either.
205 return;
206 }
207
208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214 EEnd = Proto->exception_end();
215 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000217 Exceptions.push_back(*E);
218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param)
343 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Anders Carlsson5e300d12009-06-12 16:51:40 +0000358 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000359}
360
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 delete Toks;
394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
398 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000399 }
400 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000403 }
404 }
405}
406
Craig Topper1a6eac82012-09-21 04:33:26 +0000407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000413 bool Invalid = false;
414
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000416 // For non-template functions, default arguments can be added in
417 // later declarations of a function in the same
418 // scope. Declarations in different scopes have completely
419 // distinct sets of default arguments. That is, declarations in
420 // inner scopes do not acquire default arguments from
421 // declarations in outer scopes, and vice versa. In a given
422 // function declaration, all parameters subsequent to a
423 // parameter with a default argument shall have default
424 // arguments supplied in this or previous declarations. A
425 // default argument shall not be redefined by a later
426 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000427 //
428 // C++ [dcl.fct.default]p6:
429 // Except for member functions of class templates, the default arguments
430 // in a member function definition that appears outside of the class
431 // definition are added to the set of default arguments provided by the
432 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434 ParmVarDecl *OldParam = Old->getParamDecl(p);
435 ParmVarDecl *NewParam = New->getParamDecl(p);
436
James Molloy9cda03f2012-03-13 08:55:35 +0000437 bool OldParamHasDfl = OldParam->hasDefaultArg();
438 bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440 NamedDecl *ND = Old;
441 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442 // Ignore default parameters of old decl if they are not in
443 // the same scope.
444 OldParamHasDfl = false;
445
446 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000447
Francois Pichet8d051e02011-04-10 03:03:52 +0000448 unsigned DiagDefaultParamID =
449 diag::err_param_default_argument_redefinition;
450
451 // MSVC accepts that default parameters be redefined for member functions
452 // of template class. The new default parameter's value is ignored.
453 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000457 // Merge the old default argument into the new parameter.
458 NewParam->setHasInheritedDefaultArg();
459 if (OldParam->hasUninstantiatedDefaultArg())
460 NewParam->setUninstantiatedDefaultArg(
461 OldParam->getUninstantiatedDefaultArg());
462 else
463 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000465 Invalid = false;
466 }
467 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000468
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470 // hint here. Alternatively, we could walk the type-source information
471 // for NewParam to find the last source location in the type... but it
472 // isn't worth the effort right now. This is the kind of test case that
473 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000474 // int f(int);
475 // void g(int (*fp)(int) = f);
476 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000478 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000479
480 // Look for the function declaration where the default argument was
481 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000482 for (FunctionDecl *Older = Old->getPreviousDecl();
483 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (!Older->getParamDecl(p)->hasDefaultArg())
485 break;
486
487 OldParam = Older->getParamDecl(p);
488 }
489
490 Diag(OldParam->getLocation(), diag::note_previous_definition)
491 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000492 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000493 // Merge the old default argument into the new parameter.
494 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000495 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000496 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000497 if (OldParam->hasUninstantiatedDefaultArg())
498 NewParam->setUninstantiatedDefaultArg(
499 OldParam->getUninstantiatedDefaultArg());
500 else
John McCall3d6c1782010-05-04 01:53:42 +0000501 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000502 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000503 if (New->getDescribedFunctionTemplate()) {
504 // Paragraph 4, quoted above, only applies to non-template functions.
505 Diag(NewParam->getLocation(),
506 diag::err_param_default_argument_template_redecl)
507 << NewParam->getDefaultArgRange();
508 Diag(Old->getLocation(), diag::note_template_prev_declaration)
509 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000510 } else if (New->getTemplateSpecializationKind()
511 != TSK_ImplicitInstantiation &&
512 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513 // C++ [temp.expr.spec]p21:
514 // Default function arguments shall not be specified in a declaration
515 // or a definition for one of the following explicit specializations:
516 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000517 // - the explicit specialization of a member function template;
518 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000519 // template where the class template specialization to which the
520 // member function specialization belongs is implicitly
521 // instantiated.
522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524 << New->getDeclName()
525 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000526 } else if (New->getDeclContext()->isDependentContext()) {
527 // C++ [dcl.fct.default]p6 (DR217):
528 // Default arguments for a member function of a class template shall
529 // be specified on the initial declaration of the member function
530 // within the class template.
531 //
532 // Reading the tea leaves a bit in DR217 and its reference to DR205
533 // leads me to the conclusion that one cannot add default function
534 // arguments for an out-of-line definition of a member function of a
535 // dependent type.
536 int WhichKind = 2;
537 if (CXXRecordDecl *Record
538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539 if (Record->getDescribedClassTemplate())
540 WhichKind = 0;
541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542 WhichKind = 1;
543 else
544 WhichKind = 2;
545 }
546
547 Diag(NewParam->getLocation(),
548 diag::err_param_default_argument_member_template_redecl)
549 << WhichKind
550 << NewParam->getDefaultArgRange();
551 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000552 }
553 }
554
Richard Smithb8abff62012-11-28 03:45:24 +0000555 // DR1344: If a default argument is added outside a class definition and that
556 // default argument makes the function a special member function, the program
557 // is ill-formed. This can only happen for constructors.
558 if (isa<CXXConstructorDecl>(New) &&
559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562 if (NewSM != OldSM) {
563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564 assert(NewParam->hasDefaultArg());
565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566 << NewParam->getDefaultArgRange() << NewSM;
567 Diag(Old->getLocation(), diag::note_previous_declaration);
568 }
569 }
570
Richard Smithff234882012-02-20 23:28:05 +0000571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000572 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000573 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000574 if (New->isConstexpr() != Old->isConstexpr()) {
575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576 << New << New->isConstexpr();
577 Diag(Old->getLocation(), diag::note_previous_declaration);
578 Invalid = true;
579 }
580
Douglas Gregore13ad832010-02-12 07:32:17 +0000581 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000582 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000583
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585}
586
Sebastian Redl60618fa2011-03-12 11:50:43 +0000587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 return;
596
597 assert(Context.hasSameType(New->getType(), Old->getType()) &&
598 "Should only be called if types are otherwise the same.");
599
600 QualType NewType = New->getType();
601 QualType OldType = Old->getType();
602
603 // We're only interested in pointers and references to functions, as well
604 // as pointers to member functions.
605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606 NewType = R->getPointeeType();
607 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609 NewType = P->getPointeeType();
610 OldType = OldType->getAs<PointerType>()->getPointeeType();
611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612 NewType = M->getPointeeType();
613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614 }
615
616 if (!NewType->isFunctionProtoType())
617 return;
618
619 // There's lots of special cases for functions. For function pointers, system
620 // libraries are hopefully not as broken so that we don't need these
621 // workarounds.
622 if (CheckEquivalentExceptionSpec(
623 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625 New->setInvalidDecl();
626 }
627}
628
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633 unsigned NumParams = FD->getNumParams();
634 unsigned p;
635
636 // Find first parameter with a default argument
637 for (p = 0; p < NumParams; ++p) {
638 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000639 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 break;
641 }
642
643 // C++ [dcl.fct.default]p4:
644 // In a given function declaration, all parameters
645 // subsequent to a parameter with a default argument shall
646 // have default arguments supplied in this or previous
647 // declarations. A default argument shall not be redefined
648 // by a later declaration (not even to the same value).
649 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000652 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000653 if (Param->isInvalidDecl())
654 /* We already complained about this parameter. */;
655 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000656 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000658 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 else
Mike Stump1eb44332009-09-09 15:08:12 +0000660 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 LastMissingDefaultArg = p;
664 }
665 }
666
667 if (LastMissingDefaultArg > 0) {
668 // Some default arguments were missing. Clear out all of the
669 // default arguments up to (and including) the last missing
670 // default argument, so that we leave the function parameters
671 // in a semantically valid state.
672 for (p = 0; p <= LastMissingDefaultArg; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000674 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000675 Param->setDefaultArg(0);
676 }
677 }
678 }
679}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000680
Richard Smith9f569cc2011-10-01 02:31:28 +0000681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 unsigned ArgIndex = 0;
687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691 SourceLocation ParamLoc = PD->getLocation();
692 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000694 diag::err_constexpr_non_literal_param,
695 ArgIndex+1, PD->getSourceRange(),
696 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000698 }
Joao Matos17d35c32012-08-31 22:18:20 +0000699 return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000708 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000709 case TTK_Struct: return 0;
710 case TTK_Interface: return 1;
711 case TTK_Class: return 2;
712 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000713 }
Joao Matos17d35c32012-08-31 22:18:20 +0000714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000719// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000720//
Richard Smith86c3ae42012-02-13 03:54:03 +0000721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 // C++11 [dcl.constexpr]p4:
726 // The definition of a constexpr constructor shall satisfy the following
727 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000729 const CXXRecordDecl *RD = MD->getParent();
730 if (RD->getNumVBases()) {
731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732 << isa<CXXConstructorDecl>(NewFD)
733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735 E = RD->vbases_end(); I != E; ++I)
736 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000737 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000738 return false;
739 }
Richard Smith35340502012-01-13 04:54:00 +0000740 }
741
742 if (!isa<CXXConstructorDecl>(NewFD)) {
743 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 // The definition of a constexpr function shall satisfy the following
745 // constraints:
746 // - it shall not be virtual;
747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000750
Richard Smith86c3ae42012-02-13 03:54:03 +0000751 // If it's not obvious why this function is virtual, find an overridden
752 // function which uses the 'virtual' keyword.
753 const CXXMethodDecl *WrittenVirtual = Method;
754 while (!WrittenVirtual->isVirtualAsWritten())
755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756 if (WrittenVirtual != Method)
757 Diag(WrittenVirtual->getLocation(),
758 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000759 return false;
760 }
761
762 // - its return type shall be a literal type;
763 QualType RT = NewFD->getResultType();
764 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000765 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000766 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000768 }
769
Richard Smith35340502012-01-13 04:54:00 +0000770 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000771 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000772 return false;
773
Richard Smith9f569cc2011-10-01 02:31:28 +0000774 return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000779///
Richard Smitha10b9782013-04-22 15:31:51 +0000780/// \return true if the body is OK (maybe only as an extension), false if we
781/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000783 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
786 // contain only
787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789 switch ((*DclIt)->getKind()) {
790 case Decl::StaticAssert:
791 case Decl::Using:
792 case Decl::UsingShadow:
793 case Decl::UsingDirective:
794 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000795 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 // - static_assert-declarations
797 // - using-declarations,
798 // - using-directives,
799 continue;
800
801 case Decl::Typedef:
802 case Decl::TypeAlias: {
803 // - typedef declarations and alias-declarations that do not define
804 // classes or enumerations,
805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807 // Don't allow variably-modified types in constexpr functions.
808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810 << TL.getSourceRange() << TL.getType()
811 << isa<CXXConstructorDecl>(Dcl);
812 return false;
813 }
814 continue;
815 }
816
817 case Decl::Enum:
818 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000819 // C++1y allows types to be defined, not just declared.
820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821 SemaRef.Diag(DS->getLocStart(),
822 SemaRef.getLangOpts().CPlusPlus1y
823 ? diag::warn_cxx11_compat_constexpr_type_definition
824 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000826 continue;
827
Richard Smitha10b9782013-04-22 15:31:51 +0000828 case Decl::EnumConstant:
829 case Decl::IndirectField:
830 case Decl::ParmVar:
831 // These can only appear with other declarations which are banned in
832 // C++11 and permitted in C++1y, so ignore them.
833 continue;
834
835 case Decl::Var: {
836 // C++1y [dcl.constexpr]p3 allows anything except:
837 // a definition of a variable of non-literal type or of static or
838 // thread storage duration or for which no initialization is performed.
839 VarDecl *VD = cast<VarDecl>(*DclIt);
840 if (VD->isThisDeclarationADefinition()) {
841 if (VD->isStaticLocal()) {
842 SemaRef.Diag(VD->getLocation(),
843 diag::err_constexpr_local_var_static)
844 << isa<CXXConstructorDecl>(Dcl)
845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846 return false;
847 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000848 if (!VD->getType()->isDependentType() &&
849 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000850 VD->getLocation(), VD->getType(),
851 diag::err_constexpr_local_var_non_literal_type,
852 isa<CXXConstructorDecl>(Dcl)))
853 return false;
854 if (!VD->hasInit()) {
855 SemaRef.Diag(VD->getLocation(),
856 diag::err_constexpr_local_var_no_init)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860 }
861 SemaRef.Diag(VD->getLocation(),
862 SemaRef.getLangOpts().CPlusPlus1y
863 ? diag::warn_cxx11_compat_constexpr_local_var
864 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000866 continue;
867 }
868
869 case Decl::NamespaceAlias:
870 case Decl::Function:
871 // These are disallowed in C++11 and permitted in C++1y. Allow them
872 // everywhere as an extension.
873 if (!Cxx1yLoc.isValid())
874 Cxx1yLoc = DS->getLocStart();
875 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000876
877 default:
878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882 }
883
884 return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891/// struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893/// indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896 const FunctionDecl *Dcl,
897 FieldDecl *Field,
898 llvm::SmallSet<Decl*, 16> &Inits,
899 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000900 if (Field->isUnnamedBitfield())
901 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000902
903 if (Field->isAnonymousStructOrUnion() &&
904 Field->getType()->getAsCXXRecordDecl()->isEmpty())
905 return;
906
Richard Smith9f569cc2011-10-01 02:31:28 +0000907 if (!Inits.count(Field)) {
908 if (!Diagnosed) {
909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910 Diagnosed = true;
911 }
912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913 } else if (Field->isAnonymousStructOrUnion()) {
914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916 I != E; ++I)
917 // If an anonymous union contains an anonymous struct of which any member
918 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000919 if (!RD->isUnion() || Inits.count(*I))
920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 }
922}
923
Richard Smitha10b9782013-04-22 15:31:51 +0000924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929 SourceLocation &Cxx1yLoc) {
930 // - its function-body shall be [...] a compound-statement that contains only
931 switch (S->getStmtClass()) {
932 case Stmt::NullStmtClass:
933 // - null statements,
934 return true;
935
936 case Stmt::DeclStmtClass:
937 // - static_assert-declarations
938 // - using-declarations,
939 // - using-directives,
940 // - typedef declarations and alias-declarations that do not define
941 // classes or enumerations,
942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943 return false;
944 return true;
945
946 case Stmt::ReturnStmtClass:
947 // - and exactly one return statement;
948 if (isa<CXXConstructorDecl>(Dcl)) {
949 // C++1y allows return statements in constexpr constructors.
950 if (!Cxx1yLoc.isValid())
951 Cxx1yLoc = S->getLocStart();
952 return true;
953 }
954
955 ReturnStmts.push_back(S->getLocStart());
956 return true;
957
958 case Stmt::CompoundStmtClass: {
959 // C++1y allows compound-statements.
960 if (!Cxx1yLoc.isValid())
961 Cxx1yLoc = S->getLocStart();
962
963 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967 Cxx1yLoc))
968 return false;
969 }
970 return true;
971 }
972
973 case Stmt::AttributedStmtClass:
974 if (!Cxx1yLoc.isValid())
975 Cxx1yLoc = S->getLocStart();
976 return true;
977
978 case Stmt::IfStmtClass: {
979 // C++1y allows if-statements.
980 if (!Cxx1yLoc.isValid())
981 Cxx1yLoc = S->getLocStart();
982
983 IfStmt *If = cast<IfStmt>(S);
984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985 Cxx1yLoc))
986 return false;
987 if (If->getElse() &&
988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989 Cxx1yLoc))
990 return false;
991 return true;
992 }
993
994 case Stmt::WhileStmtClass:
995 case Stmt::DoStmtClass:
996 case Stmt::ForStmtClass:
997 case Stmt::CXXForRangeStmtClass:
998 case Stmt::ContinueStmtClass:
999 // C++1y allows all of these. We don't allow them as extensions in C++11,
1000 // because they don't make sense without variable mutation.
1001 if (!SemaRef.getLangOpts().CPlusPlus1y)
1002 break;
1003 if (!Cxx1yLoc.isValid())
1004 Cxx1yLoc = S->getLocStart();
1005 for (Stmt::child_range Children = S->children(); Children; ++Children)
1006 if (*Children &&
1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008 Cxx1yLoc))
1009 return false;
1010 return true;
1011
1012 case Stmt::SwitchStmtClass:
1013 case Stmt::CaseStmtClass:
1014 case Stmt::DefaultStmtClass:
1015 case Stmt::BreakStmtClass:
1016 // C++1y allows switch-statements, and since they don't need variable
1017 // mutation, we can reasonably allow them in C++11 as an extension.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020 for (Stmt::child_range Children = S->children(); Children; ++Children)
1021 if (*Children &&
1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 return true;
1026
1027 default:
1028 if (!isa<Expr>(S))
1029 break;
1030
1031 // C++1y allows expression-statements.
1032 if (!Cxx1yLoc.isValid())
1033 Cxx1yLoc = S->getLocStart();
1034 return true;
1035 }
1036
1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038 << isa<CXXConstructorDecl>(Dcl);
1039 return false;
1040}
1041
Richard Smith9f569cc2011-10-01 02:31:28 +00001042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001047 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001048 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001049 // The definition of a constexpr function shall satisfy the following
1050 // constraints: [...]
1051 // - its function-body shall be = delete, = default, or a
1052 // compound-statement
1053 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001054 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001055 // In the definition of a constexpr constructor, [...]
1056 // - its function-body shall not be a function-try-block;
1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058 << isa<CXXConstructorDecl>(Dcl);
1059 return false;
1060 }
1061
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001062 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001063
1064 // - its function-body shall be [...] a compound-statement that contains only
1065 // [... list of cases ...]
1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001072 }
1073
Richard Smitha10b9782013-04-22 15:31:51 +00001074 if (Cxx1yLoc.isValid())
1075 Diag(Cxx1yLoc,
1076 getLangOpts().CPlusPlus1y
1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078 : diag::ext_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 if (const CXXConstructorDecl *Constructor
1082 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001084 // DR1359:
1085 // - every non-variant non-static data member and base class sub-object
1086 // shall be initialized;
1087 // - if the class is a non-empty union, or for each non-empty anonymous
1088 // union member of a non-union class, exactly one non-static data member
1089 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093 return false;
1094 }
Richard Smith6e433752011-10-10 16:38:04 +00001095 } else if (!Constructor->isDependentContext() &&
1096 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099 // Skip detailed checking if we have enough initializers, and we would
1100 // allow at most one initializer per member.
1101 bool AnyAnonStructUnionMembers = false;
1102 unsigned Fields = 0;
1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001105 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001106 AnyAnonStructUnionMembers = true;
1107 break;
1108 }
1109 }
1110 if (AnyAnonStructUnionMembers ||
1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112 // Check initialization of non-static data members. Base classes are
1113 // always initialized so do not need to be checked. Dependent bases
1114 // might not have initializers in the member initializer list.
1115 llvm::SmallSet<Decl*, 16> Inits;
1116 for (CXXConstructorDecl::init_const_iterator
1117 I = Constructor->init_begin(), E = Constructor->init_end();
1118 I != E; ++I) {
1119 if (FieldDecl *FD = (*I)->getMember())
1120 Inits.insert(FD);
1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122 Inits.insert(ID->chain_begin(), ID->chain_end());
1123 }
1124
1125 bool Diagnosed = false;
1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 if (Diagnosed)
1130 return false;
1131 }
1132 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001133 } else {
1134 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001135 // C++1y doesn't require constexpr functions to contain a 'return'
1136 // statement. We still do, unless the return type is void, because
1137 // otherwise if there's no return statement, the function cannot
1138 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001140 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142 : diag::err_constexpr_body_no_return);
1143 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001144 }
1145 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001146 Diag(ReturnStmts.back(),
1147 getLangOpts().CPlusPlus1y
1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001152 }
1153 }
1154
Richard Smith5ba73e12012-02-04 00:33:54 +00001155 // C++11 [dcl.constexpr]p5:
1156 // if no function argument values exist such that the function invocation
1157 // substitution would produce a constant expression, the program is
1158 // ill-formed; no diagnostic required.
1159 // C++11 [dcl.constexpr]p3:
1160 // - every constructor call and implicit conversion used in initializing the
1161 // return value shall be one of those allowed in a constant expression.
1162 // C++11 [dcl.constexpr]p4:
1163 // - every constructor involved in initializing non-static data members and
1164 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001165 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001168 << isa<CXXConstructorDecl>(Dcl);
1169 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001171 // Don't return false here: we allow this for compatibility in
1172 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001173 }
1174
Richard Smith9f569cc2011-10-01 02:31:28 +00001175 return true;
1176}
1177
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001184 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001185
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001186 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001187 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001188 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190 } else
1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001193 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001194 return &II == CurDecl->getIdentifier();
1195 else
1196 return false;
1197}
1198
Douglas Gregor229d47a2012-11-10 07:24:09 +00001199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202 const CXXRecordDecl *Current) {
1203 SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205 Class = Class->getCanonicalDecl();
1206 while (true) {
1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208 E = Current->bases_end();
1209 I != E; ++I) {
1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211 if (!Base)
1212 continue;
1213
1214 Base = Base->getDefinition();
1215 if (!Base)
1216 continue;
1217
1218 if (Base->getCanonicalDecl() == Class)
1219 return true;
1220
1221 Queue.push_back(Base);
1222 }
1223
1224 if (Queue.empty())
1225 return false;
1226
1227 Current = Queue.back();
1228 Queue.pop_back();
1229 }
1230
1231 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240 SourceRange SpecifierRange,
1241 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001242 TypeSourceInfo *TInfo,
1243 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001244 QualType BaseType = TInfo->getType();
1245
Douglas Gregor2943aed2009-03-03 04:44:36 +00001246 // C++ [class.union]p1:
1247 // A union shall not have base classes.
1248 if (Class->isUnion()) {
1249 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250 << SpecifierRange;
1251 return 0;
1252 }
1253
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001254 if (EllipsisLoc.isValid() &&
1255 !TInfo->getType()->containsUnexpandedParameterPack()) {
1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257 << TInfo->getTypeLoc().getSourceRange();
1258 EllipsisLoc = SourceLocation();
1259 }
Douglas Gregord777e282012-11-10 01:18:17 +00001260
1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263 if (BaseType->isDependentType()) {
1264 // Make sure that we don't have circular inheritance among our dependent
1265 // bases. For non-dependent bases, the check for completeness below handles
1266 // this.
1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001270 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001271 Diag(BaseLoc, diag::err_circular_inheritance)
1272 << BaseType << Context.getTypeDeclType(Class);
1273
1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276 << BaseType;
1277
1278 return 0;
1279 }
1280 }
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001283 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001284 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001285 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001286
1287 // Base specifiers must be record types.
1288 if (!BaseType->isRecordType()) {
1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290 return 0;
1291 }
1292
1293 // C++ [class.union]p1:
1294 // A union shall not be used as a base class.
1295 if (BaseType->isUnionType()) {
1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297 return 0;
1298 }
1299
1300 // C++ [class.derived]p2:
1301 // The class-name in a base-specifier shall not be an incompletely
1302 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001304 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001305 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 return 0;
John McCall572fc622010-08-17 07:23:57 +00001307 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001308
Eli Friedman1d954f62009-08-15 21:55:26 +00001309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001312 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer585bee42013-06-06 23:43:20 +00001314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001315 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001316
Anders Carlsson1d209272011-03-25 14:55:14 +00001317 // C++ [class]p3:
1318 // If a class is marked final and it appears as a base-type-specifier in
1319 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001320 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322 << CXXBaseDecl->getDeclName();
1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324 << CXXBaseDecl->getDeclName();
1325 return 0;
1326 }
1327
John McCall572fc622010-08-17 07:23:57 +00001328 if (BaseDecl->isInvalidDecl())
1329 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001330
1331 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001333 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001334 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001335}
1336
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// example:
1340/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001341/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001342BaseResult
John McCalld226f652010-08-21 09:40:31 +00001343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001344 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001345 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001346 ParsedType basetype, SourceLocation BaseLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001348 if (!classdecl)
1349 return true;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001353 if (!Class)
1354 return true;
1355
Richard Smith05321402013-02-19 23:47:15 +00001356 // We do not support any C++11 attributes on base-specifiers yet.
1357 // Diagnose any attributes we see.
1358 if (!Attributes.empty()) {
1359 for (AttributeList *Attr = Attributes.getList(); Attr;
1360 Attr = Attr->getNext()) {
1361 if (Attr->isInvalid() ||
1362 Attr->getKind() == AttributeList::IgnoredAttribute)
1363 continue;
1364 Diag(Attr->getLoc(),
1365 Attr->getKind() == AttributeList::UnknownAttribute
1366 ? diag::warn_unknown_attribute_ignored
1367 : diag::err_base_specifier_attribute)
1368 << Attr->getName();
1369 }
1370 }
1371
Nick Lewycky56062202010-07-26 16:56:01 +00001372 TypeSourceInfo *TInfo = 0;
1373 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001374
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001375 if (EllipsisLoc.isInvalid() &&
1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001377 UPPC_BaseType))
1378 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379
Douglas Gregor2943aed2009-03-03 04:44:36 +00001380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001381 Virtual, Access, TInfo,
1382 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001383 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001384 else
1385 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor2943aed2009-03-03 04:44:36 +00001387 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001388}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001389
Douglas Gregor2943aed2009-03-03 04:44:36 +00001390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393 unsigned NumBases) {
1394 if (NumBases == 0)
1395 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001396
1397 // Used to keep track of which base types we have already seen, so
1398 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001399 // that the key is always the unqualified canonical type of the base
1400 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001404 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001406 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001407 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001409 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001410
1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413 // C++ [class.mi]p3:
1414 // A class shall not be specified as a direct base class of a
1415 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001416 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001418 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001419 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001420
1421 // Delete the duplicate base class specifier; we're going to
1422 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001423 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424
1425 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 } else {
1427 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001428 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001429 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432 if (Class->isInterface() &&
1433 (!RD->isInterface() ||
1434 KnownBase->getAccessSpecifier() != AS_public)) {
1435 // The Microsoft extension __interface does not permit bases that
1436 // are not themselves public interfaces.
1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439 << RD->getSourceRange();
1440 Invalid = true;
1441 }
1442 if (RD->hasAttr<WeakAttr>())
1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 }
1446 }
1447
1448 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001449 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001450
1451 // Delete the remaining (good) base class specifiers, since their
1452 // data has been copied into the CXXRecordDecl.
1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001454 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001455
1456 return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001463 unsigned NumBases) {
1464 if (!ClassDecl || !Bases || !NumBases)
1465 return;
1466
1467 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001469 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001470}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001471
Douglas Gregora8f32e02009-10-06 17:59:45 +00001472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001476 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001477
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001479 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001480 return false;
1481
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001483 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001484 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001485
1486 // If either the base or the derived type is invalid, don't try to
1487 // check whether one is derived from the other.
1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489 return false;
1490
John McCall86ff3082010-02-04 22:26:26 +00001491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001498 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001499 return false;
1500
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001502 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001503 return false;
1504
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001506 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001507 return false;
1508
Douglas Gregora8f32e02009-10-06 17:59:45 +00001509 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001513 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001514 assert(BasePathArray.empty() && "Base path array must be empty!");
1515 assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517 const CXXBasePath &Path = Paths.front();
1518
1519 // We first go backward and check if we have a virtual base.
1520 // FIXME: It would be better if CXXBasePath had the base specifier for
1521 // the nearest virtual base.
1522 unsigned Start = 0;
1523 for (unsigned I = Path.size(); I != 0; --I) {
1524 if (Path[I - 1].Base->isVirtual()) {
1525 Start = I - 1;
1526 break;
1527 }
1528 }
1529
1530 // Now add all bases.
1531 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001533}
1534
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538 for (CXXCastPath::const_iterator B = BasePath.begin(),
1539 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001540 B != BEnd; ++B)
1541 if ((*B)->isVirtual())
1542 return true;
1543
1544 return false;
1545}
1546
Douglas Gregora8f32e02009-10-06 17:59:45 +00001547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001557 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 unsigned AmbigiousBaseConvID,
1559 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001560 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001561 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 // First, determine whether the path from Derived to Base is
1563 // ambiguous. This is slightly more expensive than checking whether
1564 // the Derived to Base conversion exists, because here we need to
1565 // explore multiple paths to determine if there is an ambiguity.
1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567 /*DetectVirtual=*/false);
1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569 assert(DerivationOkay &&
1570 "Can only be used with a derived-to-base conversion");
1571 (void)DerivationOkay;
1572
1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001574 if (InaccessibleBaseID) {
1575 // Check that the base class can be accessed.
1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577 InaccessibleBaseID)) {
1578 case AR_inaccessible:
1579 return true;
1580 case AR_accessible:
1581 case AR_dependent:
1582 case AR_delayed:
1583 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 }
John McCall6b2accb2010-02-10 09:31:12 +00001585 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586
1587 // Build a base path if necessary.
1588 if (BasePath)
1589 BuildBasePathArray(Paths, *BasePath);
1590 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001591 }
1592
1593 // We know that the derived-to-base conversion is ambiguous, and
1594 // we're going to produce a diagnostic. Perform the derived-to-base
1595 // search just one more time to compute all of the possible paths so
1596 // that we can print them out. This is more expensive than any of
1597 // the previous derived-to-base checks we've done, but at this point
1598 // performance isn't as much of an issue.
1599 Paths.clear();
1600 Paths.setRecordingPaths(true);
1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603 (void)StillOkay;
1604
1605 // Build up a textual representation of the ambiguous paths, e.g.,
1606 // D -> B -> A, that will be used to illustrate the ambiguous
1607 // conversions in the diagnostic. We only print one of the paths
1608 // to each base class subobject.
1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611 Diag(Loc, AmbigiousBaseConvID)
1612 << Derived << Base << PathDisplayStr << Range << Name;
1613 return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001618 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001619 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001621 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001622 IgnoreAccess ? 0
1623 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001625 Loc, Range, DeclarationName(),
1626 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643 std::string PathDisplayStr;
1644 std::set<unsigned> DisplayedPaths;
1645 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646 Path != Paths.end(); ++Path) {
1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648 // We haven't displayed a path to this particular base
1649 // class subobject yet.
1650 PathDisplayStr += "\n ";
1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652 for (CXXBasePath::const_iterator Element = Path->begin();
1653 Element != Path->end(); ++Element)
1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655 }
1656 }
1657
1658 return PathDisplayStr;
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
Abramo Bagnara6206d532010-06-05 05:09:32 +00001665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667 SourceLocation ASLoc,
1668 SourceLocation ColonLoc,
1669 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001672 ASLoc, ColonLoc);
1673 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001674 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001675}
1676
Richard Smitha4b39652012-08-06 03:25:17 +00001677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001679 if (D->isInvalidDecl())
1680 return;
1681
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001683
Richard Smitha4b39652012-08-06 03:25:17 +00001684 // Do we know which functions this declaration might be overriding?
1685 bool OverridesAreKnown = !MD ||
1686 (!MD->getParent()->hasAnyDependentBases() &&
1687 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001688
Richard Smitha4b39652012-08-06 03:25:17 +00001689 if (!MD || !MD->isVirtual()) {
1690 if (OverridesAreKnown) {
1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692 Diag(OA->getLocation(),
1693 diag::override_keyword_only_allowed_on_virtual_member_functions)
1694 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695 D->dropAttr<OverrideAttr>();
1696 }
1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698 Diag(FA->getLocation(),
1699 diag::override_keyword_only_allowed_on_virtual_member_functions)
1700 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701 D->dropAttr<FinalAttr>();
1702 }
1703 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001704 return;
1705 }
Richard Smitha4b39652012-08-06 03:25:17 +00001706
1707 if (!OverridesAreKnown)
1708 return;
1709
1710 // C++11 [class.virtual]p5:
1711 // If a virtual function is marked with the virt-specifier override and
1712 // does not override a member function of a base class, the program is
1713 // ill-formed.
1714 bool HasOverriddenMethods =
1715 MD->begin_overridden_methods() != MD->end_overridden_methods();
1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719}
1720
Richard Smitha4b39652012-08-06 03:25:17 +00001721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001722/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001723/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001726 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001727 return false;
1728
1729 Diag(New->getLocation(), diag::err_final_function_overridden)
1730 << New->getDeclName();
1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001733}
1734
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001735static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001736 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737 // FIXME: Destruction of ObjC lifetime types has side-effects.
1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739 return !RD->isCompleteDefinition() ||
1740 !RD->hasTrivialDefaultConstructor() ||
1741 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001742 return false;
1743}
1744
John McCall76da55d2013-04-16 07:28:30 +00001745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746 for (AttributeList* it = list; it != 0; it = it->getNext())
1747 if (it->isDeclspecPropertyAttribute())
1748 return it;
1749 return 0;
1750}
1751
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001757NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001759 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001760 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001761 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764 DeclarationName Name = NameInfo.getName();
1765 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001766
1767 // For anonymous bitfields, the location should point to the type.
1768 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001769 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001770
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001771 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772
John McCall4bde1e12010-06-04 08:34:12 +00001773 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001774 assert(!DS.isFriendSpecified());
1775
Richard Smith1ab0d902011-06-25 02:28:38 +00001776 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001777
John McCalle402e722012-09-25 07:32:39 +00001778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779 // The Microsoft extension __interface only permits public member functions
1780 // and prohibits constructors, destructors, operators, non-public member
1781 // functions, static methods and data members.
1782 unsigned InvalidDecl;
1783 bool ShowDeclName = true;
1784 if (!isFunc)
1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786 else if (AS != AS_public)
1787 InvalidDecl = 2;
1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789 InvalidDecl = 3;
1790 else switch (Name.getNameKind()) {
1791 case DeclarationName::CXXConstructorName:
1792 InvalidDecl = 4;
1793 ShowDeclName = false;
1794 break;
1795
1796 case DeclarationName::CXXDestructorName:
1797 InvalidDecl = 5;
1798 ShowDeclName = false;
1799 break;
1800
1801 case DeclarationName::CXXOperatorName:
1802 case DeclarationName::CXXConversionFunctionName:
1803 InvalidDecl = 6;
1804 break;
1805
1806 default:
1807 InvalidDecl = 0;
1808 break;
1809 }
1810
1811 if (InvalidDecl) {
1812 if (ShowDeclName)
1813 Diag(Loc, diag::err_invalid_member_in_interface)
1814 << (InvalidDecl-1) << Name;
1815 else
1816 Diag(Loc, diag::err_invalid_member_in_interface)
1817 << (InvalidDecl-1) << "";
1818 return 0;
1819 }
1820 }
1821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001822 // C++ 9.2p6: A member shall not be declared to have automatic storage
1823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825 // data members and cannot be applied to names declared const or static,
1826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001827 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001828 case DeclSpec::SCS_unspecified:
1829 case DeclSpec::SCS_typedef:
1830 case DeclSpec::SCS_static:
1831 break;
1832 case DeclSpec::SCS_mutable:
1833 if (isFunc) {
1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Richard Smithec642442013-04-12 22:46:28 +00001836 // FIXME: It would be nicer if the keyword was ignored only for this
1837 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001838 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001839 }
1840 break;
1841 default:
1842 Diag(DS.getStorageClassSpecLoc(),
1843 diag::err_storageclass_invalid_for_member);
1844 D.getMutableDeclSpec().ClearStorageClassSpecs();
1845 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001846 }
1847
Sebastian Redl669d5d72008-11-14 23:42:31 +00001848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001850 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001851
David Blaikie1d87fba2013-01-30 01:22:18 +00001852 if (DS.isConstexprSpecified() && isInstField) {
1853 SemaDiagnosticBuilder B =
1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856 if (InitStyle == ICIS_NoInit) {
1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858 D.getMutableDeclSpec().ClearConstexprSpec();
1859 const char *PrevSpec;
1860 unsigned DiagID;
1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001863 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001864 assert(!Failed && "Making a constexpr member const shouldn't fail");
1865 } else {
1866 B << 1;
1867 const char *PrevSpec;
1868 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001869 if (D.getMutableDeclSpec().SetStorageClassSpec(
1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001872 "This is the only DeclSpec that should fail to be applied");
1873 B << 1;
1874 } else {
1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876 isInstField = false;
1877 }
1878 }
1879 }
1880
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001881 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001882 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001884
1885 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001886 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001887 Diag(Loc, diag::err_bad_variable_name)
1888 << Name;
1889 return 0;
1890 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001891
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001892 IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
Douglas Gregorf2503652011-09-21 14:40:46 +00001894 // Member field could not be with "template" keyword.
1895 // So TemplateParameterLists should be empty in this case.
1896 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001897 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001898 if (TemplateParams->size()) {
1899 // There is no such thing as a member field template.
1900 Diag(D.getIdentifierLoc(), diag::err_template_member)
1901 << II
1902 << SourceRange(TemplateParams->getTemplateLoc(),
1903 TemplateParams->getRAngleLoc());
1904 } else {
1905 // There is an extraneous 'template<>' for this member.
1906 Diag(TemplateParams->getTemplateLoc(),
1907 diag::err_template_member_noparams)
1908 << II
1909 << SourceRange(TemplateParams->getTemplateLoc(),
1910 TemplateParams->getRAngleLoc());
1911 }
1912 return 0;
1913 }
1914
Douglas Gregor922fff22010-10-13 22:19:53 +00001915 if (SS.isSet() && !SS.isInvalid()) {
1916 // The user provided a superfluous scope specifier inside a class
1917 // definition:
1918 //
1919 // class X {
1920 // int X::member;
1921 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001922 if (DeclContext *DC = computeDeclContext(SS, false))
1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001924 else
1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001927
Douglas Gregor922fff22010-10-13 22:19:53 +00001928 SS.clear();
1929 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001930
John McCall76da55d2013-04-16 07:28:30 +00001931 AttributeList *MSPropertyAttr =
1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933 if (MSPropertyAttr) {
1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935 BitWidth, InitStyle, AS, MSPropertyAttr);
1936 isInstField = false;
1937 } else {
1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939 BitWidth, InitStyle, AS);
1940 }
Chris Lattner6f8ce142009-03-05 23:03:49 +00001941 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001942 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001944
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001945 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001946 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001947 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001948 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001949
1950 // Non-instance-fields can't have a bitfield.
1951 if (BitWidth) {
1952 if (Member->isInvalidDecl()) {
1953 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001954 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001955 // C++ 9.6p3: A bit-field shall not be a static member.
1956 // "static member 'A' cannot be a bit-field"
1957 Diag(Loc, diag::err_static_not_bitfield)
1958 << Name << BitWidth->getSourceRange();
1959 } else if (isa<TypedefDecl>(Member)) {
1960 // "typedef member 'x' cannot be a bit-field"
1961 Diag(Loc, diag::err_typedef_not_bitfield)
1962 << Name << BitWidth->getSourceRange();
1963 } else {
1964 // A function typedef ("typedef int f(); f a;").
1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001967 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001968 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner8b963ef2009-03-05 23:01:03 +00001971 BitWidth = 0;
1972 Member->setInvalidDecl();
1973 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001974
1975 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor37b372b2009-08-20 22:52:58 +00001977 // If we have declared a member function template, set the access of the
1978 // templated declaration as well.
1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001981 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001982
Richard Smitha4b39652012-08-06 03:25:17 +00001983 if (VS.isOverrideSpecified())
1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985 if (VS.isFinalSpecified())
1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001987
Douglas Gregorf5251602011-03-08 17:10:18 +00001988 if (VS.getLastLocation().isValid()) {
1989 // Update the end location of a method that has a virt-specifiers.
1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991 MD->setRangeEnd(VS.getLastLocation());
1992 }
Richard Smitha4b39652012-08-06 03:25:17 +00001993
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001994 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001995
Douglas Gregor10bd3682008-11-17 22:58:34 +00001996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001998 if (isInstField) {
1999 FieldDecl *FD = cast<FieldDecl>(Member);
2000 FieldCollector->Add(FD);
2001
2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003 FD->getLocation())
2004 != DiagnosticsEngine::Ignored) {
2005 // Remember all explicit private FieldDecls that have a name, no side
2006 // effects and are not part of a dependent type declaration.
2007 if (!FD->isImplicit() && FD->getDeclName() &&
2008 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002009 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002010 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002011 !InitializationHasSideEffects(*FD))
2012 UnusedPrivateFields.insert(FD);
2013 }
2014 }
2015
John McCalld226f652010-08-21 09:40:31 +00002016 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017}
2018
Hans Wennborg471f9852012-09-18 15:58:06 +00002019namespace {
2020 class UninitializedFieldVisitor
2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022 Sema &S;
2023 ValueDecl *VD;
2024 public:
2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002027 S(S) {
2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029 this->VD = IFD->getAnonField();
2030 else
2031 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002032 }
2033
2034 void HandleExpr(Expr *E) {
2035 if (!E) return;
2036
2037 // Expressions like x(x) sometimes lack the surrounding expressions
2038 // but need to be checked anyways.
2039 HandleValue(E);
2040 Visit(E);
2041 }
2042
2043 void HandleValue(Expr *E) {
2044 E = E->IgnoreParens();
2045
2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002048 return;
2049
2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051 // or union.
2052 MemberExpr *FieldME = ME;
2053
Hans Wennborg471f9852012-09-18 15:58:06 +00002054 Expr *Base = E;
2055 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 ME = cast<MemberExpr>(Base);
2057
2058 if (isa<VarDecl>(ME->getMemberDecl()))
2059 return;
2060
2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062 if (!FD->isAnonymousStructOrUnion())
2063 FieldME = ME;
2064
Hans Wennborg471f9852012-09-18 15:58:06 +00002065 Base = ME->getBase();
2066 }
2067
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002069 unsigned diag = VD->getType()->isReferenceType()
2070 ? diag::warn_reference_field_is_uninit
2071 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002072 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002073 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002074 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002075 }
2076
2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078 HandleValue(CO->getTrueExpr());
2079 HandleValue(CO->getFalseExpr());
2080 return;
2081 }
2082
2083 if (BinaryConditionalOperator *BCO =
2084 dyn_cast<BinaryConditionalOperator>(E)) {
2085 HandleValue(BCO->getCommon());
2086 HandleValue(BCO->getFalseExpr());
2087 return;
2088 }
2089
2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091 switch (BO->getOpcode()) {
2092 default:
2093 return;
2094 case(BO_PtrMemD):
2095 case(BO_PtrMemI):
2096 HandleValue(BO->getLHS());
2097 return;
2098 case(BO_Comma):
2099 HandleValue(BO->getRHS());
2100 return;
2101 }
2102 }
2103 }
2104
2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106 if (E->getCastKind() == CK_LValueToRValue)
2107 HandleValue(E->getSubExpr());
2108
2109 Inherited::VisitImplicitCastExpr(E);
2110 }
2111
2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113 Expr *Callee = E->getCallee();
2114 if (isa<MemberExpr>(Callee))
2115 HandleValue(Callee);
2116
2117 Inherited::VisitCXXMemberCallExpr(E);
2118 }
2119 };
2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121 ValueDecl *VD) {
2122 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123 }
2124} // namespace
2125
Richard Smith7a614d82011-06-11 17:19:42 +00002126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002130void
Richard Smithca523302012-06-10 03:12:00 +00002131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002132 Expr *InitExpr) {
2133 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002134 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002136
2137 if (!InitExpr) {
2138 FD->setInvalidDecl();
2139 FD->removeInClassInitializer();
2140 return;
2141 }
2142
Peter Collingbournefef21892011-10-23 18:59:44 +00002143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144 FD->setInvalidDecl();
2145 FD->removeInClassInitializer();
2146 return;
2147 }
2148
Hans Wennborg471f9852012-09-18 15:58:06 +00002149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150 != DiagnosticsEngine::Ignored) {
2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002156 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002157 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002158 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002159 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002160 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2161 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002162 if (Init.isInvalid()) {
2163 FD->setInvalidDecl();
2164 return;
2165 }
Richard Smith7a614d82011-06-11 17:19:42 +00002166 }
2167
Richard Smith41956372013-01-14 22:39:08 +00002168 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002169 // The initialization of each base and member constitutes a
2170 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002171 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002172 if (Init.isInvalid()) {
2173 FD->setInvalidDecl();
2174 return;
2175 }
2176
2177 InitExpr = Init.release();
2178
2179 FD->setInClassInitializer(InitExpr);
2180}
2181
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002182/// \brief Find the direct and/or virtual base specifiers that
2183/// correspond to the given base type, for use in base initialization
2184/// within a constructor.
2185static bool FindBaseInitializer(Sema &SemaRef,
2186 CXXRecordDecl *ClassDecl,
2187 QualType BaseType,
2188 const CXXBaseSpecifier *&DirectBaseSpec,
2189 const CXXBaseSpecifier *&VirtualBaseSpec) {
2190 // First, check for a direct base class.
2191 DirectBaseSpec = 0;
2192 for (CXXRecordDecl::base_class_const_iterator Base
2193 = ClassDecl->bases_begin();
2194 Base != ClassDecl->bases_end(); ++Base) {
2195 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2196 // We found a direct base of this type. That's what we're
2197 // initializing.
2198 DirectBaseSpec = &*Base;
2199 break;
2200 }
2201 }
2202
2203 // Check for a virtual base class.
2204 // FIXME: We might be able to short-circuit this if we know in advance that
2205 // there are no virtual bases.
2206 VirtualBaseSpec = 0;
2207 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2208 // We haven't found a base yet; search the class hierarchy for a
2209 // virtual base class.
2210 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2211 /*DetectVirtual=*/false);
2212 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2213 BaseType, Paths)) {
2214 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2215 Path != Paths.end(); ++Path) {
2216 if (Path->back().Base->isVirtual()) {
2217 VirtualBaseSpec = Path->back().Base;
2218 break;
2219 }
2220 }
2221 }
2222 }
2223
2224 return DirectBaseSpec || VirtualBaseSpec;
2225}
2226
Sebastian Redl6df65482011-09-24 17:48:25 +00002227/// \brief Handle a C++ member initializer using braced-init-list syntax.
2228MemInitResult
2229Sema::ActOnMemInitializer(Decl *ConstructorD,
2230 Scope *S,
2231 CXXScopeSpec &SS,
2232 IdentifierInfo *MemberOrBase,
2233 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002234 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002235 SourceLocation IdLoc,
2236 Expr *InitList,
2237 SourceLocation EllipsisLoc) {
2238 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002239 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002240 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002241}
2242
2243/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002244MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002245Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002246 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002247 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002248 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002249 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002250 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002251 SourceLocation IdLoc,
2252 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002253 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002254 SourceLocation RParenLoc,
2255 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002256 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002257 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002258 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002259 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002260}
2261
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002262namespace {
2263
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002264// Callback to only accept typo corrections that can be a valid C++ member
2265// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002266class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2267 public:
2268 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2269 : ClassDecl(ClassDecl) {}
2270
2271 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2272 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2273 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2274 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2275 else
2276 return isa<TypeDecl>(ND);
2277 }
2278 return false;
2279 }
2280
2281 private:
2282 CXXRecordDecl *ClassDecl;
2283};
2284
2285}
2286
Sebastian Redl6df65482011-09-24 17:48:25 +00002287/// \brief Handle a C++ member initializer.
2288MemInitResult
2289Sema::BuildMemInitializer(Decl *ConstructorD,
2290 Scope *S,
2291 CXXScopeSpec &SS,
2292 IdentifierInfo *MemberOrBase,
2293 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002294 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002295 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002296 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002297 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002298 if (!ConstructorD)
2299 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002301 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002302
2303 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002304 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002305 if (!Constructor) {
2306 // The user wrote a constructor initializer on a function that is
2307 // not a C++ constructor. Ignore the error for now, because we may
2308 // have more member initializers coming; we'll diagnose it just
2309 // once in ActOnMemInitializers.
2310 return true;
2311 }
2312
2313 CXXRecordDecl *ClassDecl = Constructor->getParent();
2314
2315 // C++ [class.base.init]p2:
2316 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002317 // constructor's class and, if not found in that scope, are looked
2318 // up in the scope containing the constructor's definition.
2319 // [Note: if the constructor's class contains a member with the
2320 // same name as a direct or virtual base class of the class, a
2321 // mem-initializer-id naming the member or base class and composed
2322 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002323 // mem-initializer-id for the hidden base class may be specified
2324 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002325 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002326 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002327 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002328 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002329 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002330 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002331 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2332 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002333 if (EllipsisLoc.isValid())
2334 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002335 << MemberOrBase
2336 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002337
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002338 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002339 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002340 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002341 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002342 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002343 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002344 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002345
2346 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002347 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002348 } else if (DS.getTypeSpecType() == TST_decltype) {
2349 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002350 } else {
2351 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2352 LookupParsedName(R, S, &SS);
2353
2354 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2355 if (!TyD) {
2356 if (R.isAmbiguous()) return true;
2357
John McCallfd225442010-04-09 19:01:14 +00002358 // We don't want access-control diagnostics here.
2359 R.suppressDiagnostics();
2360
Douglas Gregor7a886e12010-01-19 06:46:48 +00002361 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2362 bool NotUnknownSpecialization = false;
2363 DeclContext *DC = computeDeclContext(SS, false);
2364 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2365 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2366
2367 if (!NotUnknownSpecialization) {
2368 // When the scope specifier can refer to a member of an unknown
2369 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002370 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2371 SS.getWithLocInContext(Context),
2372 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002373 if (BaseType.isNull())
2374 return true;
2375
Douglas Gregor7a886e12010-01-19 06:46:48 +00002376 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002377 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002378 }
2379 }
2380
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002381 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002382 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002383 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002384 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002385 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002386 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002387 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2388 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002389 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002390 // We have found a non-static data member with a similar
2391 // name to what was typed; complain and initialize that
2392 // member.
2393 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2394 << MemberOrBase << true << CorrectedQuotedStr
2395 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2396 Diag(Member->getLocation(), diag::note_previous_decl)
2397 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002398
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002399 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002400 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002401 const CXXBaseSpecifier *DirectBaseSpec;
2402 const CXXBaseSpecifier *VirtualBaseSpec;
2403 if (FindBaseInitializer(*this, ClassDecl,
2404 Context.getTypeDeclType(Type),
2405 DirectBaseSpec, VirtualBaseSpec)) {
2406 // We have found a direct or virtual base class with a
2407 // similar name to what was typed; complain and initialize
2408 // that base class.
2409 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002410 << MemberOrBase << false << CorrectedQuotedStr
2411 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002412
2413 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2414 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002415 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002416 diag::note_base_class_specified_here)
2417 << BaseSpec->getType()
2418 << BaseSpec->getSourceRange();
2419
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002420 TyD = Type;
2421 }
2422 }
2423 }
2424
Douglas Gregor7a886e12010-01-19 06:46:48 +00002425 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002426 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002427 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002428 return true;
2429 }
John McCall2b194412009-12-21 10:41:20 +00002430 }
2431
Douglas Gregor7a886e12010-01-19 06:46:48 +00002432 if (BaseType.isNull()) {
2433 BaseType = Context.getTypeDeclType(TyD);
2434 if (SS.isSet()) {
2435 NestedNameSpecifier *Qualifier =
2436 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002437
Douglas Gregor7a886e12010-01-19 06:46:48 +00002438 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002439 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002440 }
John McCall2b194412009-12-21 10:41:20 +00002441 }
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCalla93c9342009-12-07 02:54:59 +00002444 if (!TInfo)
2445 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002446
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002447 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002448}
2449
Chandler Carruth81c64772011-09-03 01:14:15 +00002450/// Checks a member initializer expression for cases where reference (or
2451/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002452static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2453 Expr *Init,
2454 SourceLocation IdLoc) {
2455 QualType MemberTy = Member->getType();
2456
2457 // We only handle pointers and references currently.
2458 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2459 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2460 return;
2461
2462 const bool IsPointer = MemberTy->isPointerType();
2463 if (IsPointer) {
2464 if (const UnaryOperator *Op
2465 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2466 // The only case we're worried about with pointers requires taking the
2467 // address.
2468 if (Op->getOpcode() != UO_AddrOf)
2469 return;
2470
2471 Init = Op->getSubExpr();
2472 } else {
2473 // We only handle address-of expression initializers for pointers.
2474 return;
2475 }
2476 }
2477
Richard Smitha4bb99c2013-06-12 21:51:50 +00002478 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002479 // We only warn when referring to a non-reference parameter declaration.
2480 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2481 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002482 return;
2483
2484 S.Diag(Init->getExprLoc(),
2485 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2486 : diag::warn_bind_ref_member_to_parameter)
2487 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002488 } else {
2489 // Other initializers are fine.
2490 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002491 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002492
2493 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2494 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002495}
2496
John McCallf312b1e2010-08-26 23:41:50 +00002497MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002498Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002499 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002500 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2501 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2502 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002503 "Member must be a FieldDecl or IndirectFieldDecl");
2504
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002505 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002506 return true;
2507
Douglas Gregor464b2f02010-11-05 22:21:31 +00002508 if (Member->isInvalidDecl())
2509 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002510
John McCallb4190042009-11-04 23:02:40 +00002511 // Diagnose value-uses of fields to initialize themselves, e.g.
2512 // foo(foo)
2513 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002514 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002515 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002516 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002517 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002518 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002519 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002520 } else {
2521 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002522 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002523 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002524
Richard Trieude5e75c2012-06-14 23:11:34 +00002525 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2526 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002527 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002528 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002529 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002530 // initializing the i'th field, throw a warning if any of the >= i'th
2531 // fields are used, as they are not yet initialized.
2532 // Right now we are only handling the case where the i'th field uses
2533 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002534 // Also need to take into account that some fields may be initialized by
2535 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002536 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002537
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002538 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002539
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002540 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002541 // Can't check initialization for a member of dependent type or when
2542 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002543 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002544 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002545 bool InitList = false;
2546 if (isa<InitListExpr>(Init)) {
2547 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002548 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002549 }
2550
Chandler Carruth894aed92010-12-06 09:23:57 +00002551 // Initialize the member.
2552 InitializedEntity MemberEntity =
2553 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2554 : InitializedEntity::InitializeMember(IndirectMember, 0);
2555 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002556 InitList ? InitializationKind::CreateDirectList(IdLoc)
2557 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2558 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002559
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002560 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2561 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002562 if (MemberInit.isInvalid())
2563 return true;
2564
Richard Smith8a07cd32013-06-12 20:42:33 +00002565 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2566
Richard Smith41956372013-01-14 22:39:08 +00002567 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002568 // The initialization of each base and member constitutes a
2569 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002570 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002571 if (MemberInit.isInvalid())
2572 return true;
2573
Richard Smithc83c2302012-12-19 01:39:02 +00002574 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002575 }
2576
Chandler Carruth894aed92010-12-06 09:23:57 +00002577 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002578 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2579 InitRange.getBegin(), Init,
2580 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002581 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2583 InitRange.getBegin(), Init,
2584 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002585 }
Eli Friedman59c04372009-07-29 19:44:27 +00002586}
2587
John McCallf312b1e2010-08-26 23:41:50 +00002588MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002589Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002590 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002591 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002592 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002593 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002594 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002595 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002596
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002597 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002598 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2600 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002601 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002602 }
2603
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002605 // Initialize the object.
2606 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2607 QualType(ClassDecl->getTypeForDecl(), 0));
2608 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002609 InitList ? InitializationKind::CreateDirectList(NameLoc)
2610 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2611 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002612 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002613 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002614 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002615 if (DelegationInit.isInvalid())
2616 return true;
2617
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002618 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2619 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002620
Richard Smith41956372013-01-14 22:39:08 +00002621 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002622 // The initialization of each base and member constitutes a
2623 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002624 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2625 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002626 if (DelegationInit.isInvalid())
2627 return true;
2628
Eli Friedmand21016f2012-05-19 23:35:23 +00002629 // If we are in a dependent context, template instantiation will
2630 // perform this type-checking again. Just save the arguments that we
2631 // received in a ParenListExpr.
2632 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2633 // of the information that we have about the base
2634 // initializer. However, deconstructing the ASTs is a dicey process,
2635 // and this approach is far more likely to get the corner cases right.
2636 if (CurContext->isDependentContext())
2637 DelegationInit = Owned(Init);
2638
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002640 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002642}
2643
2644MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002645Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002646 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002647 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002648 SourceLocation BaseLoc
2649 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002650
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002651 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2652 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2653 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2654
2655 // C++ [class.base.init]p2:
2656 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002657 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002658 // of that class, the mem-initializer is ill-formed. A
2659 // mem-initializer-list can initialize a base class using any
2660 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002661 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002662
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002664 if (EllipsisLoc.isValid()) {
2665 // This is a pack expansion.
2666 if (!BaseType->containsUnexpandedParameterPack()) {
2667 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002668 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002669
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002670 EllipsisLoc = SourceLocation();
2671 }
2672 } else {
2673 // Check for any unexpanded parameter packs.
2674 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2675 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002676
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002677 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002678 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002679 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002680
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002681 // Check for direct and virtual base classes.
2682 const CXXBaseSpecifier *DirectBaseSpec = 0;
2683 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2684 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002685 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2686 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002687 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002688
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002689 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2690 VirtualBaseSpec);
2691
2692 // C++ [base.class.init]p2:
2693 // Unless the mem-initializer-id names a nonstatic data member of the
2694 // constructor's class or a direct or virtual base of that class, the
2695 // mem-initializer is ill-formed.
2696 if (!DirectBaseSpec && !VirtualBaseSpec) {
2697 // If the class has any dependent bases, then it's possible that
2698 // one of those types will resolve to the same type as
2699 // BaseType. Therefore, just treat this as a dependent base
2700 // class initialization. FIXME: Should we try to check the
2701 // initialization anyway? It seems odd.
2702 if (ClassDecl->hasAnyDependentBases())
2703 Dependent = true;
2704 else
2705 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2706 << BaseType << Context.getTypeDeclType(ClassDecl)
2707 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2708 }
2709 }
2710
2711 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002712 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Sebastian Redl6df65482011-09-24 17:48:25 +00002714 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2715 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002716 InitRange.getBegin(), Init,
2717 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002718 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002719
2720 // C++ [base.class.init]p2:
2721 // If a mem-initializer-id is ambiguous because it designates both
2722 // a direct non-virtual base class and an inherited virtual base
2723 // class, the mem-initializer is ill-formed.
2724 if (DirectBaseSpec && VirtualBaseSpec)
2725 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002726 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002727
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002728 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002729 if (!BaseSpec)
2730 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2731
2732 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002733 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002734 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002735 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002736 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002737 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002738 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002739
2740 InitializedEntity BaseEntity =
2741 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2742 InitializationKind Kind =
2743 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2744 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2745 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002746 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2747 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002748 if (BaseInit.isInvalid())
2749 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002750
Richard Smith41956372013-01-14 22:39:08 +00002751 // C++11 [class.base.init]p7:
2752 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002753 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002754 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755 if (BaseInit.isInvalid())
2756 return true;
2757
2758 // If we are in a dependent context, template instantiation will
2759 // perform this type-checking again. Just save the arguments that we
2760 // received in a ParenListExpr.
2761 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2762 // of the information that we have about the base
2763 // initializer. However, deconstructing the ASTs is a dicey process,
2764 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002765 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002766 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002767
Sean Huntcbb67482011-01-08 20:30:50 +00002768 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002769 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002770 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002771 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002772 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002773}
2774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002776static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2777 if (T.isNull()) T = E->getType();
2778 QualType TargetType = SemaRef.BuildReferenceType(
2779 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002780 SourceLocation ExprLoc = E->getLocStart();
2781 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2782 TargetType, ExprLoc);
2783
2784 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2785 SourceRange(ExprLoc, ExprLoc),
2786 E->getSourceRange()).take();
2787}
2788
Anders Carlssone5ef7402010-04-23 03:10:23 +00002789/// ImplicitInitializerKind - How an implicit base or member initializer should
2790/// initialize its base or member.
2791enum ImplicitInitializerKind {
2792 IIK_Default,
2793 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002794 IIK_Move,
2795 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002796};
2797
Anders Carlssondefefd22010-04-23 02:00:02 +00002798static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002799BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002800 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002801 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002802 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002803 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002804 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002805 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2806 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002807
John McCall60d7b3a2010-08-24 06:29:42 +00002808 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002809
2810 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002811 case IIK_Inherit: {
2812 const CXXRecordDecl *Inherited =
2813 Constructor->getInheritedConstructor()->getParent();
2814 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2815 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2816 // C++11 [class.inhctor]p8:
2817 // Each expression in the expression-list is of the form
2818 // static_cast<T&&>(p), where p is the name of the corresponding
2819 // constructor parameter and T is the declared type of p.
2820 SmallVector<Expr*, 16> Args;
2821 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2822 ParmVarDecl *PD = Constructor->getParamDecl(I);
2823 ExprResult ArgExpr =
2824 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2825 VK_LValue, SourceLocation());
2826 if (ArgExpr.isInvalid())
2827 return true;
2828 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2829 }
2830
2831 InitializationKind InitKind = InitializationKind::CreateDirect(
2832 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002833 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002834 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2835 break;
2836 }
2837 }
2838 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002839 case IIK_Default: {
2840 InitializationKind InitKind
2841 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002842 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2843 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002844 break;
2845 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002846
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002847 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002848 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002849 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002850 ParmVarDecl *Param = Constructor->getParamDecl(0);
2851 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002852
Anders Carlssone5ef7402010-04-23 03:10:23 +00002853 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002854 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002855 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002856 Constructor->getLocation(), ParamType,
2857 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002858
Eli Friedman5f2987c2012-02-02 03:46:19 +00002859 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2860
Anders Carlssonc7957502010-04-24 22:02:54 +00002861 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002862 QualType ArgTy =
2863 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2864 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002865
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002866 if (Moving) {
2867 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2868 }
2869
John McCallf871d0c2010-08-07 06:22:56 +00002870 CXXCastPath BasePath;
2871 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002872 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2873 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002874 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002875 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002876
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 InitializationKind InitKind
2878 = InitializationKind::CreateDirect(Constructor->getLocation(),
2879 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002880 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2881 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002882 break;
2883 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002884 }
John McCall9ae2f072010-08-23 23:25:46 +00002885
Douglas Gregor53c374f2010-12-07 00:41:46 +00002886 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002887 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002888 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002889
Anders Carlssondefefd22010-04-23 02:00:02 +00002890 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002891 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002892 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2893 SourceLocation()),
2894 BaseSpec->isVirtual(),
2895 SourceLocation(),
2896 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002897 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002898 SourceLocation());
2899
Anders Carlssondefefd22010-04-23 02:00:02 +00002900 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002901}
2902
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002903static bool RefersToRValueRef(Expr *MemRef) {
2904 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2905 return Referenced->getType()->isRValueReferenceType();
2906}
2907
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002908static bool
2909BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002910 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002911 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002912 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002913 if (Field->isInvalidDecl())
2914 return true;
2915
Chandler Carruthf186b542010-06-29 23:50:44 +00002916 SourceLocation Loc = Constructor->getLocation();
2917
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002918 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2919 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002920 ParmVarDecl *Param = Constructor->getParamDecl(0);
2921 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002922
2923 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002924 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2925 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002926
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002927 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002928 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002929 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002930 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002931
Eli Friedman5f2987c2012-02-02 03:46:19 +00002932 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2933
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002934 if (Moving) {
2935 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2936 }
2937
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002938 // Build a reference to this field within the parameter.
2939 CXXScopeSpec SS;
2940 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2941 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002942 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2943 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002944 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002945 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002946 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002947 ParamType, Loc,
2948 /*IsArrow=*/false,
2949 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002950 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002951 /*FirstQualifierInScope=*/0,
2952 MemberLookup,
2953 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002954 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002955 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002956
2957 // C++11 [class.copy]p15:
2958 // - if a member m has rvalue reference type T&&, it is direct-initialized
2959 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002960 if (RefersToRValueRef(CtorArg.get())) {
2961 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002962 }
2963
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002964 // When the field we are copying is an array, create index variables for
2965 // each dimension of the array. We use these index variables to subscript
2966 // the source array, and other clients (e.g., CodeGen) will perform the
2967 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002968 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002969 QualType BaseType = Field->getType();
2970 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002971 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002972 while (const ConstantArrayType *Array
2973 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002974 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002975 // Create the iteration variable for this array index.
2976 IdentifierInfo *IterationVarName = 0;
2977 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002978 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002979 llvm::raw_svector_ostream OS(Str);
2980 OS << "__i" << IndexVariables.size();
2981 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2982 }
2983 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002984 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002985 IterationVarName, SizeType,
2986 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002987 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002988 IndexVariables.push_back(IterationVar);
2989
2990 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002991 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002992 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002993 assert(!IterationVarRef.isInvalid() &&
2994 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002995 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2996 assert(!IterationVarRef.isInvalid() &&
2997 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002998
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002999 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003000 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003001 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003002 Loc);
3003 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003004 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003005
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003006 BaseType = Array->getElementType();
3007 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003008
3009 // The array subscript expression is an lvalue, which is wrong for moving.
3010 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003011 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003012
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003013 // Construct the entity that we will be initializing. For an array, this
3014 // will be first element in the array, which may require several levels
3015 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003016 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003017 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003018 if (Indirect)
3019 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3020 else
3021 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003022 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3023 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3024 0,
3025 Entities.back()));
3026
3027 // Direct-initialize to use the copy constructor.
3028 InitializationKind InitKind =
3029 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3030
Sebastian Redl74e611a2011-09-04 18:14:28 +00003031 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003032 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003033
John McCall60d7b3a2010-08-24 06:29:42 +00003034 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003035 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003036 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003037 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003038 if (MemberInit.isInvalid())
3039 return true;
3040
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003041 if (Indirect) {
3042 assert(IndexVariables.size() == 0 &&
3043 "Indirect field improperly initialized");
3044 CXXMemberInit
3045 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3046 Loc, Loc,
3047 MemberInit.takeAs<Expr>(),
3048 Loc);
3049 } else
3050 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3051 Loc, MemberInit.takeAs<Expr>(),
3052 Loc,
3053 IndexVariables.data(),
3054 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003055 return false;
3056 }
3057
Richard Smith07b0fdc2013-03-18 21:12:30 +00003058 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3059 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003060
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003061 QualType FieldBaseElementType =
3062 SemaRef.Context.getBaseElementType(Field->getType());
3063
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003064 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003065 InitializedEntity InitEntity
3066 = Indirect? InitializedEntity::InitializeMember(Indirect)
3067 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003068 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003069 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003070
3071 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3072 ExprResult MemberInit =
3073 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003074
Douglas Gregor53c374f2010-12-07 00:41:46 +00003075 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003076 if (MemberInit.isInvalid())
3077 return true;
3078
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003079 if (Indirect)
3080 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3081 Indirect, Loc,
3082 Loc,
3083 MemberInit.get(),
3084 Loc);
3085 else
3086 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3087 Field, Loc, Loc,
3088 MemberInit.get(),
3089 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003090 return false;
3091 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003092
Sean Hunt1f2f3842011-05-17 00:19:05 +00003093 if (!Field->getParent()->isUnion()) {
3094 if (FieldBaseElementType->isReferenceType()) {
3095 SemaRef.Diag(Constructor->getLocation(),
3096 diag::err_uninitialized_member_in_ctor)
3097 << (int)Constructor->isImplicit()
3098 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3099 << 0 << Field->getDeclName();
3100 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3101 return true;
3102 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003103
Sean Hunt1f2f3842011-05-17 00:19:05 +00003104 if (FieldBaseElementType.isConstQualified()) {
3105 SemaRef.Diag(Constructor->getLocation(),
3106 diag::err_uninitialized_member_in_ctor)
3107 << (int)Constructor->isImplicit()
3108 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3109 << 1 << Field->getDeclName();
3110 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3111 return true;
3112 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003113 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003114
David Blaikie4e4d0842012-03-11 07:00:24 +00003115 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003116 FieldBaseElementType->isObjCRetainableType() &&
3117 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3118 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003119 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003120 // Default-initialize Objective-C pointers to NULL.
3121 CXXMemberInit
3122 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3123 Loc, Loc,
3124 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3125 Loc);
3126 return false;
3127 }
3128
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003129 // Nothing to initialize.
3130 CXXMemberInit = 0;
3131 return false;
3132}
John McCallf1860e52010-05-20 23:23:51 +00003133
3134namespace {
3135struct BaseAndFieldInfo {
3136 Sema &S;
3137 CXXConstructorDecl *Ctor;
3138 bool AnyErrorsInInits;
3139 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003140 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003141 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003142
3143 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3144 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003145 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3146 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003147 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003148 else if (Generated && Ctor->isMoveConstructor())
3149 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003150 else if (Ctor->getInheritedConstructor())
3151 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003152 else
3153 IIK = IIK_Default;
3154 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003155
3156 bool isImplicitCopyOrMove() const {
3157 switch (IIK) {
3158 case IIK_Copy:
3159 case IIK_Move:
3160 return true;
3161
3162 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003163 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003164 return false;
3165 }
David Blaikie30263482012-01-20 21:50:17 +00003166
3167 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003168 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003169
3170 bool addFieldInitializer(CXXCtorInitializer *Init) {
3171 AllToInit.push_back(Init);
3172
3173 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003174 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003175 S.UnusedPrivateFields.remove(Init->getAnyMember());
3176
3177 return false;
3178 }
John McCallf1860e52010-05-20 23:23:51 +00003179};
3180}
3181
Richard Smitha4950662011-09-19 13:34:43 +00003182/// \brief Determine whether the given indirect field declaration is somewhere
3183/// within an anonymous union.
3184static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3185 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3186 CEnd = F->chain_end();
3187 C != CEnd; ++C)
3188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3189 if (Record->isUnion())
3190 return true;
3191
3192 return false;
3193}
3194
Douglas Gregorddb21472011-11-02 23:04:16 +00003195/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3196/// array type.
3197static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3198 if (T->isIncompleteArrayType())
3199 return true;
3200
3201 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3202 if (!ArrayT->getSize())
3203 return true;
3204
3205 T = ArrayT->getElementType();
3206 }
3207
3208 return false;
3209}
3210
Richard Smith7a614d82011-06-11 17:19:42 +00003211static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003212 FieldDecl *Field,
3213 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003214
Chandler Carruthe861c602010-06-30 02:59:29 +00003215 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003216 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3217 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003218
Richard Smith0b8220a2012-08-07 21:30:42 +00003219 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003220 // has a brace-or-equal-initializer, the entity is initialized as specified
3221 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003222 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003223 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3224 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003225 CXXCtorInitializer *Init;
3226 if (Indirect)
3227 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3228 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003229 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003230 SourceLocation());
3231 else
3232 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3233 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003234 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003235 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003236 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003237 }
3238
Richard Smithc115f632011-09-18 11:14:50 +00003239 // Don't build an implicit initializer for union members if none was
3240 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003241 if (Field->getParent()->isUnion() ||
3242 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003243 return false;
3244
Douglas Gregorddb21472011-11-02 23:04:16 +00003245 // Don't initialize incomplete or zero-length arrays.
3246 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3247 return false;
3248
John McCallf1860e52010-05-20 23:23:51 +00003249 // Don't try to build an implicit initializer if there were semantic
3250 // errors in any of the initializers (and therefore we might be
3251 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003252 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003253 return false;
3254
Sean Huntcbb67482011-01-08 20:30:50 +00003255 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003256 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3257 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003258 return true;
John McCallf1860e52010-05-20 23:23:51 +00003259
Richard Smith0b8220a2012-08-07 21:30:42 +00003260 if (!Init)
3261 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003262
Richard Smith0b8220a2012-08-07 21:30:42 +00003263 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003264}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003265
3266bool
3267Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3268 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003269 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003270 Constructor->setNumCtorInitializers(1);
3271 CXXCtorInitializer **initializer =
3272 new (Context) CXXCtorInitializer*[1];
3273 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3274 Constructor->setCtorInitializers(initializer);
3275
Sean Huntb76af9c2011-05-03 23:05:34 +00003276 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003277 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003278 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3279 }
3280
Sean Huntc1598702011-05-05 00:05:47 +00003281 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003282
Sean Hunt059ce0d2011-05-01 07:04:31 +00003283 return false;
3284}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003285
David Blaikie93c86172013-01-17 05:26:25 +00003286bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3287 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003288 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003289 // Just store the initializers as written, they will be checked during
3290 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003291 if (!Initializers.empty()) {
3292 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003293 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003294 new (Context) CXXCtorInitializer*[Initializers.size()];
3295 memcpy(baseOrMemberInitializers, Initializers.data(),
3296 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003297 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003298 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003299
3300 // Let template instantiation know whether we had errors.
3301 if (AnyErrors)
3302 Constructor->setInvalidDecl();
3303
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003304 return false;
3305 }
3306
John McCallf1860e52010-05-20 23:23:51 +00003307 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003308
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003309 // We need to build the initializer AST according to order of construction
3310 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003311 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003312 if (!ClassDecl)
3313 return true;
3314
Eli Friedman80c30da2009-11-09 19:20:36 +00003315 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003316
David Blaikie93c86172013-01-17 05:26:25 +00003317 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003318 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003319
3320 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003321 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003322 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003323 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003324 }
3325
Anders Carlsson711f34a2010-04-21 19:52:01 +00003326 // Keep track of the direct virtual bases.
3327 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3328 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3329 E = ClassDecl->bases_end(); I != E; ++I) {
3330 if (I->isVirtual())
3331 DirectVBases.insert(I);
3332 }
3333
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003334 // Push virtual bases before others.
3335 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3336 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3337
Sean Huntcbb67482011-01-08 20:30:50 +00003338 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003339 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3340 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003341 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003342 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003343 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003344 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003345 VBase, IsInheritedVirtualBase,
3346 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003347 HadError = true;
3348 continue;
3349 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003350
John McCallf1860e52010-05-20 23:23:51 +00003351 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003352 }
3353 }
Mike Stump1eb44332009-09-09 15:08:12 +00003354
John McCallf1860e52010-05-20 23:23:51 +00003355 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003356 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3357 E = ClassDecl->bases_end(); Base != E; ++Base) {
3358 // Virtuals are in the virtual base list and already constructed.
3359 if (Base->isVirtual())
3360 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003361
Sean Huntcbb67482011-01-08 20:30:50 +00003362 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003363 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3364 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003365 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003366 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003367 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003368 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003369 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003370 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003371 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003372 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003373
John McCallf1860e52010-05-20 23:23:51 +00003374 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003375 }
3376 }
Mike Stump1eb44332009-09-09 15:08:12 +00003377
John McCallf1860e52010-05-20 23:23:51 +00003378 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003379 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3380 MemEnd = ClassDecl->decls_end();
3381 Mem != MemEnd; ++Mem) {
3382 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003383 // C++ [class.bit]p2:
3384 // A declaration for a bit-field that omits the identifier declares an
3385 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3386 // initialized.
3387 if (F->isUnnamedBitfield())
3388 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003389
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003390 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003391 // handle anonymous struct/union fields based on their individual
3392 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003393 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003394 continue;
3395
3396 if (CollectFieldInitializer(*this, Info, F))
3397 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003398 continue;
3399 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003400
3401 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003402 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003403 continue;
3404
3405 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3406 if (F->getType()->isIncompleteArrayType()) {
3407 assert(ClassDecl->hasFlexibleArrayMember() &&
3408 "Incomplete array type is not valid");
3409 continue;
3410 }
3411
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003412 // Initialize each field of an anonymous struct individually.
3413 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3414 HadError = true;
3415
3416 continue;
3417 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003418 }
Mike Stump1eb44332009-09-09 15:08:12 +00003419
David Blaikie93c86172013-01-17 05:26:25 +00003420 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003421 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003422 Constructor->setNumCtorInitializers(NumInitializers);
3423 CXXCtorInitializer **baseOrMemberInitializers =
3424 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003425 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003426 NumInitializers * sizeof(CXXCtorInitializer*));
3427 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003428
John McCallef027fe2010-03-16 21:39:52 +00003429 // Constructors implicitly reference the base and member
3430 // destructors.
3431 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3432 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003433 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003434
3435 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003436}
3437
David Blaikieee000bb2013-01-17 08:49:22 +00003438static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003439 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003440 const RecordDecl *RD = RT->getDecl();
3441 if (RD->isAnonymousStructOrUnion()) {
3442 for (RecordDecl::field_iterator Field = RD->field_begin(),
3443 E = RD->field_end(); Field != E; ++Field)
3444 PopulateKeysForFields(*Field, IdealInits);
3445 return;
3446 }
Eli Friedman6347f422009-07-21 19:28:10 +00003447 }
David Blaikieee000bb2013-01-17 08:49:22 +00003448 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003449}
3450
Anders Carlssonea356fb2010-04-02 05:42:15 +00003451static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003452 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003453}
3454
Anders Carlssonea356fb2010-04-02 05:42:15 +00003455static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003456 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003457 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003458 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003459
David Blaikieee000bb2013-01-17 08:49:22 +00003460 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003461}
3462
David Blaikie93c86172013-01-17 05:26:25 +00003463static void DiagnoseBaseOrMemInitializerOrder(
3464 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3465 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003466 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003467 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003469 // Don't check initializers order unless the warning is enabled at the
3470 // location of at least one initializer.
3471 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003472 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003473 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003474 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3475 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003476 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003477 ShouldCheckOrder = true;
3478 break;
3479 }
3480 }
3481 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003482 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003483
John McCalld6ca8da2010-04-10 07:37:23 +00003484 // Build the list of bases and members in the order that they'll
3485 // actually be initialized. The explicit initializers should be in
3486 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003487 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Anders Carlsson071d6102010-04-02 03:38:04 +00003489 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3490
John McCalld6ca8da2010-04-10 07:37:23 +00003491 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003492 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003493 ClassDecl->vbases_begin(),
3494 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003495 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003496
John McCalld6ca8da2010-04-10 07:37:23 +00003497 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003498 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003499 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003500 if (Base->isVirtual())
3501 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003502 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
John McCalld6ca8da2010-04-10 07:37:23 +00003505 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003506 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003507 E = ClassDecl->field_end(); Field != E; ++Field) {
3508 if (Field->isUnnamedBitfield())
3509 continue;
3510
David Blaikieee000bb2013-01-17 08:49:22 +00003511 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003512 }
3513
John McCalld6ca8da2010-04-10 07:37:23 +00003514 unsigned NumIdealInits = IdealInitKeys.size();
3515 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003516
Sean Huntcbb67482011-01-08 20:30:50 +00003517 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003518 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003519 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003520 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003521
3522 // Scan forward to try to find this initializer in the idealized
3523 // initializers list.
3524 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3525 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003526 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003527
3528 // If we didn't find this initializer, it must be because we
3529 // scanned past it on a previous iteration. That can only
3530 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003531 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003532 Sema::SemaDiagnosticBuilder D =
3533 SemaRef.Diag(PrevInit->getSourceLocation(),
3534 diag::warn_initializer_out_of_order);
3535
Francois Pichet00eb3f92010-12-04 09:14:42 +00003536 if (PrevInit->isAnyMemberInitializer())
3537 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003538 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003539 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003540
Francois Pichet00eb3f92010-12-04 09:14:42 +00003541 if (Init->isAnyMemberInitializer())
3542 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003543 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003544 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003545
3546 // Move back to the initializer's location in the ideal list.
3547 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3548 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003549 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003550
3551 assert(IdealIndex != NumIdealInits &&
3552 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003553 }
John McCalld6ca8da2010-04-10 07:37:23 +00003554
3555 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003556 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003557}
3558
John McCall3c3ccdb2010-04-10 09:28:51 +00003559namespace {
3560bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003561 CXXCtorInitializer *Init,
3562 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003563 if (!PrevInit) {
3564 PrevInit = Init;
3565 return false;
3566 }
3567
Douglas Gregordc392c12013-03-25 23:28:23 +00003568 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003569 S.Diag(Init->getSourceLocation(),
3570 diag::err_multiple_mem_initialization)
3571 << Field->getDeclName()
3572 << Init->getSourceRange();
3573 else {
John McCallf4c73712011-01-19 06:33:43 +00003574 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003575 assert(BaseClass && "neither field nor base");
3576 S.Diag(Init->getSourceLocation(),
3577 diag::err_multiple_base_initialization)
3578 << QualType(BaseClass, 0)
3579 << Init->getSourceRange();
3580 }
3581 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3582 << 0 << PrevInit->getSourceRange();
3583
3584 return true;
3585}
3586
Sean Huntcbb67482011-01-08 20:30:50 +00003587typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003588typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3589
3590bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003591 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003592 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003593 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003594 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003595 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003596
3597 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003598 if (Parent->isUnion()) {
3599 UnionEntry &En = Unions[Parent];
3600 if (En.first && En.first != Child) {
3601 S.Diag(Init->getSourceLocation(),
3602 diag::err_multiple_mem_union_initialization)
3603 << Field->getDeclName()
3604 << Init->getSourceRange();
3605 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3606 << 0 << En.second->getSourceRange();
3607 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003608 }
3609 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003610 En.first = Child;
3611 En.second = Init;
3612 }
David Blaikie6fe29652011-11-17 06:01:57 +00003613 if (!Parent->isAnonymousStructOrUnion())
3614 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003615 }
3616
3617 Child = Parent;
3618 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003619 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003620
3621 return false;
3622}
3623}
3624
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003625/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003626void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003627 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003628 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003629 bool AnyErrors) {
3630 if (!ConstructorDecl)
3631 return;
3632
3633 AdjustDeclIfTemplate(ConstructorDecl);
3634
3635 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003636 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003637
3638 if (!Constructor) {
3639 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3640 return;
3641 }
3642
John McCall3c3ccdb2010-04-10 09:28:51 +00003643 // Mapping for the duplicate initializers check.
3644 // For member initializers, this is keyed with a FieldDecl*.
3645 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003646 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003647
3648 // Mapping for the inconsistent anonymous-union initializers check.
3649 RedundantUnionMap MemberUnions;
3650
Anders Carlssonea356fb2010-04-02 05:42:15 +00003651 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003652 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003653 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003654
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003655 // Set the source order index.
3656 Init->setSourceOrder(i);
3657
Francois Pichet00eb3f92010-12-04 09:14:42 +00003658 if (Init->isAnyMemberInitializer()) {
3659 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003660 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3661 CheckRedundantUnionInit(*this, Init, MemberUnions))
3662 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003663 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003664 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3665 if (CheckRedundantInit(*this, Init, Members[Key]))
3666 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003667 } else {
3668 assert(Init->isDelegatingInitializer());
3669 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003670 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003671 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003672 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003673 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003674 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003675 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003676 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003677 // Return immediately as the initializer is set.
3678 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003679 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003680 }
3681
Anders Carlssonea356fb2010-04-02 05:42:15 +00003682 if (HadError)
3683 return;
3684
David Blaikie93c86172013-01-17 05:26:25 +00003685 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003686
David Blaikie93c86172013-01-17 05:26:25 +00003687 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003688}
3689
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003690void
John McCallef027fe2010-03-16 21:39:52 +00003691Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3692 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003693 // Ignore dependent contexts. Also ignore unions, since their members never
3694 // have destructors implicitly called.
3695 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003696 return;
John McCall58e6f342010-03-16 05:22:47 +00003697
3698 // FIXME: all the access-control diagnostics are positioned on the
3699 // field/base declaration. That's probably good; that said, the
3700 // user might reasonably want to know why the destructor is being
3701 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003702
Anders Carlsson9f853df2009-11-17 04:44:12 +00003703 // Non-static data members.
3704 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3705 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003706 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003707 if (Field->isInvalidDecl())
3708 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003709
3710 // Don't destroy incomplete or zero-length arrays.
3711 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3712 continue;
3713
Anders Carlsson9f853df2009-11-17 04:44:12 +00003714 QualType FieldType = Context.getBaseElementType(Field->getType());
3715
3716 const RecordType* RT = FieldType->getAs<RecordType>();
3717 if (!RT)
3718 continue;
3719
3720 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003721 if (FieldClassDecl->isInvalidDecl())
3722 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003723 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003724 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003725 // The destructor for an implicit anonymous union member is never invoked.
3726 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3727 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003728
Douglas Gregordb89f282010-07-01 22:47:18 +00003729 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003730 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003731 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003732 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003733 << Field->getDeclName()
3734 << FieldType);
3735
Eli Friedman5f2987c2012-02-02 03:46:19 +00003736 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003737 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003738 }
3739
John McCall58e6f342010-03-16 05:22:47 +00003740 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3741
Anders Carlsson9f853df2009-11-17 04:44:12 +00003742 // Bases.
3743 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3744 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003745 // Bases are always records in a well-formed non-dependent class.
3746 const RecordType *RT = Base->getType()->getAs<RecordType>();
3747
3748 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003749 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003750 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003751
John McCall58e6f342010-03-16 05:22:47 +00003752 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003753 // If our base class is invalid, we probably can't get its dtor anyway.
3754 if (BaseClassDecl->isInvalidDecl())
3755 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003756 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003757 continue;
John McCall58e6f342010-03-16 05:22:47 +00003758
Douglas Gregordb89f282010-07-01 22:47:18 +00003759 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003760 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003761
3762 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003763 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003764 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003765 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003766 << Base->getSourceRange(),
3767 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003768
Eli Friedman5f2987c2012-02-02 03:46:19 +00003769 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003770 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003771 }
3772
3773 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003774 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3775 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003776
3777 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003778 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003779
3780 // Ignore direct virtual bases.
3781 if (DirectVirtualBases.count(RT))
3782 continue;
3783
John McCall58e6f342010-03-16 05:22:47 +00003784 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003785 // If our base class is invalid, we probably can't get its dtor anyway.
3786 if (BaseClassDecl->isInvalidDecl())
3787 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003788 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003789 continue;
John McCall58e6f342010-03-16 05:22:47 +00003790
Douglas Gregordb89f282010-07-01 22:47:18 +00003791 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003792 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer585bee42013-06-06 23:43:20 +00003793 if (CheckDestructorAccess(
3794 ClassDecl->getLocation(), Dtor,
3795 PDiag(diag::err_access_dtor_vbase)
3796 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3797 Context.getTypeDeclType(ClassDecl)) ==
3798 AR_accessible) {
3799 CheckDerivedToBaseConversion(
3800 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3801 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3802 SourceRange(), DeclarationName(), 0);
3803 }
John McCall58e6f342010-03-16 05:22:47 +00003804
Eli Friedman5f2987c2012-02-02 03:46:19 +00003805 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003806 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003807 }
3808}
3809
John McCalld226f652010-08-21 09:40:31 +00003810void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003811 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003812 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Mike Stump1eb44332009-09-09 15:08:12 +00003814 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003815 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003816 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003817}
3818
Mike Stump1eb44332009-09-09 15:08:12 +00003819bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003820 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003821 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3822 unsigned DiagID;
3823 AbstractDiagSelID SelID;
3824
3825 public:
3826 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3827 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3828
3829 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003830 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003831 if (SelID == -1)
3832 S.Diag(Loc, DiagID) << T;
3833 else
3834 S.Diag(Loc, DiagID) << SelID << T;
3835 }
3836 } Diagnoser(DiagID, SelID);
3837
3838 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003839}
3840
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003841bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003842 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003843 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003844 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Anders Carlsson11f21a02009-03-23 19:10:31 +00003846 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003847 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Ted Kremenek6217b802009-07-29 21:53:49 +00003849 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003850 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003852 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003854 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003855 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Ted Kremenek6217b802009-07-29 21:53:49 +00003858 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003859 if (!RT)
3860 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
John McCall86ff3082010-02-04 22:26:26 +00003862 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003863
John McCall94c3b562010-08-18 09:41:07 +00003864 // We can't answer whether something is abstract until it has a
3865 // definition. If it's currently being defined, we'll walk back
3866 // over all the declarations when we have a full definition.
3867 const CXXRecordDecl *Def = RD->getDefinition();
3868 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003869 return false;
3870
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003871 if (!RD->isAbstract())
3872 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003874 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003875 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003876
John McCall94c3b562010-08-18 09:41:07 +00003877 return true;
3878}
3879
3880void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3881 // Check if we've already emitted the list of pure virtual functions
3882 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003883 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003886 CXXFinalOverriderMap FinalOverriders;
3887 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003889 // Keep a set of seen pure methods so we won't diagnose the same method
3890 // more than once.
3891 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3892
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003893 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3894 MEnd = FinalOverriders.end();
3895 M != MEnd;
3896 ++M) {
3897 for (OverridingMethods::iterator SO = M->second.begin(),
3898 SOEnd = M->second.end();
3899 SO != SOEnd; ++SO) {
3900 // C++ [class.abstract]p4:
3901 // A class is abstract if it contains or inherits at least one
3902 // pure virtual function for which the final overrider is pure
3903 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003905 //
3906 if (SO->second.size() != 1)
3907 continue;
3908
3909 if (!SO->second.front().Method->isPure())
3910 continue;
3911
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003912 if (!SeenPureMethods.insert(SO->second.front().Method))
3913 continue;
3914
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003915 Diag(SO->second.front().Method->getLocation(),
3916 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003917 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003918 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003919 }
3920
3921 if (!PureVirtualClassDiagSet)
3922 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3923 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003924}
3925
Anders Carlsson8211eff2009-03-24 01:19:16 +00003926namespace {
John McCall94c3b562010-08-18 09:41:07 +00003927struct AbstractUsageInfo {
3928 Sema &S;
3929 CXXRecordDecl *Record;
3930 CanQualType AbstractType;
3931 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003932
John McCall94c3b562010-08-18 09:41:07 +00003933 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3934 : S(S), Record(Record),
3935 AbstractType(S.Context.getCanonicalType(
3936 S.Context.getTypeDeclType(Record))),
3937 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003938
John McCall94c3b562010-08-18 09:41:07 +00003939 void DiagnoseAbstractType() {
3940 if (Invalid) return;
3941 S.DiagnoseAbstractType(Record);
3942 Invalid = true;
3943 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003944
John McCall94c3b562010-08-18 09:41:07 +00003945 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3946};
3947
3948struct CheckAbstractUsage {
3949 AbstractUsageInfo &Info;
3950 const NamedDecl *Ctx;
3951
3952 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3953 : Info(Info), Ctx(Ctx) {}
3954
3955 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3956 switch (TL.getTypeLocClass()) {
3957#define ABSTRACT_TYPELOC(CLASS, PARENT)
3958#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003959 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003960#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003961 }
John McCall94c3b562010-08-18 09:41:07 +00003962 }
Mike Stump1eb44332009-09-09 15:08:12 +00003963
John McCall94c3b562010-08-18 09:41:07 +00003964 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3965 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3966 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003967 if (!TL.getArg(I))
3968 continue;
3969
John McCall94c3b562010-08-18 09:41:07 +00003970 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3971 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003972 }
John McCall94c3b562010-08-18 09:41:07 +00003973 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003974
John McCall94c3b562010-08-18 09:41:07 +00003975 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3976 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3977 }
Mike Stump1eb44332009-09-09 15:08:12 +00003978
John McCall94c3b562010-08-18 09:41:07 +00003979 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3980 // Visit the type parameters from a permissive context.
3981 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3982 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3983 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3984 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3985 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3986 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003987 }
John McCall94c3b562010-08-18 09:41:07 +00003988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
John McCall94c3b562010-08-18 09:41:07 +00003990 // Visit pointee types from a permissive context.
3991#define CheckPolymorphic(Type) \
3992 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3993 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3994 }
3995 CheckPolymorphic(PointerTypeLoc)
3996 CheckPolymorphic(ReferenceTypeLoc)
3997 CheckPolymorphic(MemberPointerTypeLoc)
3998 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003999 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004000
John McCall94c3b562010-08-18 09:41:07 +00004001 /// Handle all the types we haven't given a more specific
4002 /// implementation for above.
4003 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004 // Every other kind of type that we haven't called out already
4005 // that has an inner type is either (1) sugar or (2) contains that
4006 // inner type in some way as a subobject.
4007 if (TypeLoc Next = TL.getNextTypeLoc())
4008 return Visit(Next, Sel);
4009
4010 // If there's no inner type and we're in a permissive context,
4011 // don't diagnose.
4012 if (Sel == Sema::AbstractNone) return;
4013
4014 // Check whether the type matches the abstract type.
4015 QualType T = TL.getType();
4016 if (T->isArrayType()) {
4017 Sel = Sema::AbstractArrayType;
4018 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004019 }
John McCall94c3b562010-08-18 09:41:07 +00004020 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4021 if (CT != Info.AbstractType) return;
4022
4023 // It matched; do some magic.
4024 if (Sel == Sema::AbstractArrayType) {
4025 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4026 << T << TL.getSourceRange();
4027 } else {
4028 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4029 << Sel << T << TL.getSourceRange();
4030 }
4031 Info.DiagnoseAbstractType();
4032 }
4033};
4034
4035void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4036 Sema::AbstractDiagSelID Sel) {
4037 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4038}
4039
4040}
4041
4042/// Check for invalid uses of an abstract type in a method declaration.
4043static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4044 CXXMethodDecl *MD) {
4045 // No need to do the check on definitions, which require that
4046 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004047 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004048 return;
4049
4050 // For safety's sake, just ignore it if we don't have type source
4051 // information. This should never happen for non-implicit methods,
4052 // but...
4053 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4054 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4055}
4056
4057/// Check for invalid uses of an abstract type within a class definition.
4058static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4059 CXXRecordDecl *RD) {
4060 for (CXXRecordDecl::decl_iterator
4061 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4062 Decl *D = *I;
4063 if (D->isImplicit()) continue;
4064
4065 // Methods and method templates.
4066 if (isa<CXXMethodDecl>(D)) {
4067 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4068 } else if (isa<FunctionTemplateDecl>(D)) {
4069 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4070 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4071
4072 // Fields and static variables.
4073 } else if (isa<FieldDecl>(D)) {
4074 FieldDecl *FD = cast<FieldDecl>(D);
4075 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4076 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4077 } else if (isa<VarDecl>(D)) {
4078 VarDecl *VD = cast<VarDecl>(D);
4079 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4080 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4081
4082 // Nested classes and class templates.
4083 } else if (isa<CXXRecordDecl>(D)) {
4084 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4085 } else if (isa<ClassTemplateDecl>(D)) {
4086 CheckAbstractClassUsage(Info,
4087 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4088 }
4089 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004090}
4091
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004092/// \brief Perform semantic checks on a class definition that has been
4093/// completing, introducing implicitly-declared members, checking for
4094/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004095void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004096 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004097 return;
4098
John McCall94c3b562010-08-18 09:41:07 +00004099 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4100 AbstractUsageInfo Info(*this, Record);
4101 CheckAbstractClassUsage(Info, Record);
4102 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004103
4104 // If this is not an aggregate type and has no user-declared constructor,
4105 // complain about any non-static data members of reference or const scalar
4106 // type, since they will never get initializers.
4107 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004108 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4109 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004110 bool Complained = false;
4111 for (RecordDecl::field_iterator F = Record->field_begin(),
4112 FEnd = Record->field_end();
4113 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004114 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004115 continue;
4116
Douglas Gregor325e5932010-04-15 00:00:53 +00004117 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004118 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004119 if (!Complained) {
4120 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4121 << Record->getTagKind() << Record;
4122 Complained = true;
4123 }
4124
4125 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4126 << F->getType()->isReferenceType()
4127 << F->getDeclName();
4128 }
4129 }
4130 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004131
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004132 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004133 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004134
4135 if (Record->getIdentifier()) {
4136 // C++ [class.mem]p13:
4137 // If T is the name of a class, then each of the following shall have a
4138 // name different from T:
4139 // - every member of every anonymous union that is a member of class T.
4140 //
4141 // C++ [class.mem]p14:
4142 // In addition, if class T has a user-declared constructor (12.1), every
4143 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004144 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4145 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4146 ++I) {
4147 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004148 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4149 isa<IndirectFieldDecl>(D)) {
4150 Diag(D->getLocation(), diag::err_member_name_of_class)
4151 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004152 break;
4153 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004154 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004155 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004156
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004157 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004158 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004159 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004160 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004161 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4162 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4163 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004164
David Blaikieb6b5b972012-09-21 03:21:07 +00004165 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4166 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4167 DiagnoseAbstractType(Record);
4168 }
4169
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004170 if (!Record->isDependentType()) {
4171 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4172 MEnd = Record->method_end();
4173 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004174 // See if a method overloads virtual methods in a base
4175 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004176 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004177 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004178
4179 // Check whether the explicitly-defaulted special members are valid.
4180 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4181 CheckExplicitlyDefaultedSpecialMember(*M);
4182
4183 // For an explicitly defaulted or deleted special member, we defer
4184 // determining triviality until the class is complete. That time is now!
4185 if (!M->isImplicit() && !M->isUserProvided()) {
4186 CXXSpecialMember CSM = getSpecialMember(*M);
4187 if (CSM != CXXInvalid) {
4188 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4189
4190 // Inform the class that we've finished declaring this member.
4191 Record->finishedDefaultedOrDeletedMember(*M);
4192 }
4193 }
4194 }
4195 }
4196
4197 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4198 // function that is not a constructor declares that member function to be
4199 // const. [...] The class of which that function is a member shall be
4200 // a literal type.
4201 //
4202 // If the class has virtual bases, any constexpr members will already have
4203 // been diagnosed by the checks performed on the member declaration, so
4204 // suppress this (less useful) diagnostic.
4205 //
4206 // We delay this until we know whether an explicitly-defaulted (or deleted)
4207 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004208 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004209 !Record->isLiteral() && !Record->getNumVBases()) {
4210 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4211 MEnd = Record->method_end();
4212 M != MEnd; ++M) {
4213 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4214 switch (Record->getTemplateSpecializationKind()) {
4215 case TSK_ImplicitInstantiation:
4216 case TSK_ExplicitInstantiationDeclaration:
4217 case TSK_ExplicitInstantiationDefinition:
4218 // If a template instantiates to a non-literal type, but its members
4219 // instantiate to constexpr functions, the template is technically
4220 // ill-formed, but we allow it for sanity.
4221 continue;
4222
4223 case TSK_Undeclared:
4224 case TSK_ExplicitSpecialization:
4225 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4226 diag::err_constexpr_method_non_literal);
4227 break;
4228 }
4229
4230 // Only produce one error per class.
4231 break;
4232 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004233 }
4234 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004235
Richard Smith07b0fdc2013-03-18 21:12:30 +00004236 // Declare inheriting constructors. We do this eagerly here because:
4237 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004238 // constructors from different classes.
4239 // - The lazy declaration of the other implicit constructors is so as to not
4240 // waste space and performance on classes that are not meant to be
4241 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004242 // have inheriting constructors.
4243 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004244}
4245
Richard Smith7756afa2012-06-10 05:43:50 +00004246/// Is the special member function which would be selected to perform the
4247/// specified operation on the specified class type a constexpr constructor?
4248static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4249 Sema::CXXSpecialMember CSM,
4250 bool ConstArg) {
4251 Sema::SpecialMemberOverloadResult *SMOR =
4252 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4253 false, false, false, false);
4254 if (!SMOR || !SMOR->getMethod())
4255 // A constructor we wouldn't select can't be "involved in initializing"
4256 // anything.
4257 return true;
4258 return SMOR->getMethod()->isConstexpr();
4259}
4260
4261/// Determine whether the specified special member function would be constexpr
4262/// if it were implicitly defined.
4263static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4264 Sema::CXXSpecialMember CSM,
4265 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004266 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004267 return false;
4268
4269 // C++11 [dcl.constexpr]p4:
4270 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004271 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004272 switch (CSM) {
4273 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004274 // Since default constructor lookup is essentially trivial (and cannot
4275 // involve, for instance, template instantiation), we compute whether a
4276 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4277 //
4278 // This is important for performance; we need to know whether the default
4279 // constructor is constexpr to determine whether the type is a literal type.
4280 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4281
Richard Smith7756afa2012-06-10 05:43:50 +00004282 case Sema::CXXCopyConstructor:
4283 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004284 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004285 break;
4286
4287 case Sema::CXXCopyAssignment:
4288 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004289 if (!S.getLangOpts().CPlusPlus1y)
4290 return false;
4291 // In C++1y, we need to perform overload resolution.
4292 Ctor = false;
4293 break;
4294
Richard Smith7756afa2012-06-10 05:43:50 +00004295 case Sema::CXXDestructor:
4296 case Sema::CXXInvalid:
4297 return false;
4298 }
4299
4300 // -- if the class is a non-empty union, or for each non-empty anonymous
4301 // union member of a non-union class, exactly one non-static data member
4302 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004303 //
4304 // If we squint, this is guaranteed, since exactly one non-static data member
4305 // will be initialized (if the constructor isn't deleted), we just don't know
4306 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004307 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004308 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004309
4310 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004311 if (Ctor && ClassDecl->getNumVBases())
4312 return false;
4313
4314 // C++1y [class.copy]p26:
4315 // -- [the class] is a literal type, and
4316 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004317 return false;
4318
4319 // -- every constructor involved in initializing [...] base class
4320 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004321 // -- the assignment operator selected to copy/move each direct base
4322 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004323 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4324 BEnd = ClassDecl->bases_end();
4325 B != BEnd; ++B) {
4326 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4327 if (!BaseType) continue;
4328
4329 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4330 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4331 return false;
4332 }
4333
4334 // -- every constructor involved in initializing non-static data members
4335 // [...] shall be a constexpr constructor;
4336 // -- every non-static data member and base class sub-object shall be
4337 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004338 // -- for each non-stastic data member of X that is of class type (or array
4339 // thereof), the assignment operator selected to copy/move that member is
4340 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004341 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4342 FEnd = ClassDecl->field_end();
4343 F != FEnd; ++F) {
4344 if (F->isInvalidDecl())
4345 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004346 if (const RecordType *RecordTy =
4347 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004348 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4349 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4350 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004351 }
4352 }
4353
4354 // All OK, it's constexpr!
4355 return true;
4356}
4357
Richard Smithb9d0b762012-07-27 04:22:15 +00004358static Sema::ImplicitExceptionSpecification
4359computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4360 switch (S.getSpecialMember(MD)) {
4361 case Sema::CXXDefaultConstructor:
4362 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4363 case Sema::CXXCopyConstructor:
4364 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4365 case Sema::CXXCopyAssignment:
4366 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4367 case Sema::CXXMoveConstructor:
4368 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4369 case Sema::CXXMoveAssignment:
4370 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4371 case Sema::CXXDestructor:
4372 return S.ComputeDefaultedDtorExceptionSpec(MD);
4373 case Sema::CXXInvalid:
4374 break;
4375 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004376 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4377 "only special members have implicit exception specs");
4378 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004379}
4380
Richard Smithdd25e802012-07-30 23:48:14 +00004381static void
4382updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4383 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4384 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4385 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004386 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4387 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004388}
4389
Richard Smithb9d0b762012-07-27 04:22:15 +00004390void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4391 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4392 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4393 return;
4394
Richard Smithdd25e802012-07-30 23:48:14 +00004395 // Evaluate the exception specification.
4396 ImplicitExceptionSpecification ExceptSpec =
4397 computeImplicitExceptionSpec(*this, Loc, MD);
4398
4399 // Update the type of the special member to use it.
4400 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4401
4402 // A user-provided destructor can be defined outside the class. When that
4403 // happens, be sure to update the exception specification on both
4404 // declarations.
4405 const FunctionProtoType *CanonicalFPT =
4406 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4407 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4408 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4409 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004410}
4411
Richard Smith3003e1d2012-05-15 04:39:51 +00004412void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4413 CXXRecordDecl *RD = MD->getParent();
4414 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004415
Richard Smith3003e1d2012-05-15 04:39:51 +00004416 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4417 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004418
4419 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004420 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004421 bool First = MD == MD->getCanonicalDecl();
4422
4423 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004424
4425 // C++11 [dcl.fct.def.default]p1:
4426 // A function that is explicitly defaulted shall
4427 // -- be a special member function (checked elsewhere),
4428 // -- have the same type (except for ref-qualifiers, and except that a
4429 // copy operation can take a non-const reference) as an implicit
4430 // declaration, and
4431 // -- not have default arguments.
4432 unsigned ExpectedParams = 1;
4433 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4434 ExpectedParams = 0;
4435 if (MD->getNumParams() != ExpectedParams) {
4436 // This also checks for default arguments: a copy or move constructor with a
4437 // default argument is classified as a default constructor, and assignment
4438 // operations and destructors can't have default arguments.
4439 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4440 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004441 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004442 } else if (MD->isVariadic()) {
4443 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4444 << CSM << MD->getSourceRange();
4445 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004446 }
4447
Richard Smith3003e1d2012-05-15 04:39:51 +00004448 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004449
Richard Smith7756afa2012-06-10 05:43:50 +00004450 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004451 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004452 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004453 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004454 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004455
Richard Smith3003e1d2012-05-15 04:39:51 +00004456 QualType ReturnType = Context.VoidTy;
4457 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4458 // Check for return type matching.
4459 ReturnType = Type->getResultType();
4460 QualType ExpectedReturnType =
4461 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4462 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4463 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4464 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4465 HadError = true;
4466 }
4467
4468 // A defaulted special member cannot have cv-qualifiers.
4469 if (Type->getTypeQuals()) {
4470 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004471 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004472 HadError = true;
4473 }
4474 }
4475
4476 // Check for parameter type matching.
4477 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004478 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004479 if (ExpectedParams && ArgType->isReferenceType()) {
4480 // Argument must be reference to possibly-const T.
4481 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004482 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004483
4484 if (ReferentType.isVolatileQualified()) {
4485 Diag(MD->getLocation(),
4486 diag::err_defaulted_special_member_volatile_param) << CSM;
4487 HadError = true;
4488 }
4489
Richard Smith7756afa2012-06-10 05:43:50 +00004490 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004491 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4492 Diag(MD->getLocation(),
4493 diag::err_defaulted_special_member_copy_const_param)
4494 << (CSM == CXXCopyAssignment);
4495 // FIXME: Explain why this special member can't be const.
4496 } else {
4497 Diag(MD->getLocation(),
4498 diag::err_defaulted_special_member_move_const_param)
4499 << (CSM == CXXMoveAssignment);
4500 }
4501 HadError = true;
4502 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004503 } else if (ExpectedParams) {
4504 // A copy assignment operator can take its argument by value, but a
4505 // defaulted one cannot.
4506 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004507 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004508 HadError = true;
4509 }
Sean Huntbe631222011-05-17 20:44:43 +00004510
Richard Smith61802452011-12-22 02:22:31 +00004511 // C++11 [dcl.fct.def.default]p2:
4512 // An explicitly-defaulted function may be declared constexpr only if it
4513 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004514 // Do not apply this rule to members of class templates, since core issue 1358
4515 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004516 // functions which cannot be constexpr (for non-constructors in C++11 and for
4517 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004518 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4519 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004520 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4521 : isa<CXXConstructorDecl>(MD)) &&
4522 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004523 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4524 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004525 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004526 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004527 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004528
Richard Smith61802452011-12-22 02:22:31 +00004529 // and may have an explicit exception-specification only if it is compatible
4530 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004531 if (Type->hasExceptionSpec()) {
4532 // Delay the check if this is the first declaration of the special member,
4533 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004534 if (First) {
4535 // If the exception specification needs to be instantiated, do so now,
4536 // before we clobber it with an EST_Unevaluated specification below.
4537 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4538 InstantiateExceptionSpec(MD->getLocStart(), MD);
4539 Type = MD->getType()->getAs<FunctionProtoType>();
4540 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004541 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004542 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004543 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4544 }
Richard Smith61802452011-12-22 02:22:31 +00004545
4546 // If a function is explicitly defaulted on its first declaration,
4547 if (First) {
4548 // -- it is implicitly considered to be constexpr if the implicit
4549 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004550 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004551
Richard Smith3003e1d2012-05-15 04:39:51 +00004552 // -- it is implicitly considered to have the same exception-specification
4553 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004554 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4555 EPI.ExceptionSpecType = EST_Unevaluated;
4556 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004557 MD->setType(Context.getFunctionType(ReturnType,
4558 ArrayRef<QualType>(&ArgType,
4559 ExpectedParams),
4560 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004561 }
4562
Richard Smith3003e1d2012-05-15 04:39:51 +00004563 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004564 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004565 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004566 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004567 // C++11 [dcl.fct.def.default]p4:
4568 // [For a] user-provided explicitly-defaulted function [...] if such a
4569 // function is implicitly defined as deleted, the program is ill-formed.
4570 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4571 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004572 }
4573 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004574
Richard Smith3003e1d2012-05-15 04:39:51 +00004575 if (HadError)
4576 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004577}
4578
Richard Smith1d28caf2012-12-11 01:14:52 +00004579/// Check whether the exception specification provided for an
4580/// explicitly-defaulted special member matches the exception specification
4581/// that would have been generated for an implicit special member, per
4582/// C++11 [dcl.fct.def.default]p2.
4583void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4584 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4585 // Compute the implicit exception specification.
4586 FunctionProtoType::ExtProtoInfo EPI;
4587 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4588 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004589 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004590
4591 // Ensure that it matches.
4592 CheckEquivalentExceptionSpec(
4593 PDiag(diag::err_incorrect_defaulted_exception_spec)
4594 << getSpecialMember(MD), PDiag(),
4595 ImplicitType, SourceLocation(),
4596 SpecifiedType, MD->getLocation());
4597}
4598
4599void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4600 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4601 I != N; ++I)
4602 CheckExplicitlyDefaultedMemberExceptionSpec(
4603 DelayedDefaultedMemberExceptionSpecs[I].first,
4604 DelayedDefaultedMemberExceptionSpecs[I].second);
4605
4606 DelayedDefaultedMemberExceptionSpecs.clear();
4607}
4608
Richard Smith7d5088a2012-02-18 02:02:13 +00004609namespace {
4610struct SpecialMemberDeletionInfo {
4611 Sema &S;
4612 CXXMethodDecl *MD;
4613 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004614 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004615
4616 // Properties of the special member, computed for convenience.
4617 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4618 SourceLocation Loc;
4619
4620 bool AllFieldsAreConst;
4621
4622 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004623 Sema::CXXSpecialMember CSM, bool Diagnose)
4624 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004625 IsConstructor(false), IsAssignment(false), IsMove(false),
4626 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4627 AllFieldsAreConst(true) {
4628 switch (CSM) {
4629 case Sema::CXXDefaultConstructor:
4630 case Sema::CXXCopyConstructor:
4631 IsConstructor = true;
4632 break;
4633 case Sema::CXXMoveConstructor:
4634 IsConstructor = true;
4635 IsMove = true;
4636 break;
4637 case Sema::CXXCopyAssignment:
4638 IsAssignment = true;
4639 break;
4640 case Sema::CXXMoveAssignment:
4641 IsAssignment = true;
4642 IsMove = true;
4643 break;
4644 case Sema::CXXDestructor:
4645 break;
4646 case Sema::CXXInvalid:
4647 llvm_unreachable("invalid special member kind");
4648 }
4649
4650 if (MD->getNumParams()) {
4651 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4652 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4653 }
4654 }
4655
4656 bool inUnion() const { return MD->getParent()->isUnion(); }
4657
4658 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004659 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4660 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004661 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004662 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4663 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4664 Quals = 0;
4665 return S.LookupSpecialMember(Class, CSM,
4666 ConstArg || (Quals & Qualifiers::Const),
4667 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004668 MD->getRefQualifier() == RQ_RValue,
4669 TQ & Qualifiers::Const,
4670 TQ & Qualifiers::Volatile);
4671 }
4672
Richard Smith6c4c36c2012-03-30 20:53:28 +00004673 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004674
Richard Smith6c4c36c2012-03-30 20:53:28 +00004675 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004676 bool shouldDeleteForField(FieldDecl *FD);
4677 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004678
Richard Smith517bb842012-07-18 03:51:16 +00004679 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4680 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004681 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4682 Sema::SpecialMemberOverloadResult *SMOR,
4683 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004684
4685 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004686};
4687}
4688
John McCall12d8d802012-04-09 20:53:23 +00004689/// Is the given special member inaccessible when used on the given
4690/// sub-object.
4691bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4692 CXXMethodDecl *target) {
4693 /// If we're operating on a base class, the object type is the
4694 /// type of this special member.
4695 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004696 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004697 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4698 objectTy = S.Context.getTypeDeclType(MD->getParent());
4699 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4700
4701 // If we're operating on a field, the object type is the type of the field.
4702 } else {
4703 objectTy = S.Context.getTypeDeclType(target->getParent());
4704 }
4705
4706 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4707}
4708
Richard Smith6c4c36c2012-03-30 20:53:28 +00004709/// Check whether we should delete a special member due to the implicit
4710/// definition containing a call to a special member of a subobject.
4711bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4712 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4713 bool IsDtorCallInCtor) {
4714 CXXMethodDecl *Decl = SMOR->getMethod();
4715 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4716
4717 int DiagKind = -1;
4718
4719 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4720 DiagKind = !Decl ? 0 : 1;
4721 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4722 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004723 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004724 DiagKind = 3;
4725 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4726 !Decl->isTrivial()) {
4727 // A member of a union must have a trivial corresponding special member.
4728 // As a weird special case, a destructor call from a union's constructor
4729 // must be accessible and non-deleted, but need not be trivial. Such a
4730 // destructor is never actually called, but is semantically checked as
4731 // if it were.
4732 DiagKind = 4;
4733 }
4734
4735 if (DiagKind == -1)
4736 return false;
4737
4738 if (Diagnose) {
4739 if (Field) {
4740 S.Diag(Field->getLocation(),
4741 diag::note_deleted_special_member_class_subobject)
4742 << CSM << MD->getParent() << /*IsField*/true
4743 << Field << DiagKind << IsDtorCallInCtor;
4744 } else {
4745 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4746 S.Diag(Base->getLocStart(),
4747 diag::note_deleted_special_member_class_subobject)
4748 << CSM << MD->getParent() << /*IsField*/false
4749 << Base->getType() << DiagKind << IsDtorCallInCtor;
4750 }
4751
4752 if (DiagKind == 1)
4753 S.NoteDeletedFunction(Decl);
4754 // FIXME: Explain inaccessibility if DiagKind == 3.
4755 }
4756
4757 return true;
4758}
4759
Richard Smith9a561d52012-02-26 09:11:52 +00004760/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004761/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004762bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004763 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004764 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004765
4766 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004767 // -- any direct or virtual base class, or non-static data member with no
4768 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004769 // either M has no default constructor or overload resolution as applied
4770 // to M's default constructor results in an ambiguity or in a function
4771 // that is deleted or inaccessible
4772 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4773 // -- a direct or virtual base class B that cannot be copied/moved because
4774 // overload resolution, as applied to B's corresponding special member,
4775 // results in an ambiguity or a function that is deleted or inaccessible
4776 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004777 // C++11 [class.dtor]p5:
4778 // -- any direct or virtual base class [...] has a type with a destructor
4779 // that is deleted or inaccessible
4780 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004781 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004782 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004783 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004784
Richard Smith6c4c36c2012-03-30 20:53:28 +00004785 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4786 // -- any direct or virtual base class or non-static data member has a
4787 // type with a destructor that is deleted or inaccessible
4788 if (IsConstructor) {
4789 Sema::SpecialMemberOverloadResult *SMOR =
4790 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4791 false, false, false, false, false);
4792 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4793 return true;
4794 }
4795
Richard Smith9a561d52012-02-26 09:11:52 +00004796 return false;
4797}
4798
4799/// Check whether we should delete a special member function due to the class
4800/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004801bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004802 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004803 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004804}
4805
4806/// Check whether we should delete a special member function due to the class
4807/// having a particular non-static data member.
4808bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4809 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4810 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4811
4812 if (CSM == Sema::CXXDefaultConstructor) {
4813 // For a default constructor, all references must be initialized in-class
4814 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004815 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4816 if (Diagnose)
4817 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4818 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004819 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004820 }
Richard Smith79363f52012-02-27 06:07:25 +00004821 // C++11 [class.ctor]p5: any non-variant non-static data member of
4822 // const-qualified type (or array thereof) with no
4823 // brace-or-equal-initializer does not have a user-provided default
4824 // constructor.
4825 if (!inUnion() && FieldType.isConstQualified() &&
4826 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004827 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4828 if (Diagnose)
4829 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004830 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004831 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004832 }
4833
4834 if (inUnion() && !FieldType.isConstQualified())
4835 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004836 } else if (CSM == Sema::CXXCopyConstructor) {
4837 // For a copy constructor, data members must not be of rvalue reference
4838 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004839 if (FieldType->isRValueReferenceType()) {
4840 if (Diagnose)
4841 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4842 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004843 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004844 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004845 } else if (IsAssignment) {
4846 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004847 if (FieldType->isReferenceType()) {
4848 if (Diagnose)
4849 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4850 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004851 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852 }
4853 if (!FieldRecord && FieldType.isConstQualified()) {
4854 // C++11 [class.copy]p23:
4855 // -- a non-static data member of const non-class type (or array thereof)
4856 if (Diagnose)
4857 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004858 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004859 return true;
4860 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004861 }
4862
4863 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004864 // Some additional restrictions exist on the variant members.
4865 if (!inUnion() && FieldRecord->isUnion() &&
4866 FieldRecord->isAnonymousStructOrUnion()) {
4867 bool AllVariantFieldsAreConst = true;
4868
Richard Smithdf8dc862012-03-29 19:00:10 +00004869 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004870 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4871 UE = FieldRecord->field_end();
4872 UI != UE; ++UI) {
4873 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004874
4875 if (!UnionFieldType.isConstQualified())
4876 AllVariantFieldsAreConst = false;
4877
Richard Smith9a561d52012-02-26 09:11:52 +00004878 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4879 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004880 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4881 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004882 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004883 }
4884
4885 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004886 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004887 FieldRecord->field_begin() != FieldRecord->field_end()) {
4888 if (Diagnose)
4889 S.Diag(FieldRecord->getLocation(),
4890 diag::note_deleted_default_ctor_all_const)
4891 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004893 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004894
Richard Smithdf8dc862012-03-29 19:00:10 +00004895 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004896 // This is technically non-conformant, but sanity demands it.
4897 return false;
4898 }
4899
Richard Smith517bb842012-07-18 03:51:16 +00004900 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4901 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004902 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004903 }
4904
4905 return false;
4906}
4907
4908/// C++11 [class.ctor] p5:
4909/// A defaulted default constructor for a class X is defined as deleted if
4910/// X is a union and all of its variant members are of const-qualified type.
4911bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004912 // This is a silly definition, because it gives an empty union a deleted
4913 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004914 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4915 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4916 if (Diagnose)
4917 S.Diag(MD->getParent()->getLocation(),
4918 diag::note_deleted_default_ctor_all_const)
4919 << MD->getParent() << /*not anonymous union*/0;
4920 return true;
4921 }
4922 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004923}
4924
4925/// Determine whether a defaulted special member function should be defined as
4926/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4927/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004928bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4929 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004930 if (MD->isInvalidDecl())
4931 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004932 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004933 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004934 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004935 return false;
4936
Richard Smith7d5088a2012-02-18 02:02:13 +00004937 // C++11 [expr.lambda.prim]p19:
4938 // The closure type associated with a lambda-expression has a
4939 // deleted (8.4.3) default constructor and a deleted copy
4940 // assignment operator.
4941 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004942 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4943 if (Diagnose)
4944 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004945 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004946 }
4947
Richard Smith5bdaac52012-04-02 20:59:25 +00004948 // For an anonymous struct or union, the copy and assignment special members
4949 // will never be used, so skip the check. For an anonymous union declared at
4950 // namespace scope, the constructor and destructor are used.
4951 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4952 RD->isAnonymousStructOrUnion())
4953 return false;
4954
Richard Smith6c4c36c2012-03-30 20:53:28 +00004955 // C++11 [class.copy]p7, p18:
4956 // If the class definition declares a move constructor or move assignment
4957 // operator, an implicitly declared copy constructor or copy assignment
4958 // operator is defined as deleted.
4959 if (MD->isImplicit() &&
4960 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4961 CXXMethodDecl *UserDeclaredMove = 0;
4962
4963 // In Microsoft mode, a user-declared move only causes the deletion of the
4964 // corresponding copy operation, not both copy operations.
4965 if (RD->hasUserDeclaredMoveConstructor() &&
4966 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4967 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004968
4969 // Find any user-declared move constructor.
4970 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4971 E = RD->ctor_end(); I != E; ++I) {
4972 if (I->isMoveConstructor()) {
4973 UserDeclaredMove = *I;
4974 break;
4975 }
4976 }
Richard Smith1c931be2012-04-02 18:40:40 +00004977 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004978 } else if (RD->hasUserDeclaredMoveAssignment() &&
4979 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4980 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004981
4982 // Find any user-declared move assignment operator.
4983 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4984 E = RD->method_end(); I != E; ++I) {
4985 if (I->isMoveAssignmentOperator()) {
4986 UserDeclaredMove = *I;
4987 break;
4988 }
4989 }
Richard Smith1c931be2012-04-02 18:40:40 +00004990 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004991 }
4992
4993 if (UserDeclaredMove) {
4994 Diag(UserDeclaredMove->getLocation(),
4995 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004996 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004997 << UserDeclaredMove->isMoveAssignmentOperator();
4998 return true;
4999 }
5000 }
Sean Hunte16da072011-10-10 06:18:57 +00005001
Richard Smith5bdaac52012-04-02 20:59:25 +00005002 // Do access control from the special member function
5003 ContextRAII MethodContext(*this, MD);
5004
Richard Smith9a561d52012-02-26 09:11:52 +00005005 // C++11 [class.dtor]p5:
5006 // -- for a virtual destructor, lookup of the non-array deallocation function
5007 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005008 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005009 FunctionDecl *OperatorDelete = 0;
5010 DeclarationName Name =
5011 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5012 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005013 OperatorDelete, false)) {
5014 if (Diagnose)
5015 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005016 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005017 }
Richard Smith9a561d52012-02-26 09:11:52 +00005018 }
5019
Richard Smith6c4c36c2012-03-30 20:53:28 +00005020 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005021
Sean Huntcdee3fe2011-05-11 22:34:38 +00005022 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005023 BE = RD->bases_end(); BI != BE; ++BI)
5024 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005025 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005026 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005027
5028 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005029 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005030 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005031 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005032
5033 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005034 FE = RD->field_end(); FI != FE; ++FI)
5035 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005036 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005037 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005038
Richard Smith7d5088a2012-02-18 02:02:13 +00005039 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005040 return true;
5041
5042 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005043}
5044
Richard Smithac713512012-12-08 02:53:02 +00005045/// Perform lookup for a special member of the specified kind, and determine
5046/// whether it is trivial. If the triviality can be determined without the
5047/// lookup, skip it. This is intended for use when determining whether a
5048/// special member of a containing object is trivial, and thus does not ever
5049/// perform overload resolution for default constructors.
5050///
5051/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5052/// member that was most likely to be intended to be trivial, if any.
5053static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5054 Sema::CXXSpecialMember CSM, unsigned Quals,
5055 CXXMethodDecl **Selected) {
5056 if (Selected)
5057 *Selected = 0;
5058
5059 switch (CSM) {
5060 case Sema::CXXInvalid:
5061 llvm_unreachable("not a special member");
5062
5063 case Sema::CXXDefaultConstructor:
5064 // C++11 [class.ctor]p5:
5065 // A default constructor is trivial if:
5066 // - all the [direct subobjects] have trivial default constructors
5067 //
5068 // Note, no overload resolution is performed in this case.
5069 if (RD->hasTrivialDefaultConstructor())
5070 return true;
5071
5072 if (Selected) {
5073 // If there's a default constructor which could have been trivial, dig it
5074 // out. Otherwise, if there's any user-provided default constructor, point
5075 // to that as an example of why there's not a trivial one.
5076 CXXConstructorDecl *DefCtor = 0;
5077 if (RD->needsImplicitDefaultConstructor())
5078 S.DeclareImplicitDefaultConstructor(RD);
5079 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5080 CE = RD->ctor_end(); CI != CE; ++CI) {
5081 if (!CI->isDefaultConstructor())
5082 continue;
5083 DefCtor = *CI;
5084 if (!DefCtor->isUserProvided())
5085 break;
5086 }
5087
5088 *Selected = DefCtor;
5089 }
5090
5091 return false;
5092
5093 case Sema::CXXDestructor:
5094 // C++11 [class.dtor]p5:
5095 // A destructor is trivial if:
5096 // - all the direct [subobjects] have trivial destructors
5097 if (RD->hasTrivialDestructor())
5098 return true;
5099
5100 if (Selected) {
5101 if (RD->needsImplicitDestructor())
5102 S.DeclareImplicitDestructor(RD);
5103 *Selected = RD->getDestructor();
5104 }
5105
5106 return false;
5107
5108 case Sema::CXXCopyConstructor:
5109 // C++11 [class.copy]p12:
5110 // A copy constructor is trivial if:
5111 // - the constructor selected to copy each direct [subobject] is trivial
5112 if (RD->hasTrivialCopyConstructor()) {
5113 if (Quals == Qualifiers::Const)
5114 // We must either select the trivial copy constructor or reach an
5115 // ambiguity; no need to actually perform overload resolution.
5116 return true;
5117 } else if (!Selected) {
5118 return false;
5119 }
5120 // In C++98, we are not supposed to perform overload resolution here, but we
5121 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5122 // cases like B as having a non-trivial copy constructor:
5123 // struct A { template<typename T> A(T&); };
5124 // struct B { mutable A a; };
5125 goto NeedOverloadResolution;
5126
5127 case Sema::CXXCopyAssignment:
5128 // C++11 [class.copy]p25:
5129 // A copy assignment operator is trivial if:
5130 // - the assignment operator selected to copy each direct [subobject] is
5131 // trivial
5132 if (RD->hasTrivialCopyAssignment()) {
5133 if (Quals == Qualifiers::Const)
5134 return true;
5135 } else if (!Selected) {
5136 return false;
5137 }
5138 // In C++98, we are not supposed to perform overload resolution here, but we
5139 // treat that as a language defect.
5140 goto NeedOverloadResolution;
5141
5142 case Sema::CXXMoveConstructor:
5143 case Sema::CXXMoveAssignment:
5144 NeedOverloadResolution:
5145 Sema::SpecialMemberOverloadResult *SMOR =
5146 S.LookupSpecialMember(RD, CSM,
5147 Quals & Qualifiers::Const,
5148 Quals & Qualifiers::Volatile,
5149 /*RValueThis*/false, /*ConstThis*/false,
5150 /*VolatileThis*/false);
5151
5152 // The standard doesn't describe how to behave if the lookup is ambiguous.
5153 // We treat it as not making the member non-trivial, just like the standard
5154 // mandates for the default constructor. This should rarely matter, because
5155 // the member will also be deleted.
5156 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5157 return true;
5158
5159 if (!SMOR->getMethod()) {
5160 assert(SMOR->getKind() ==
5161 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5162 return false;
5163 }
5164
5165 // We deliberately don't check if we found a deleted special member. We're
5166 // not supposed to!
5167 if (Selected)
5168 *Selected = SMOR->getMethod();
5169 return SMOR->getMethod()->isTrivial();
5170 }
5171
5172 llvm_unreachable("unknown special method kind");
5173}
5174
Benjamin Kramera574c892013-02-15 12:30:38 +00005175static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005176 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5177 CI != CE; ++CI)
5178 if (!CI->isImplicit())
5179 return *CI;
5180
5181 // Look for constructor templates.
5182 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5183 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5184 if (CXXConstructorDecl *CD =
5185 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5186 return CD;
5187 }
5188
5189 return 0;
5190}
5191
5192/// The kind of subobject we are checking for triviality. The values of this
5193/// enumeration are used in diagnostics.
5194enum TrivialSubobjectKind {
5195 /// The subobject is a base class.
5196 TSK_BaseClass,
5197 /// The subobject is a non-static data member.
5198 TSK_Field,
5199 /// The object is actually the complete object.
5200 TSK_CompleteObject
5201};
5202
5203/// Check whether the special member selected for a given type would be trivial.
5204static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5205 QualType SubType,
5206 Sema::CXXSpecialMember CSM,
5207 TrivialSubobjectKind Kind,
5208 bool Diagnose) {
5209 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5210 if (!SubRD)
5211 return true;
5212
5213 CXXMethodDecl *Selected;
5214 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5215 Diagnose ? &Selected : 0))
5216 return true;
5217
5218 if (Diagnose) {
5219 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5220 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5221 << Kind << SubType.getUnqualifiedType();
5222 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5223 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5224 } else if (!Selected)
5225 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5226 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5227 else if (Selected->isUserProvided()) {
5228 if (Kind == TSK_CompleteObject)
5229 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5230 << Kind << SubType.getUnqualifiedType() << CSM;
5231 else {
5232 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5233 << Kind << SubType.getUnqualifiedType() << CSM;
5234 S.Diag(Selected->getLocation(), diag::note_declared_at);
5235 }
5236 } else {
5237 if (Kind != TSK_CompleteObject)
5238 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5239 << Kind << SubType.getUnqualifiedType() << CSM;
5240
5241 // Explain why the defaulted or deleted special member isn't trivial.
5242 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5243 }
5244 }
5245
5246 return false;
5247}
5248
5249/// Check whether the members of a class type allow a special member to be
5250/// trivial.
5251static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5252 Sema::CXXSpecialMember CSM,
5253 bool ConstArg, bool Diagnose) {
5254 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5255 FE = RD->field_end(); FI != FE; ++FI) {
5256 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5257 continue;
5258
5259 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5260
5261 // Pretend anonymous struct or union members are members of this class.
5262 if (FI->isAnonymousStructOrUnion()) {
5263 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5264 CSM, ConstArg, Diagnose))
5265 return false;
5266 continue;
5267 }
5268
5269 // C++11 [class.ctor]p5:
5270 // A default constructor is trivial if [...]
5271 // -- no non-static data member of its class has a
5272 // brace-or-equal-initializer
5273 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5274 if (Diagnose)
5275 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5276 return false;
5277 }
5278
5279 // Objective C ARC 4.3.5:
5280 // [...] nontrivally ownership-qualified types are [...] not trivially
5281 // default constructible, copy constructible, move constructible, copy
5282 // assignable, move assignable, or destructible [...]
5283 if (S.getLangOpts().ObjCAutoRefCount &&
5284 FieldType.hasNonTrivialObjCLifetime()) {
5285 if (Diagnose)
5286 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5287 << RD << FieldType.getObjCLifetime();
5288 return false;
5289 }
5290
5291 if (ConstArg && !FI->isMutable())
5292 FieldType.addConst();
5293 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5294 TSK_Field, Diagnose))
5295 return false;
5296 }
5297
5298 return true;
5299}
5300
5301/// Diagnose why the specified class does not have a trivial special member of
5302/// the given kind.
5303void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5304 QualType Ty = Context.getRecordType(RD);
5305 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5306 Ty.addConst();
5307
5308 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5309 TSK_CompleteObject, /*Diagnose*/true);
5310}
5311
5312/// Determine whether a defaulted or deleted special member function is trivial,
5313/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5314/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5315bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5316 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005317 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5318
5319 CXXRecordDecl *RD = MD->getParent();
5320
5321 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005322
5323 // C++11 [class.copy]p12, p25:
5324 // A [special member] is trivial if its declared parameter type is the same
5325 // as if it had been implicitly declared [...]
5326 switch (CSM) {
5327 case CXXDefaultConstructor:
5328 case CXXDestructor:
5329 // Trivial default constructors and destructors cannot have parameters.
5330 break;
5331
5332 case CXXCopyConstructor:
5333 case CXXCopyAssignment: {
5334 // Trivial copy operations always have const, non-volatile parameter types.
5335 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005336 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005337 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5338 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5339 if (Diagnose)
5340 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5341 << Param0->getSourceRange() << Param0->getType()
5342 << Context.getLValueReferenceType(
5343 Context.getRecordType(RD).withConst());
5344 return false;
5345 }
5346 break;
5347 }
5348
5349 case CXXMoveConstructor:
5350 case CXXMoveAssignment: {
5351 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005352 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005353 const RValueReferenceType *RT =
5354 Param0->getType()->getAs<RValueReferenceType>();
5355 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5356 if (Diagnose)
5357 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5358 << Param0->getSourceRange() << Param0->getType()
5359 << Context.getRValueReferenceType(Context.getRecordType(RD));
5360 return false;
5361 }
5362 break;
5363 }
5364
5365 case CXXInvalid:
5366 llvm_unreachable("not a special member");
5367 }
5368
5369 // FIXME: We require that the parameter-declaration-clause is equivalent to
5370 // that of an implicit declaration, not just that the declared parameter type
5371 // matches, in order to prevent absuridities like a function simultaneously
5372 // being a trivial copy constructor and a non-trivial default constructor.
5373 // This issue has not yet been assigned a core issue number.
5374 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5375 if (Diagnose)
5376 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5377 diag::note_nontrivial_default_arg)
5378 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5379 return false;
5380 }
5381 if (MD->isVariadic()) {
5382 if (Diagnose)
5383 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5384 return false;
5385 }
5386
5387 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5388 // A copy/move [constructor or assignment operator] is trivial if
5389 // -- the [member] selected to copy/move each direct base class subobject
5390 // is trivial
5391 //
5392 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5393 // A [default constructor or destructor] is trivial if
5394 // -- all the direct base classes have trivial [default constructors or
5395 // destructors]
5396 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5397 BE = RD->bases_end(); BI != BE; ++BI)
5398 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5399 ConstArg ? BI->getType().withConst()
5400 : BI->getType(),
5401 CSM, TSK_BaseClass, Diagnose))
5402 return false;
5403
5404 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5405 // A copy/move [constructor or assignment operator] for a class X is
5406 // trivial if
5407 // -- for each non-static data member of X that is of class type (or array
5408 // thereof), the constructor selected to copy/move that member is
5409 // trivial
5410 //
5411 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5412 // A [default constructor or destructor] is trivial if
5413 // -- for all of the non-static data members of its class that are of class
5414 // type (or array thereof), each such class has a trivial [default
5415 // constructor or destructor]
5416 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5417 return false;
5418
5419 // C++11 [class.dtor]p5:
5420 // A destructor is trivial if [...]
5421 // -- the destructor is not virtual
5422 if (CSM == CXXDestructor && MD->isVirtual()) {
5423 if (Diagnose)
5424 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5425 return false;
5426 }
5427
5428 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5429 // A [special member] for class X is trivial if [...]
5430 // -- class X has no virtual functions and no virtual base classes
5431 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5432 if (!Diagnose)
5433 return false;
5434
5435 if (RD->getNumVBases()) {
5436 // Check for virtual bases. We already know that the corresponding
5437 // member in all bases is trivial, so vbases must all be direct.
5438 CXXBaseSpecifier &BS = *RD->vbases_begin();
5439 assert(BS.isVirtual());
5440 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5441 return false;
5442 }
5443
5444 // Must have a virtual method.
5445 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5446 ME = RD->method_end(); MI != ME; ++MI) {
5447 if (MI->isVirtual()) {
5448 SourceLocation MLoc = MI->getLocStart();
5449 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5450 return false;
5451 }
5452 }
5453
5454 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5455 }
5456
5457 // Looks like it's trivial!
5458 return true;
5459}
5460
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005461/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005462namespace {
5463 struct FindHiddenVirtualMethodData {
5464 Sema *S;
5465 CXXMethodDecl *Method;
5466 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005467 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005468 };
5469}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005470
David Blaikie5f750682012-10-19 00:53:08 +00005471/// \brief Check whether any most overriden method from MD in Methods
5472static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5473 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5474 if (MD->size_overridden_methods() == 0)
5475 return Methods.count(MD->getCanonicalDecl());
5476 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5477 E = MD->end_overridden_methods();
5478 I != E; ++I)
5479 if (CheckMostOverridenMethods(*I, Methods))
5480 return true;
5481 return false;
5482}
5483
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005484/// \brief Member lookup function that determines whether a given C++
5485/// method overloads virtual methods in a base class without overriding any,
5486/// to be used with CXXRecordDecl::lookupInBases().
5487static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5488 CXXBasePath &Path,
5489 void *UserData) {
5490 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5491
5492 FindHiddenVirtualMethodData &Data
5493 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5494
5495 DeclarationName Name = Data.Method->getDeclName();
5496 assert(Name.getNameKind() == DeclarationName::Identifier);
5497
5498 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005499 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005500 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005501 !Path.Decls.empty();
5502 Path.Decls = Path.Decls.slice(1)) {
5503 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005504 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005505 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005506 foundSameNameMethod = true;
5507 // Interested only in hidden virtual methods.
5508 if (!MD->isVirtual())
5509 continue;
5510 // If the method we are checking overrides a method from its base
5511 // don't warn about the other overloaded methods.
5512 if (!Data.S->IsOverload(Data.Method, MD, false))
5513 return true;
5514 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005515 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005516 overloadedMethods.push_back(MD);
5517 }
5518 }
5519
5520 if (foundSameNameMethod)
5521 Data.OverloadedMethods.append(overloadedMethods.begin(),
5522 overloadedMethods.end());
5523 return foundSameNameMethod;
5524}
5525
David Blaikie5f750682012-10-19 00:53:08 +00005526/// \brief Add the most overriden methods from MD to Methods
5527static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5528 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5529 if (MD->size_overridden_methods() == 0)
5530 Methods.insert(MD->getCanonicalDecl());
5531 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5532 E = MD->end_overridden_methods();
5533 I != E; ++I)
5534 AddMostOverridenMethods(*I, Methods);
5535}
5536
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005537/// \brief See if a method overloads virtual methods in a base class without
5538/// overriding any.
5539void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5540 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005541 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005542 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005543 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005544 return;
5545
5546 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5547 /*bool RecordPaths=*/false,
5548 /*bool DetectVirtual=*/false);
5549 FindHiddenVirtualMethodData Data;
5550 Data.Method = MD;
5551 Data.S = this;
5552
5553 // Keep the base methods that were overriden or introduced in the subclass
5554 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005555 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5556 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5557 NamedDecl *ND = *I;
5558 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005559 ND = shad->getTargetDecl();
5560 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5561 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005562 }
5563
5564 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5565 !Data.OverloadedMethods.empty()) {
5566 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5567 << MD << (Data.OverloadedMethods.size() > 1);
5568
5569 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5570 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005571 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005572 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005573 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5574 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005575 }
5576 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005577}
5578
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005579void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005580 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005581 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005582 SourceLocation RBrac,
5583 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005584 if (!TagDecl)
5585 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005586
Douglas Gregor42af25f2009-05-11 19:58:34 +00005587 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005588
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005589 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5590 if (l->getKind() != AttributeList::AT_Visibility)
5591 continue;
5592 l->setInvalid();
5593 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5594 l->getName();
5595 }
5596
David Blaikie77b6de02011-09-22 02:58:26 +00005597 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005598 // strict aliasing violation!
5599 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005600 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005601
Douglas Gregor23c94db2010-07-02 17:43:08 +00005602 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005603 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005604}
5605
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005606/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5607/// special functions, such as the default constructor, copy
5608/// constructor, or destructor, to the given C++ class (C++
5609/// [special]p1). This routine can only be executed just before the
5610/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005611void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005612 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005613 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005614
Richard Smithbc2a35d2012-12-08 08:32:28 +00005615 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005616 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005617
Richard Smithbc2a35d2012-12-08 08:32:28 +00005618 // If the properties or semantics of the copy constructor couldn't be
5619 // determined while the class was being declared, force a declaration
5620 // of it now.
5621 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5622 DeclareImplicitCopyConstructor(ClassDecl);
5623 }
5624
Richard Smith80ad52f2013-01-02 11:42:31 +00005625 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005626 ++ASTContext::NumImplicitMoveConstructors;
5627
Richard Smithbc2a35d2012-12-08 08:32:28 +00005628 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5629 DeclareImplicitMoveConstructor(ClassDecl);
5630 }
5631
Douglas Gregora376d102010-07-02 21:50:04 +00005632 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5633 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005634
5635 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005636 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005637 // it shows up in the right place in the vtable and that we diagnose
5638 // problems with the implicit exception specification.
5639 if (ClassDecl->isDynamicClass() ||
5640 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005641 DeclareImplicitCopyAssignment(ClassDecl);
5642 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005643
Richard Smith80ad52f2013-01-02 11:42:31 +00005644 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005645 ++ASTContext::NumImplicitMoveAssignmentOperators;
5646
5647 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005648 if (ClassDecl->isDynamicClass() ||
5649 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005650 DeclareImplicitMoveAssignment(ClassDecl);
5651 }
5652
Douglas Gregor4923aa22010-07-02 20:37:36 +00005653 if (!ClassDecl->hasUserDeclaredDestructor()) {
5654 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005655
5656 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005657 // have to declare the destructor immediately. This ensures that, e.g., it
5658 // shows up in the right place in the vtable and that we diagnose problems
5659 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005660 if (ClassDecl->isDynamicClass() ||
5661 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005662 DeclareImplicitDestructor(ClassDecl);
5663 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005664}
5665
Francois Pichet8387e2a2011-04-22 22:18:13 +00005666void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5667 if (!D)
5668 return;
5669
5670 int NumParamList = D->getNumTemplateParameterLists();
5671 for (int i = 0; i < NumParamList; i++) {
5672 TemplateParameterList* Params = D->getTemplateParameterList(i);
5673 for (TemplateParameterList::iterator Param = Params->begin(),
5674 ParamEnd = Params->end();
5675 Param != ParamEnd; ++Param) {
5676 NamedDecl *Named = cast<NamedDecl>(*Param);
5677 if (Named->getDeclName()) {
5678 S->AddDecl(Named);
5679 IdResolver.AddDecl(Named);
5680 }
5681 }
5682 }
5683}
5684
John McCalld226f652010-08-21 09:40:31 +00005685void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005686 if (!D)
5687 return;
5688
5689 TemplateParameterList *Params = 0;
5690 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5691 Params = Template->getTemplateParameters();
5692 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5693 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5694 Params = PartialSpec->getTemplateParameters();
5695 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005696 return;
5697
Douglas Gregor6569d682009-05-27 23:11:45 +00005698 for (TemplateParameterList::iterator Param = Params->begin(),
5699 ParamEnd = Params->end();
5700 Param != ParamEnd; ++Param) {
5701 NamedDecl *Named = cast<NamedDecl>(*Param);
5702 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005703 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005704 IdResolver.AddDecl(Named);
5705 }
5706 }
5707}
5708
John McCalld226f652010-08-21 09:40:31 +00005709void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005710 if (!RecordD) return;
5711 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005712 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005713 PushDeclContext(S, Record);
5714}
5715
John McCalld226f652010-08-21 09:40:31 +00005716void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005717 if (!RecordD) return;
5718 PopDeclContext();
5719}
5720
Douglas Gregor72b505b2008-12-16 21:30:33 +00005721/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5722/// parsing a top-level (non-nested) C++ class, and we are now
5723/// parsing those parts of the given Method declaration that could
5724/// not be parsed earlier (C++ [class.mem]p2), such as default
5725/// arguments. This action should enter the scope of the given
5726/// Method declaration as if we had just parsed the qualified method
5727/// name. However, it should not bring the parameters into scope;
5728/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005729void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005730}
5731
5732/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5733/// C++ method declaration. We're (re-)introducing the given
5734/// function parameter into scope for use in parsing later parts of
5735/// the method declaration. For example, we could see an
5736/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005737void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005738 if (!ParamD)
5739 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005740
John McCalld226f652010-08-21 09:40:31 +00005741 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005742
5743 // If this parameter has an unparsed default argument, clear it out
5744 // to make way for the parsed default argument.
5745 if (Param->hasUnparsedDefaultArg())
5746 Param->setDefaultArg(0);
5747
John McCalld226f652010-08-21 09:40:31 +00005748 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005749 if (Param->getDeclName())
5750 IdResolver.AddDecl(Param);
5751}
5752
5753/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5754/// processing the delayed method declaration for Method. The method
5755/// declaration is now considered finished. There may be a separate
5756/// ActOnStartOfFunctionDef action later (not necessarily
5757/// immediately!) for this method, if it was also defined inside the
5758/// class body.
John McCalld226f652010-08-21 09:40:31 +00005759void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005760 if (!MethodD)
5761 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005763 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005764
John McCalld226f652010-08-21 09:40:31 +00005765 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005766
5767 // Now that we have our default arguments, check the constructor
5768 // again. It could produce additional diagnostics or affect whether
5769 // the class has implicitly-declared destructors, among other
5770 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005771 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5772 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005773
5774 // Check the default arguments, which we may have added.
5775 if (!Method->isInvalidDecl())
5776 CheckCXXDefaultArguments(Method);
5777}
5778
Douglas Gregor42a552f2008-11-05 20:51:48 +00005779/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005780/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005781/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005782/// emit diagnostics and set the invalid bit to true. In any case, the type
5783/// will be updated to reflect a well-formed type for the constructor and
5784/// returned.
5785QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005786 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005787 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005788
5789 // C++ [class.ctor]p3:
5790 // A constructor shall not be virtual (10.3) or static (9.4). A
5791 // constructor can be invoked for a const, volatile or const
5792 // volatile object. A constructor shall not be declared const,
5793 // volatile, or const volatile (9.3.2).
5794 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005795 if (!D.isInvalidType())
5796 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5797 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5798 << SourceRange(D.getIdentifierLoc());
5799 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005800 }
John McCalld931b082010-08-26 03:08:43 +00005801 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005802 if (!D.isInvalidType())
5803 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5804 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5805 << SourceRange(D.getIdentifierLoc());
5806 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005807 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005808 }
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005810 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005811 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005812 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005813 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5814 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005815 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5817 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005818 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5820 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005821 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005822 }
Mike Stump1eb44332009-09-09 15:08:12 +00005823
Douglas Gregorc938c162011-01-26 05:01:58 +00005824 // C++0x [class.ctor]p4:
5825 // A constructor shall not be declared with a ref-qualifier.
5826 if (FTI.hasRefQualifier()) {
5827 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5828 << FTI.RefQualifierIsLValueRef
5829 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5830 D.setInvalidType();
5831 }
5832
Douglas Gregor42a552f2008-11-05 20:51:48 +00005833 // Rebuild the function type "R" without any type qualifiers (in
5834 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005835 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005836 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005837 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5838 return R;
5839
5840 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5841 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005842 EPI.RefQualifier = RQ_None;
5843
Richard Smith07b0fdc2013-03-18 21:12:30 +00005844 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005845}
5846
Douglas Gregor72b505b2008-12-16 21:30:33 +00005847/// CheckConstructor - Checks a fully-formed constructor for
5848/// well-formedness, issuing any diagnostics required. Returns true if
5849/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005850void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005851 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005852 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5853 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005854 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005855
5856 // C++ [class.copy]p3:
5857 // A declaration of a constructor for a class X is ill-formed if
5858 // its first parameter is of type (optionally cv-qualified) X and
5859 // either there are no other parameters or else all other
5860 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005861 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005862 ((Constructor->getNumParams() == 1) ||
5863 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005864 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5865 Constructor->getTemplateSpecializationKind()
5866 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005867 QualType ParamType = Constructor->getParamDecl(0)->getType();
5868 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5869 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005870 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005871 const char *ConstRef
5872 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5873 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005874 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005875 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005876
5877 // FIXME: Rather that making the constructor invalid, we should endeavor
5878 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005879 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005880 }
5881 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005882}
5883
John McCall15442822010-08-04 01:04:25 +00005884/// CheckDestructor - Checks a fully-formed destructor definition for
5885/// well-formedness, issuing any diagnostics required. Returns true
5886/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005887bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005888 CXXRecordDecl *RD = Destructor->getParent();
5889
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005890 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005891 SourceLocation Loc;
5892
5893 if (!Destructor->isImplicit())
5894 Loc = Destructor->getLocation();
5895 else
5896 Loc = RD->getLocation();
5897
5898 // If we have a virtual destructor, look up the deallocation function
5899 FunctionDecl *OperatorDelete = 0;
5900 DeclarationName Name =
5901 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005902 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005903 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005904
Eli Friedman5f2987c2012-02-02 03:46:19 +00005905 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005906
5907 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005908 }
Anders Carlsson37909802009-11-30 21:24:50 +00005909
5910 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005911}
5912
Mike Stump1eb44332009-09-09 15:08:12 +00005913static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005914FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5915 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5916 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005917 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005918}
5919
Douglas Gregor42a552f2008-11-05 20:51:48 +00005920/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5921/// the well-formednes of the destructor declarator @p D with type @p
5922/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005923/// emit diagnostics and set the declarator to invalid. Even if this happens,
5924/// will be updated to reflect a well-formed type for the destructor and
5925/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005926QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005927 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005928 // C++ [class.dtor]p1:
5929 // [...] A typedef-name that names a class is a class-name
5930 // (7.1.3); however, a typedef-name that names a class shall not
5931 // be used as the identifier in the declarator for a destructor
5932 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005933 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005934 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005935 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005936 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005937 else if (const TemplateSpecializationType *TST =
5938 DeclaratorType->getAs<TemplateSpecializationType>())
5939 if (TST->isTypeAlias())
5940 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5941 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005942
5943 // C++ [class.dtor]p2:
5944 // A destructor is used to destroy objects of its class type. A
5945 // destructor takes no parameters, and no return type can be
5946 // specified for it (not even void). The address of a destructor
5947 // shall not be taken. A destructor shall not be static. A
5948 // destructor can be invoked for a const, volatile or const
5949 // volatile object. A destructor shall not be declared const,
5950 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005951 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005952 if (!D.isInvalidType())
5953 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5954 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005955 << SourceRange(D.getIdentifierLoc())
5956 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5957
John McCalld931b082010-08-26 03:08:43 +00005958 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005959 }
Chris Lattner65401802009-04-25 08:28:21 +00005960 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005961 // Destructors don't have return types, but the parser will
5962 // happily parse something like:
5963 //
5964 // class X {
5965 // float ~X();
5966 // };
5967 //
5968 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005969 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5970 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5971 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005974 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005975 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005976 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5978 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005979 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5981 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005982 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5984 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005985 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005986 }
5987
Douglas Gregorc938c162011-01-26 05:01:58 +00005988 // C++0x [class.dtor]p2:
5989 // A destructor shall not be declared with a ref-qualifier.
5990 if (FTI.hasRefQualifier()) {
5991 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5992 << FTI.RefQualifierIsLValueRef
5993 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5994 D.setInvalidType();
5995 }
5996
Douglas Gregor42a552f2008-11-05 20:51:48 +00005997 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005998 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005999 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6000
6001 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006002 FTI.freeArgs();
6003 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006004 }
6005
Mike Stump1eb44332009-09-09 15:08:12 +00006006 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006007 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006008 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006009 D.setInvalidType();
6010 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006011
6012 // Rebuild the function type "R" without any type qualifiers or
6013 // parameters (in case any of the errors above fired) and with
6014 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006015 // types.
John McCalle23cf432010-12-14 08:05:40 +00006016 if (!D.isInvalidType())
6017 return R;
6018
Douglas Gregord92ec472010-07-01 05:10:53 +00006019 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006020 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6021 EPI.Variadic = false;
6022 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006023 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006024 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006025}
6026
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006027/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6028/// well-formednes of the conversion function declarator @p D with
6029/// type @p R. If there are any errors in the declarator, this routine
6030/// will emit diagnostics and return true. Otherwise, it will return
6031/// false. Either way, the type @p R will be updated to reflect a
6032/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006033void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006034 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006035 // C++ [class.conv.fct]p1:
6036 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006037 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006038 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006039 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006040 if (!D.isInvalidType())
6041 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6042 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6043 << SourceRange(D.getIdentifierLoc());
6044 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006045 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006046 }
John McCalla3f81372010-04-13 00:04:31 +00006047
6048 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6049
Chris Lattner6e475012009-04-25 08:35:12 +00006050 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006051 // Conversion functions don't have return types, but the parser will
6052 // happily parse something like:
6053 //
6054 // class X {
6055 // float operator bool();
6056 // };
6057 //
6058 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006059 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6060 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6061 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006062 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006063 }
6064
John McCalla3f81372010-04-13 00:04:31 +00006065 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6066
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006067 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006068 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006069 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6070
6071 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006072 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006073 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006074 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006075 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006076 D.setInvalidType();
6077 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006078
John McCalla3f81372010-04-13 00:04:31 +00006079 // Diagnose "&operator bool()" and other such nonsense. This
6080 // is actually a gcc extension which we don't support.
6081 if (Proto->getResultType() != ConvType) {
6082 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6083 << Proto->getResultType();
6084 D.setInvalidType();
6085 ConvType = Proto->getResultType();
6086 }
6087
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006088 // C++ [class.conv.fct]p4:
6089 // The conversion-type-id shall not represent a function type nor
6090 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006091 if (ConvType->isArrayType()) {
6092 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6093 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006094 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006095 } else if (ConvType->isFunctionType()) {
6096 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6097 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006098 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006099 }
6100
6101 // Rebuild the function type "R" without any parameters (in case any
6102 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006103 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006104 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006105 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006106
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006107 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006108 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006109 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006110 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006111 diag::warn_cxx98_compat_explicit_conversion_functions :
6112 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006113 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006114}
6115
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006116/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6117/// the declaration of the given C++ conversion function. This routine
6118/// is responsible for recording the conversion function in the C++
6119/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006120Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 assert(Conversion && "Expected to receive a conversion function declaration");
6122
Douglas Gregor9d350972008-12-12 08:25:50 +00006123 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006124
6125 // Make sure we aren't redeclaring the conversion function.
6126 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006127
6128 // C++ [class.conv.fct]p1:
6129 // [...] A conversion function is never used to convert a
6130 // (possibly cv-qualified) object to the (possibly cv-qualified)
6131 // same object type (or a reference to it), to a (possibly
6132 // cv-qualified) base class of that type (or a reference to it),
6133 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006134 // FIXME: Suppress this warning if the conversion function ends up being a
6135 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006136 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006137 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006138 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006139 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006140 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6141 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006142 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006143 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006144 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6145 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006146 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006147 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006148 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006149 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006150 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006151 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006152 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006153 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006154 }
6155
Douglas Gregore80622f2010-09-29 04:25:11 +00006156 if (FunctionTemplateDecl *ConversionTemplate
6157 = Conversion->getDescribedFunctionTemplate())
6158 return ConversionTemplate;
6159
John McCalld226f652010-08-21 09:40:31 +00006160 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006161}
6162
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006163//===----------------------------------------------------------------------===//
6164// Namespace Handling
6165//===----------------------------------------------------------------------===//
6166
Richard Smithd1a55a62012-10-04 22:13:39 +00006167/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6168/// reopened.
6169static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6170 SourceLocation Loc,
6171 IdentifierInfo *II, bool *IsInline,
6172 NamespaceDecl *PrevNS) {
6173 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006174
Richard Smithc969e6a2012-10-05 01:46:25 +00006175 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6176 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6177 // inline namespaces, with the intention of bringing names into namespace std.
6178 //
6179 // We support this just well enough to get that case working; this is not
6180 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006181 if (*IsInline && II && II->getName().startswith("__atomic") &&
6182 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006183 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006184 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6185 NS = NS->getPreviousDecl())
6186 NS->setInline(*IsInline);
6187 // Patch up the lookup table for the containing namespace. This isn't really
6188 // correct, but it's good enough for this particular case.
6189 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6190 E = PrevNS->decls_end(); I != E; ++I)
6191 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6192 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6193 return;
6194 }
6195
6196 if (PrevNS->isInline())
6197 // The user probably just forgot the 'inline', so suggest that it
6198 // be added back.
6199 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6200 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6201 else
6202 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6203 << IsInline;
6204
6205 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6206 *IsInline = PrevNS->isInline();
6207}
John McCallea318642010-08-26 09:15:37 +00006208
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006209/// ActOnStartNamespaceDef - This is called at the start of a namespace
6210/// definition.
John McCalld226f652010-08-21 09:40:31 +00006211Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006212 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006213 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006214 SourceLocation IdentLoc,
6215 IdentifierInfo *II,
6216 SourceLocation LBrace,
6217 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006218 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6219 // For anonymous namespace, take the location of the left brace.
6220 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006221 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006222 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006223 bool IsStd = false;
6224 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006225 Scope *DeclRegionScope = NamespcScope->getParent();
6226
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006227 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006228 if (II) {
6229 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006230 // The identifier in an original-namespace-definition shall not
6231 // have been previously defined in the declarative region in
6232 // which the original-namespace-definition appears. The
6233 // identifier in an original-namespace-definition is the name of
6234 // the namespace. Subsequently in that declarative region, it is
6235 // treated as an original-namespace-name.
6236 //
6237 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006238 // look through using directives, just look for any ordinary names.
6239
6240 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006241 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6242 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006243 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006244 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6245 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6246 ++I) {
6247 if ((*I)->getIdentifierNamespace() & IDNS) {
6248 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006249 break;
6250 }
6251 }
6252
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006253 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6254
6255 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006256 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006257 if (IsInline != PrevNS->isInline())
6258 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6259 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006260 } else if (PrevDecl) {
6261 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006262 Diag(Loc, diag::err_redefinition_different_kind)
6263 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006264 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006265 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006266 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006267 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006268 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006269 // This is the first "real" definition of the namespace "std", so update
6270 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006271 PrevNS = getStdNamespace();
6272 IsStd = true;
6273 AddToKnown = !IsInline;
6274 } else {
6275 // We've seen this namespace for the first time.
6276 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006277 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006278 } else {
John McCall9aeed322009-10-01 00:25:31 +00006279 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006280
6281 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006282 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006283 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006284 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006285 } else {
6286 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006287 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006288 }
6289
Richard Smithd1a55a62012-10-04 22:13:39 +00006290 if (PrevNS && IsInline != PrevNS->isInline())
6291 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6292 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006293 }
6294
6295 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6296 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006297 if (IsInvalid)
6298 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006299
6300 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006301
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006302 // FIXME: Should we be merging attributes?
6303 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006304 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006305
6306 if (IsStd)
6307 StdNamespace = Namespc;
6308 if (AddToKnown)
6309 KnownNamespaces[Namespc] = false;
6310
6311 if (II) {
6312 PushOnScopeChains(Namespc, DeclRegionScope);
6313 } else {
6314 // Link the anonymous namespace into its parent.
6315 DeclContext *Parent = CurContext->getRedeclContext();
6316 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6317 TU->setAnonymousNamespace(Namespc);
6318 } else {
6319 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006320 }
John McCall9aeed322009-10-01 00:25:31 +00006321
Douglas Gregora4181472010-03-24 00:46:35 +00006322 CurContext->addDecl(Namespc);
6323
John McCall9aeed322009-10-01 00:25:31 +00006324 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6325 // behaves as if it were replaced by
6326 // namespace unique { /* empty body */ }
6327 // using namespace unique;
6328 // namespace unique { namespace-body }
6329 // where all occurrences of 'unique' in a translation unit are
6330 // replaced by the same identifier and this identifier differs
6331 // from all other identifiers in the entire program.
6332
6333 // We just create the namespace with an empty name and then add an
6334 // implicit using declaration, just like the standard suggests.
6335 //
6336 // CodeGen enforces the "universally unique" aspect by giving all
6337 // declarations semantically contained within an anonymous
6338 // namespace internal linkage.
6339
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006340 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006341 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006342 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006343 /* 'using' */ LBrace,
6344 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006345 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006346 /* identifier */ SourceLocation(),
6347 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006348 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006349 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006350 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006351 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006352 }
6353
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006354 ActOnDocumentableDecl(Namespc);
6355
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006356 // Although we could have an invalid decl (i.e. the namespace name is a
6357 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006358 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6359 // for the namespace has the declarations that showed up in that particular
6360 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006361 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006362 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006363}
6364
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006365/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6366/// is a namespace alias, returns the namespace it points to.
6367static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6368 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6369 return AD->getNamespace();
6370 return dyn_cast_or_null<NamespaceDecl>(D);
6371}
6372
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006373/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6374/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006375void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006376 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6377 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006378 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006379 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006380 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006381 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006382}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006383
John McCall384aff82010-08-25 07:42:41 +00006384CXXRecordDecl *Sema::getStdBadAlloc() const {
6385 return cast_or_null<CXXRecordDecl>(
6386 StdBadAlloc.get(Context.getExternalSource()));
6387}
6388
6389NamespaceDecl *Sema::getStdNamespace() const {
6390 return cast_or_null<NamespaceDecl>(
6391 StdNamespace.get(Context.getExternalSource()));
6392}
6393
Douglas Gregor66992202010-06-29 17:53:46 +00006394/// \brief Retrieve the special "std" namespace, which may require us to
6395/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006396NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006397 if (!StdNamespace) {
6398 // The "std" namespace has not yet been defined, so build one implicitly.
6399 StdNamespace = NamespaceDecl::Create(Context,
6400 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006401 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006402 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006403 &PP.getIdentifierTable().get("std"),
6404 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006405 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006406 }
6407
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006408 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006409}
6410
Sebastian Redl395e04d2012-01-17 22:49:33 +00006411bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006412 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006413 "Looking for std::initializer_list outside of C++.");
6414
6415 // We're looking for implicit instantiations of
6416 // template <typename E> class std::initializer_list.
6417
6418 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6419 return false;
6420
Sebastian Redl84760e32012-01-17 22:49:58 +00006421 ClassTemplateDecl *Template = 0;
6422 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006423
Sebastian Redl84760e32012-01-17 22:49:58 +00006424 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006425
Sebastian Redl84760e32012-01-17 22:49:58 +00006426 ClassTemplateSpecializationDecl *Specialization =
6427 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6428 if (!Specialization)
6429 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006430
Sebastian Redl84760e32012-01-17 22:49:58 +00006431 Template = Specialization->getSpecializedTemplate();
6432 Arguments = Specialization->getTemplateArgs().data();
6433 } else if (const TemplateSpecializationType *TST =
6434 Ty->getAs<TemplateSpecializationType>()) {
6435 Template = dyn_cast_or_null<ClassTemplateDecl>(
6436 TST->getTemplateName().getAsTemplateDecl());
6437 Arguments = TST->getArgs();
6438 }
6439 if (!Template)
6440 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006441
6442 if (!StdInitializerList) {
6443 // Haven't recognized std::initializer_list yet, maybe this is it.
6444 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6445 if (TemplateClass->getIdentifier() !=
6446 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006447 !getStdNamespace()->InEnclosingNamespaceSetOf(
6448 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006449 return false;
6450 // This is a template called std::initializer_list, but is it the right
6451 // template?
6452 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006453 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006454 return false;
6455 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6456 return false;
6457
6458 // It's the right template.
6459 StdInitializerList = Template;
6460 }
6461
6462 if (Template != StdInitializerList)
6463 return false;
6464
6465 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006466 if (Element)
6467 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006468 return true;
6469}
6470
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006471static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6472 NamespaceDecl *Std = S.getStdNamespace();
6473 if (!Std) {
6474 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6475 return 0;
6476 }
6477
6478 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6479 Loc, Sema::LookupOrdinaryName);
6480 if (!S.LookupQualifiedName(Result, Std)) {
6481 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6482 return 0;
6483 }
6484 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6485 if (!Template) {
6486 Result.suppressDiagnostics();
6487 // We found something weird. Complain about the first thing we found.
6488 NamedDecl *Found = *Result.begin();
6489 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6490 return 0;
6491 }
6492
6493 // We found some template called std::initializer_list. Now verify that it's
6494 // correct.
6495 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006496 if (Params->getMinRequiredArguments() != 1 ||
6497 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006498 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6499 return 0;
6500 }
6501
6502 return Template;
6503}
6504
6505QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6506 if (!StdInitializerList) {
6507 StdInitializerList = LookupStdInitializerList(*this, Loc);
6508 if (!StdInitializerList)
6509 return QualType();
6510 }
6511
6512 TemplateArgumentListInfo Args(Loc, Loc);
6513 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6514 Context.getTrivialTypeSourceInfo(Element,
6515 Loc)));
6516 return Context.getCanonicalType(
6517 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6518}
6519
Sebastian Redl98d36062012-01-17 22:50:14 +00006520bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6521 // C++ [dcl.init.list]p2:
6522 // A constructor is an initializer-list constructor if its first parameter
6523 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6524 // std::initializer_list<E> for some type E, and either there are no other
6525 // parameters or else all other parameters have default arguments.
6526 if (Ctor->getNumParams() < 1 ||
6527 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6528 return false;
6529
6530 QualType ArgType = Ctor->getParamDecl(0)->getType();
6531 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6532 ArgType = RT->getPointeeType().getUnqualifiedType();
6533
6534 return isStdInitializerList(ArgType, 0);
6535}
6536
Douglas Gregor9172aa62011-03-26 22:25:30 +00006537/// \brief Determine whether a using statement is in a context where it will be
6538/// apply in all contexts.
6539static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6540 switch (CurContext->getDeclKind()) {
6541 case Decl::TranslationUnit:
6542 return true;
6543 case Decl::LinkageSpec:
6544 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6545 default:
6546 return false;
6547 }
6548}
6549
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006550namespace {
6551
6552// Callback to only accept typo corrections that are namespaces.
6553class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6554 public:
6555 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6556 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6557 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6558 }
6559 return false;
6560 }
6561};
6562
6563}
6564
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006565static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6566 CXXScopeSpec &SS,
6567 SourceLocation IdentLoc,
6568 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006569 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006570 R.clear();
6571 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006572 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006573 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006574 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6575 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006576 if (DeclContext *DC = S.computeDeclContext(SS, false))
6577 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6578 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006579 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6580 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006581 else
6582 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6583 << Ident << CorrectedQuotedStr
6584 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006585
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006586 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6587 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006588
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006589 R.addDecl(Corrected.getCorrectionDecl());
6590 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006591 }
6592 return false;
6593}
6594
John McCalld226f652010-08-21 09:40:31 +00006595Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006596 SourceLocation UsingLoc,
6597 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006598 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006599 SourceLocation IdentLoc,
6600 IdentifierInfo *NamespcName,
6601 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006602 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6603 assert(NamespcName && "Invalid NamespcName.");
6604 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006605
6606 // This can only happen along a recovery path.
6607 while (S->getFlags() & Scope::TemplateParamScope)
6608 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006609 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006610
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006611 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006612 NestedNameSpecifier *Qualifier = 0;
6613 if (SS.isSet())
6614 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6615
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006616 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006617 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6618 LookupParsedName(R, S, &SS);
6619 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006620 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006621
Douglas Gregor66992202010-06-29 17:53:46 +00006622 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006623 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006624 // Allow "using namespace std;" or "using namespace ::std;" even if
6625 // "std" hasn't been defined yet, for GCC compatibility.
6626 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6627 NamespcName->isStr("std")) {
6628 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006629 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006630 R.resolveKind();
6631 }
6632 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006633 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006634 }
6635
John McCallf36e02d2009-10-09 21:13:30 +00006636 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006637 NamedDecl *Named = R.getFoundDecl();
6638 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6639 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006640 // C++ [namespace.udir]p1:
6641 // A using-directive specifies that the names in the nominated
6642 // namespace can be used in the scope in which the
6643 // using-directive appears after the using-directive. During
6644 // unqualified name lookup (3.4.1), the names appear as if they
6645 // were declared in the nearest enclosing namespace which
6646 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006647 // namespace. [Note: in this context, "contains" means "contains
6648 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006649
6650 // Find enclosing context containing both using-directive and
6651 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006652 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006653 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6654 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6655 CommonAncestor = CommonAncestor->getParent();
6656
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006657 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006658 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006659 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006660
Douglas Gregor9172aa62011-03-26 22:25:30 +00006661 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006662 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006663 Diag(IdentLoc, diag::warn_using_directive_in_header);
6664 }
6665
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006666 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006667 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006668 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006669 }
6670
Richard Smith6b3d3e52013-02-20 19:22:51 +00006671 if (UDir)
6672 ProcessDeclAttributeList(S, UDir, AttrList);
6673
John McCalld226f652010-08-21 09:40:31 +00006674 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006675}
6676
6677void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006678 // If the scope has an associated entity and the using directive is at
6679 // namespace or translation unit scope, add the UsingDirectiveDecl into
6680 // its lookup structure so qualified name lookup can find it.
6681 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6682 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006683 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006684 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006685 // Otherwise, it is at block sope. The using-directives will affect lookup
6686 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006687 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006688}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006689
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006690
John McCalld226f652010-08-21 09:40:31 +00006691Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006692 AccessSpecifier AS,
6693 bool HasUsingKeyword,
6694 SourceLocation UsingLoc,
6695 CXXScopeSpec &SS,
6696 UnqualifiedId &Name,
6697 AttributeList *AttrList,
6698 bool IsTypeName,
6699 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006700 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006701
Douglas Gregor12c118a2009-11-04 16:30:06 +00006702 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006703 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006704 case UnqualifiedId::IK_Identifier:
6705 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006706 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006707 case UnqualifiedId::IK_ConversionFunctionId:
6708 break;
6709
6710 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006711 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006712 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006713 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006714 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006715 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006716 diag::err_using_decl_constructor)
6717 << SS.getRange();
6718
Richard Smith80ad52f2013-01-02 11:42:31 +00006719 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006720
John McCalld226f652010-08-21 09:40:31 +00006721 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006722
6723 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006724 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006725 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006726 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006727
6728 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006729 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006730 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006731 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006732 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006733
6734 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6735 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006736 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006737 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006738
Richard Smith07b0fdc2013-03-18 21:12:30 +00006739 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006740 // TODO: store that the declaration was written without 'using' and
6741 // talk about access decls instead of using decls in the
6742 // diagnostics.
6743 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006744 UsingLoc = Name.getLocStart();
Richard Smith1b2209f2013-06-13 02:12:17 +00006745
6746 Diag(UsingLoc,
6747 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6748 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006749 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006750 }
6751
Douglas Gregor56c04582010-12-16 00:46:58 +00006752 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6753 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6754 return 0;
6755
John McCall9488ea12009-11-17 05:59:44 +00006756 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006757 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006758 /* IsInstantiation */ false,
6759 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006760 if (UD)
6761 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006762
John McCalld226f652010-08-21 09:40:31 +00006763 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006764}
6765
Douglas Gregor09acc982010-07-07 23:08:52 +00006766/// \brief Determine whether a using declaration considers the given
6767/// declarations as "equivalent", e.g., if they are redeclarations of
6768/// the same entity or are both typedefs of the same type.
6769static bool
6770IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6771 bool &SuppressRedeclaration) {
6772 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6773 SuppressRedeclaration = false;
6774 return true;
6775 }
6776
Richard Smith162e1c12011-04-15 14:24:37 +00006777 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6778 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006779 SuppressRedeclaration = true;
6780 return Context.hasSameType(TD1->getUnderlyingType(),
6781 TD2->getUnderlyingType());
6782 }
6783
6784 return false;
6785}
6786
6787
John McCall9f54ad42009-12-10 09:41:52 +00006788/// Determines whether to create a using shadow decl for a particular
6789/// decl, given the set of decls existing prior to this using lookup.
6790bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6791 const LookupResult &Previous) {
6792 // Diagnose finding a decl which is not from a base class of the
6793 // current class. We do this now because there are cases where this
6794 // function will silently decide not to build a shadow decl, which
6795 // will pre-empt further diagnostics.
6796 //
6797 // We don't need to do this in C++0x because we do the check once on
6798 // the qualifier.
6799 //
6800 // FIXME: diagnose the following if we care enough:
6801 // struct A { int foo; };
6802 // struct B : A { using A::foo; };
6803 // template <class T> struct C : A {};
6804 // template <class T> struct D : C<T> { using B::foo; } // <---
6805 // This is invalid (during instantiation) in C++03 because B::foo
6806 // resolves to the using decl in B, which is not a base class of D<T>.
6807 // We can't diagnose it immediately because C<T> is an unknown
6808 // specialization. The UsingShadowDecl in D<T> then points directly
6809 // to A::foo, which will look well-formed when we instantiate.
6810 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006811 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006812 DeclContext *OrigDC = Orig->getDeclContext();
6813
6814 // Handle enums and anonymous structs.
6815 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6816 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6817 while (OrigRec->isAnonymousStructOrUnion())
6818 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6819
6820 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6821 if (OrigDC == CurContext) {
6822 Diag(Using->getLocation(),
6823 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006824 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006825 Diag(Orig->getLocation(), diag::note_using_decl_target);
6826 return true;
6827 }
6828
Douglas Gregordc355712011-02-25 00:36:19 +00006829 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006830 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006831 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006832 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006833 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006834 Diag(Orig->getLocation(), diag::note_using_decl_target);
6835 return true;
6836 }
6837 }
6838
6839 if (Previous.empty()) return false;
6840
6841 NamedDecl *Target = Orig;
6842 if (isa<UsingShadowDecl>(Target))
6843 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6844
John McCalld7533ec2009-12-11 02:33:26 +00006845 // If the target happens to be one of the previous declarations, we
6846 // don't have a conflict.
6847 //
6848 // FIXME: but we might be increasing its access, in which case we
6849 // should redeclare it.
6850 NamedDecl *NonTag = 0, *Tag = 0;
6851 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6852 I != E; ++I) {
6853 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006854 bool Result;
6855 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6856 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006857
6858 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6859 }
6860
John McCall9f54ad42009-12-10 09:41:52 +00006861 if (Target->isFunctionOrFunctionTemplate()) {
6862 FunctionDecl *FD;
6863 if (isa<FunctionTemplateDecl>(Target))
6864 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6865 else
6866 FD = cast<FunctionDecl>(Target);
6867
6868 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006869 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006870 case Ovl_Overload:
6871 return false;
6872
6873 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006874 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006875 break;
6876
6877 // We found a decl with the exact signature.
6878 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006879 // If we're in a record, we want to hide the target, so we
6880 // return true (without a diagnostic) to tell the caller not to
6881 // build a shadow decl.
6882 if (CurContext->isRecord())
6883 return true;
6884
6885 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006886 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006887 break;
6888 }
6889
6890 Diag(Target->getLocation(), diag::note_using_decl_target);
6891 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6892 return true;
6893 }
6894
6895 // Target is not a function.
6896
John McCall9f54ad42009-12-10 09:41:52 +00006897 if (isa<TagDecl>(Target)) {
6898 // No conflict between a tag and a non-tag.
6899 if (!Tag) return false;
6900
John McCall41ce66f2009-12-10 19:51:03 +00006901 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006902 Diag(Target->getLocation(), diag::note_using_decl_target);
6903 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6904 return true;
6905 }
6906
6907 // No conflict between a tag and a non-tag.
6908 if (!NonTag) return false;
6909
John McCall41ce66f2009-12-10 19:51:03 +00006910 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006911 Diag(Target->getLocation(), diag::note_using_decl_target);
6912 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6913 return true;
6914}
6915
John McCall9488ea12009-11-17 05:59:44 +00006916/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006917UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006918 UsingDecl *UD,
6919 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006920
6921 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006922 NamedDecl *Target = Orig;
6923 if (isa<UsingShadowDecl>(Target)) {
6924 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6925 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006926 }
6927
6928 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006929 = UsingShadowDecl::Create(Context, CurContext,
6930 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006931 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006932
6933 Shadow->setAccess(UD->getAccess());
6934 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6935 Shadow->setInvalidDecl();
6936
John McCall9488ea12009-11-17 05:59:44 +00006937 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006938 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006939 else
John McCall604e7f12009-12-08 07:46:18 +00006940 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006941
John McCall604e7f12009-12-08 07:46:18 +00006942
John McCall9f54ad42009-12-10 09:41:52 +00006943 return Shadow;
6944}
John McCall604e7f12009-12-08 07:46:18 +00006945
John McCall9f54ad42009-12-10 09:41:52 +00006946/// Hides a using shadow declaration. This is required by the current
6947/// using-decl implementation when a resolvable using declaration in a
6948/// class is followed by a declaration which would hide or override
6949/// one or more of the using decl's targets; for example:
6950///
6951/// struct Base { void foo(int); };
6952/// struct Derived : Base {
6953/// using Base::foo;
6954/// void foo(int);
6955/// };
6956///
6957/// The governing language is C++03 [namespace.udecl]p12:
6958///
6959/// When a using-declaration brings names from a base class into a
6960/// derived class scope, member functions in the derived class
6961/// override and/or hide member functions with the same name and
6962/// parameter types in a base class (rather than conflicting).
6963///
6964/// There are two ways to implement this:
6965/// (1) optimistically create shadow decls when they're not hidden
6966/// by existing declarations, or
6967/// (2) don't create any shadow decls (or at least don't make them
6968/// visible) until we've fully parsed/instantiated the class.
6969/// The problem with (1) is that we might have to retroactively remove
6970/// a shadow decl, which requires several O(n) operations because the
6971/// decl structures are (very reasonably) not designed for removal.
6972/// (2) avoids this but is very fiddly and phase-dependent.
6973void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006974 if (Shadow->getDeclName().getNameKind() ==
6975 DeclarationName::CXXConversionFunctionName)
6976 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6977
John McCall9f54ad42009-12-10 09:41:52 +00006978 // Remove it from the DeclContext...
6979 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006980
John McCall9f54ad42009-12-10 09:41:52 +00006981 // ...and the scope, if applicable...
6982 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006983 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006984 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006985 }
6986
John McCall9f54ad42009-12-10 09:41:52 +00006987 // ...and the using decl.
6988 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6989
6990 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006991 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006992}
6993
John McCall7ba107a2009-11-18 02:36:19 +00006994/// Builds a using declaration.
6995///
6996/// \param IsInstantiation - Whether this call arises from an
6997/// instantiation of an unresolved using declaration. We treat
6998/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006999NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7000 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007001 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007002 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007003 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007004 bool IsInstantiation,
7005 bool IsTypeName,
7006 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007007 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007008 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007009 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007010
Anders Carlsson550b14b2009-08-28 05:49:21 +00007011 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007012
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007013 if (SS.isEmpty()) {
7014 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007015 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007016 }
Mike Stump1eb44332009-09-09 15:08:12 +00007017
John McCall9f54ad42009-12-10 09:41:52 +00007018 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007019 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007020 ForRedeclaration);
7021 Previous.setHideTags(false);
7022 if (S) {
7023 LookupName(Previous, S);
7024
7025 // It is really dumb that we have to do this.
7026 LookupResult::Filter F = Previous.makeFilter();
7027 while (F.hasNext()) {
7028 NamedDecl *D = F.next();
7029 if (!isDeclInScope(D, CurContext, S))
7030 F.erase();
7031 }
7032 F.done();
7033 } else {
7034 assert(IsInstantiation && "no scope in non-instantiation");
7035 assert(CurContext->isRecord() && "scope not record in instantiation");
7036 LookupQualifiedName(Previous, CurContext);
7037 }
7038
John McCall9f54ad42009-12-10 09:41:52 +00007039 // Check for invalid redeclarations.
7040 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7041 return 0;
7042
7043 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007044 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7045 return 0;
7046
John McCallaf8e6ed2009-11-12 03:15:40 +00007047 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007048 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007049 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007050 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00007051 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00007052 // FIXME: not all declaration name kinds are legal here
7053 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7054 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007055 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007056 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007057 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007058 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7059 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007060 }
John McCalled976492009-12-04 22:46:56 +00007061 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007062 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7063 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007064 }
John McCalled976492009-12-04 22:46:56 +00007065 D->setAccess(AS);
7066 CurContext->addDecl(D);
7067
7068 if (!LookupContext) return D;
7069 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007070
John McCall77bb1aa2010-05-01 00:40:08 +00007071 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007072 UD->setInvalidDecl();
7073 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007074 }
7075
Richard Smithc5a89a12012-04-02 01:30:27 +00007076 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007077 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007078 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007079 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007080 return UD;
7081 }
7082
7083 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007084
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007085 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007086
John McCall604e7f12009-12-08 07:46:18 +00007087 // Unlike most lookups, we don't always want to hide tag
7088 // declarations: tag names are visible through the using declaration
7089 // even if hidden by ordinary names, *except* in a dependent context
7090 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007091 if (!IsInstantiation)
7092 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007093
John McCallb9abd8722012-04-07 03:04:20 +00007094 // For the purposes of this lookup, we have a base object type
7095 // equal to that of the current context.
7096 if (CurContext->isRecord()) {
7097 R.setBaseObjectType(
7098 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7099 }
7100
John McCalla24dc2e2009-11-17 02:14:36 +00007101 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007102
John McCallf36e02d2009-10-09 21:13:30 +00007103 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00007104 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007105 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007106 UD->setInvalidDecl();
7107 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007108 }
7109
John McCalled976492009-12-04 22:46:56 +00007110 if (R.isAmbiguous()) {
7111 UD->setInvalidDecl();
7112 return UD;
7113 }
Mike Stump1eb44332009-09-09 15:08:12 +00007114
John McCall7ba107a2009-11-18 02:36:19 +00007115 if (IsTypeName) {
7116 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007117 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007118 Diag(IdentLoc, diag::err_using_typename_non_type);
7119 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7120 Diag((*I)->getUnderlyingDecl()->getLocation(),
7121 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007122 UD->setInvalidDecl();
7123 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007124 }
7125 } else {
7126 // If we asked for a non-typename and we got a type, error out,
7127 // but only if this is an instantiation of an unresolved using
7128 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007129 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007130 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7131 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007132 UD->setInvalidDecl();
7133 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007134 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007135 }
7136
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007137 // C++0x N2914 [namespace.udecl]p6:
7138 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007139 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007140 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7141 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007142 UD->setInvalidDecl();
7143 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007144 }
Mike Stump1eb44332009-09-09 15:08:12 +00007145
John McCall9f54ad42009-12-10 09:41:52 +00007146 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7147 if (!CheckUsingShadowDecl(UD, *I, Previous))
7148 BuildUsingShadowDecl(S, UD, *I);
7149 }
John McCall9488ea12009-11-17 05:59:44 +00007150
7151 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007152}
7153
Sebastian Redlf677ea32011-02-05 19:23:19 +00007154/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007155bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7156 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007157
Douglas Gregordc355712011-02-25 00:36:19 +00007158 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007159 assert(SourceType &&
7160 "Using decl naming constructor doesn't have type in scope spec.");
7161 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7162
7163 // Check whether the named type is a direct base class.
7164 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7165 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7166 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7167 BaseIt != BaseE; ++BaseIt) {
7168 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7169 if (CanonicalSourceType == BaseType)
7170 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007171 if (BaseIt->getType()->isDependentType())
7172 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007173 }
7174
7175 if (BaseIt == BaseE) {
7176 // Did not find SourceType in the bases.
7177 Diag(UD->getUsingLocation(),
7178 diag::err_using_decl_constructor_not_in_direct_base)
7179 << UD->getNameInfo().getSourceRange()
7180 << QualType(SourceType, 0) << TargetClass;
7181 return true;
7182 }
7183
Richard Smithc5a89a12012-04-02 01:30:27 +00007184 if (!CurContext->isDependentContext())
7185 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007186
7187 return false;
7188}
7189
John McCall9f54ad42009-12-10 09:41:52 +00007190/// Checks that the given using declaration is not an invalid
7191/// redeclaration. Note that this is checking only for the using decl
7192/// itself, not for any ill-formedness among the UsingShadowDecls.
7193bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7194 bool isTypeName,
7195 const CXXScopeSpec &SS,
7196 SourceLocation NameLoc,
7197 const LookupResult &Prev) {
7198 // C++03 [namespace.udecl]p8:
7199 // C++0x [namespace.udecl]p10:
7200 // A using-declaration is a declaration and can therefore be used
7201 // repeatedly where (and only where) multiple declarations are
7202 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007203 //
John McCall8a726212010-11-29 18:01:58 +00007204 // That's in non-member contexts.
7205 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007206 return false;
7207
7208 NestedNameSpecifier *Qual
7209 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7210
7211 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7212 NamedDecl *D = *I;
7213
7214 bool DTypename;
7215 NestedNameSpecifier *DQual;
7216 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7217 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007218 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007219 } else if (UnresolvedUsingValueDecl *UD
7220 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7221 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007222 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007223 } else if (UnresolvedUsingTypenameDecl *UD
7224 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7225 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007226 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007227 } else continue;
7228
7229 // using decls differ if one says 'typename' and the other doesn't.
7230 // FIXME: non-dependent using decls?
7231 if (isTypeName != DTypename) continue;
7232
7233 // using decls differ if they name different scopes (but note that
7234 // template instantiation can cause this check to trigger when it
7235 // didn't before instantiation).
7236 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7237 Context.getCanonicalNestedNameSpecifier(DQual))
7238 continue;
7239
7240 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007241 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007242 return true;
7243 }
7244
7245 return false;
7246}
7247
John McCall604e7f12009-12-08 07:46:18 +00007248
John McCalled976492009-12-04 22:46:56 +00007249/// Checks that the given nested-name qualifier used in a using decl
7250/// in the current context is appropriately related to the current
7251/// scope. If an error is found, diagnoses it and returns true.
7252bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7253 const CXXScopeSpec &SS,
7254 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007255 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007256
John McCall604e7f12009-12-08 07:46:18 +00007257 if (!CurContext->isRecord()) {
7258 // C++03 [namespace.udecl]p3:
7259 // C++0x [namespace.udecl]p8:
7260 // A using-declaration for a class member shall be a member-declaration.
7261
7262 // If we weren't able to compute a valid scope, it must be a
7263 // dependent class scope.
7264 if (!NamedContext || NamedContext->isRecord()) {
7265 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7266 << SS.getRange();
7267 return true;
7268 }
7269
7270 // Otherwise, everything is known to be fine.
7271 return false;
7272 }
7273
7274 // The current scope is a record.
7275
7276 // If the named context is dependent, we can't decide much.
7277 if (!NamedContext) {
7278 // FIXME: in C++0x, we can diagnose if we can prove that the
7279 // nested-name-specifier does not refer to a base class, which is
7280 // still possible in some cases.
7281
7282 // Otherwise we have to conservatively report that things might be
7283 // okay.
7284 return false;
7285 }
7286
7287 if (!NamedContext->isRecord()) {
7288 // Ideally this would point at the last name in the specifier,
7289 // but we don't have that level of source info.
7290 Diag(SS.getRange().getBegin(),
7291 diag::err_using_decl_nested_name_specifier_is_not_class)
7292 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7293 return true;
7294 }
7295
Douglas Gregor6fb07292010-12-21 07:41:49 +00007296 if (!NamedContext->isDependentContext() &&
7297 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7298 return true;
7299
Richard Smith80ad52f2013-01-02 11:42:31 +00007300 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007301 // C++0x [namespace.udecl]p3:
7302 // In a using-declaration used as a member-declaration, the
7303 // nested-name-specifier shall name a base class of the class
7304 // being defined.
7305
7306 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7307 cast<CXXRecordDecl>(NamedContext))) {
7308 if (CurContext == NamedContext) {
7309 Diag(NameLoc,
7310 diag::err_using_decl_nested_name_specifier_is_current_class)
7311 << SS.getRange();
7312 return true;
7313 }
7314
7315 Diag(SS.getRange().getBegin(),
7316 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7317 << (NestedNameSpecifier*) SS.getScopeRep()
7318 << cast<CXXRecordDecl>(CurContext)
7319 << SS.getRange();
7320 return true;
7321 }
7322
7323 return false;
7324 }
7325
7326 // C++03 [namespace.udecl]p4:
7327 // A using-declaration used as a member-declaration shall refer
7328 // to a member of a base class of the class being defined [etc.].
7329
7330 // Salient point: SS doesn't have to name a base class as long as
7331 // lookup only finds members from base classes. Therefore we can
7332 // diagnose here only if we can prove that that can't happen,
7333 // i.e. if the class hierarchies provably don't intersect.
7334
7335 // TODO: it would be nice if "definitely valid" results were cached
7336 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7337 // need to be repeated.
7338
7339 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007340 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007341
7342 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7343 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7344 Data->Bases.insert(Base);
7345 return true;
7346 }
7347
7348 bool hasDependentBases(const CXXRecordDecl *Class) {
7349 return !Class->forallBases(collect, this);
7350 }
7351
7352 /// Returns true if the base is dependent or is one of the
7353 /// accumulated base classes.
7354 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7355 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7356 return !Data->Bases.count(Base);
7357 }
7358
7359 bool mightShareBases(const CXXRecordDecl *Class) {
7360 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7361 }
7362 };
7363
7364 UserData Data;
7365
7366 // Returns false if we find a dependent base.
7367 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7368 return false;
7369
7370 // Returns false if the class has a dependent base or if it or one
7371 // of its bases is present in the base set of the current context.
7372 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7373 return false;
7374
7375 Diag(SS.getRange().getBegin(),
7376 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7377 << (NestedNameSpecifier*) SS.getScopeRep()
7378 << cast<CXXRecordDecl>(CurContext)
7379 << SS.getRange();
7380
7381 return true;
John McCalled976492009-12-04 22:46:56 +00007382}
7383
Richard Smith162e1c12011-04-15 14:24:37 +00007384Decl *Sema::ActOnAliasDeclaration(Scope *S,
7385 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007386 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007387 SourceLocation UsingLoc,
7388 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007389 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007390 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007391 // Skip up to the relevant declaration scope.
7392 while (S->getFlags() & Scope::TemplateParamScope)
7393 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007394 assert((S->getFlags() & Scope::DeclScope) &&
7395 "got alias-declaration outside of declaration scope");
7396
7397 if (Type.isInvalid())
7398 return 0;
7399
7400 bool Invalid = false;
7401 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7402 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007403 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007404
7405 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7406 return 0;
7407
7408 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007409 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007410 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007411 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7412 TInfo->getTypeLoc().getBeginLoc());
7413 }
Richard Smith162e1c12011-04-15 14:24:37 +00007414
7415 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7416 LookupName(Previous, S);
7417
7418 // Warn about shadowing the name of a template parameter.
7419 if (Previous.isSingleResult() &&
7420 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007421 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007422 Previous.clear();
7423 }
7424
7425 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7426 "name in alias declaration must be an identifier");
7427 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7428 Name.StartLocation,
7429 Name.Identifier, TInfo);
7430
7431 NewTD->setAccess(AS);
7432
7433 if (Invalid)
7434 NewTD->setInvalidDecl();
7435
Richard Smith6b3d3e52013-02-20 19:22:51 +00007436 ProcessDeclAttributeList(S, NewTD, AttrList);
7437
Richard Smith3e4c6c42011-05-05 21:57:07 +00007438 CheckTypedefForVariablyModifiedType(S, NewTD);
7439 Invalid |= NewTD->isInvalidDecl();
7440
Richard Smith162e1c12011-04-15 14:24:37 +00007441 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007442
7443 NamedDecl *NewND;
7444 if (TemplateParamLists.size()) {
7445 TypeAliasTemplateDecl *OldDecl = 0;
7446 TemplateParameterList *OldTemplateParams = 0;
7447
7448 if (TemplateParamLists.size() != 1) {
7449 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007450 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7451 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007452 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007453 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007454
7455 // Only consider previous declarations in the same scope.
7456 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7457 /*ExplicitInstantiationOrSpecialization*/false);
7458 if (!Previous.empty()) {
7459 Redeclaration = true;
7460
7461 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7462 if (!OldDecl && !Invalid) {
7463 Diag(UsingLoc, diag::err_redefinition_different_kind)
7464 << Name.Identifier;
7465
7466 NamedDecl *OldD = Previous.getRepresentativeDecl();
7467 if (OldD->getLocation().isValid())
7468 Diag(OldD->getLocation(), diag::note_previous_definition);
7469
7470 Invalid = true;
7471 }
7472
7473 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7474 if (TemplateParameterListsAreEqual(TemplateParams,
7475 OldDecl->getTemplateParameters(),
7476 /*Complain=*/true,
7477 TPL_TemplateMatch))
7478 OldTemplateParams = OldDecl->getTemplateParameters();
7479 else
7480 Invalid = true;
7481
7482 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7483 if (!Invalid &&
7484 !Context.hasSameType(OldTD->getUnderlyingType(),
7485 NewTD->getUnderlyingType())) {
7486 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7487 // but we can't reasonably accept it.
7488 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7489 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7490 if (OldTD->getLocation().isValid())
7491 Diag(OldTD->getLocation(), diag::note_previous_definition);
7492 Invalid = true;
7493 }
7494 }
7495 }
7496
7497 // Merge any previous default template arguments into our parameters,
7498 // and check the parameter list.
7499 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7500 TPC_TypeAliasTemplate))
7501 return 0;
7502
7503 TypeAliasTemplateDecl *NewDecl =
7504 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7505 Name.Identifier, TemplateParams,
7506 NewTD);
7507
7508 NewDecl->setAccess(AS);
7509
7510 if (Invalid)
7511 NewDecl->setInvalidDecl();
7512 else if (OldDecl)
7513 NewDecl->setPreviousDeclaration(OldDecl);
7514
7515 NewND = NewDecl;
7516 } else {
7517 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7518 NewND = NewTD;
7519 }
Richard Smith162e1c12011-04-15 14:24:37 +00007520
7521 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007522 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007523
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007524 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007525 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007526}
7527
John McCalld226f652010-08-21 09:40:31 +00007528Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007529 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007530 SourceLocation AliasLoc,
7531 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007532 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007533 SourceLocation IdentLoc,
7534 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007535
Anders Carlsson81c85c42009-03-28 23:53:49 +00007536 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007537 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7538 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007539
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007540 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007541 NamedDecl *PrevDecl
7542 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7543 ForRedeclaration);
7544 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7545 PrevDecl = 0;
7546
7547 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007548 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007549 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007550 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007551 // FIXME: At some point, we'll want to create the (redundant)
7552 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007553 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007554 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007555 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007556 }
Mike Stump1eb44332009-09-09 15:08:12 +00007557
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007558 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7559 diag::err_redefinition_different_kind;
7560 Diag(AliasLoc, DiagID) << Alias;
7561 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007562 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007563 }
7564
John McCalla24dc2e2009-11-17 02:14:36 +00007565 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007566 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007567
John McCallf36e02d2009-10-09 21:13:30 +00007568 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007569 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007570 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007571 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007572 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007573 }
Mike Stump1eb44332009-09-09 15:08:12 +00007574
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007575 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007576 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007577 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007578 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007579
John McCall3dbd3d52010-02-16 06:53:13 +00007580 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007581 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007582}
7583
Sean Hunt001cad92011-05-10 00:49:42 +00007584Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007585Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7586 CXXMethodDecl *MD) {
7587 CXXRecordDecl *ClassDecl = MD->getParent();
7588
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007589 // C++ [except.spec]p14:
7590 // An implicitly declared special member function (Clause 12) shall have an
7591 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007592 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007593 if (ClassDecl->isInvalidDecl())
7594 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007595
Sebastian Redl60618fa2011-03-12 11:50:43 +00007596 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007597 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7598 BEnd = ClassDecl->bases_end();
7599 B != BEnd; ++B) {
7600 if (B->isVirtual()) // Handled below.
7601 continue;
7602
Douglas Gregor18274032010-07-03 00:47:00 +00007603 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7604 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007605 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7606 // If this is a deleted function, add it anyway. This might be conformant
7607 // with the standard. This might not. I'm not sure. It might not matter.
7608 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007609 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007610 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007611 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007612
7613 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007614 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7615 BEnd = ClassDecl->vbases_end();
7616 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007617 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007619 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7620 // If this is a deleted function, add it anyway. This might be conformant
7621 // with the standard. This might not. I'm not sure. It might not matter.
7622 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007623 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007624 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007625 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007626
7627 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007628 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7629 FEnd = ClassDecl->field_end();
7630 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007631 if (F->hasInClassInitializer()) {
7632 if (Expr *E = F->getInClassInitializer())
7633 ExceptSpec.CalledExpr(E);
7634 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007635 // DR1351:
7636 // If the brace-or-equal-initializer of a non-static data member
7637 // invokes a defaulted default constructor of its class or of an
7638 // enclosing class in a potentially evaluated subexpression, the
7639 // program is ill-formed.
7640 //
7641 // This resolution is unworkable: the exception specification of the
7642 // default constructor can be needed in an unevaluated context, in
7643 // particular, in the operand of a noexcept-expression, and we can be
7644 // unable to compute an exception specification for an enclosed class.
7645 //
7646 // We do not allow an in-class initializer to require the evaluation
7647 // of the exception specification for any in-class initializer whose
7648 // definition is not lexically complete.
7649 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007650 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007651 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007652 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7653 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7654 // If this is a deleted function, add it anyway. This might be conformant
7655 // with the standard. This might not. I'm not sure. It might not matter.
7656 // In particular, the problem is that this function never gets called. It
7657 // might just be ill-formed because this function attempts to refer to
7658 // a deleted function here.
7659 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007660 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007661 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007662 }
John McCalle23cf432010-12-14 08:05:40 +00007663
Sean Hunt001cad92011-05-10 00:49:42 +00007664 return ExceptSpec;
7665}
7666
Richard Smith07b0fdc2013-03-18 21:12:30 +00007667Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007668Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7669 CXXRecordDecl *ClassDecl = CD->getParent();
7670
7671 // C++ [except.spec]p14:
7672 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007673 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007674 if (ClassDecl->isInvalidDecl())
7675 return ExceptSpec;
7676
7677 // Inherited constructor.
7678 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7679 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7680 // FIXME: Copying or moving the parameters could add extra exceptions to the
7681 // set, as could the default arguments for the inherited constructor. This
7682 // will be addressed when we implement the resolution of core issue 1351.
7683 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7684
7685 // Direct base-class constructors.
7686 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7687 BEnd = ClassDecl->bases_end();
7688 B != BEnd; ++B) {
7689 if (B->isVirtual()) // Handled below.
7690 continue;
7691
7692 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7693 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7694 if (BaseClassDecl == InheritedDecl)
7695 continue;
7696 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7697 if (Constructor)
7698 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7699 }
7700 }
7701
7702 // Virtual base-class constructors.
7703 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7704 BEnd = ClassDecl->vbases_end();
7705 B != BEnd; ++B) {
7706 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7708 if (BaseClassDecl == InheritedDecl)
7709 continue;
7710 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7711 if (Constructor)
7712 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7713 }
7714 }
7715
7716 // Field constructors.
7717 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7718 FEnd = ClassDecl->field_end();
7719 F != FEnd; ++F) {
7720 if (F->hasInClassInitializer()) {
7721 if (Expr *E = F->getInClassInitializer())
7722 ExceptSpec.CalledExpr(E);
7723 else if (!F->isInvalidDecl())
7724 Diag(CD->getLocation(),
7725 diag::err_in_class_initializer_references_def_ctor) << CD;
7726 } else if (const RecordType *RecordTy
7727 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7728 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7729 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7730 if (Constructor)
7731 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7732 }
7733 }
7734
Richard Smith07b0fdc2013-03-18 21:12:30 +00007735 return ExceptSpec;
7736}
7737
Richard Smithafb49182012-11-29 01:34:07 +00007738namespace {
7739/// RAII object to register a special member as being currently declared.
7740struct DeclaringSpecialMember {
7741 Sema &S;
7742 Sema::SpecialMemberDecl D;
7743 bool WasAlreadyBeingDeclared;
7744
7745 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7746 : S(S), D(RD, CSM) {
7747 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7748 if (WasAlreadyBeingDeclared)
7749 // This almost never happens, but if it does, ensure that our cache
7750 // doesn't contain a stale result.
7751 S.SpecialMemberCache.clear();
7752
7753 // FIXME: Register a note to be produced if we encounter an error while
7754 // declaring the special member.
7755 }
7756 ~DeclaringSpecialMember() {
7757 if (!WasAlreadyBeingDeclared)
7758 S.SpecialMembersBeingDeclared.erase(D);
7759 }
7760
7761 /// \brief Are we already trying to declare this special member?
7762 bool isAlreadyBeingDeclared() const {
7763 return WasAlreadyBeingDeclared;
7764 }
7765};
7766}
7767
Sean Hunt001cad92011-05-10 00:49:42 +00007768CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7769 CXXRecordDecl *ClassDecl) {
7770 // C++ [class.ctor]p5:
7771 // A default constructor for a class X is a constructor of class X
7772 // that can be called without an argument. If there is no
7773 // user-declared constructor for class X, a default constructor is
7774 // implicitly declared. An implicitly-declared default constructor
7775 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007776 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007777 "Should not build implicit default constructor!");
7778
Richard Smithafb49182012-11-29 01:34:07 +00007779 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7780 if (DSM.isAlreadyBeingDeclared())
7781 return 0;
7782
Richard Smith7756afa2012-06-10 05:43:50 +00007783 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7784 CXXDefaultConstructor,
7785 false);
7786
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007787 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007788 CanQualType ClassType
7789 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007790 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007791 DeclarationName Name
7792 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007793 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007794 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007795 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007796 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007797 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007798 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007799 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007800 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007801
7802 // Build an exception specification pointing back at this constructor.
7803 FunctionProtoType::ExtProtoInfo EPI;
7804 EPI.ExceptionSpecType = EST_Unevaluated;
7805 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007806 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007807
Richard Smithbc2a35d2012-12-08 08:32:28 +00007808 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7809 // constructors is easy to compute.
7810 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7811
7812 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007813 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007814
Douglas Gregor18274032010-07-03 00:47:00 +00007815 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007816 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007817
Douglas Gregor23c94db2010-07-02 17:43:08 +00007818 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007819 PushOnScopeChains(DefaultCon, S, false);
7820 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007821
Douglas Gregor32df23e2010-07-01 22:02:46 +00007822 return DefaultCon;
7823}
7824
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007825void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7826 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007827 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007828 !Constructor->doesThisDeclarationHaveABody() &&
7829 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007830 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007831
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007832 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007833 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007834
Eli Friedman9a14db32012-10-18 20:14:08 +00007835 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007836 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007837 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007838 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007839 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007840 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007841 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007842 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007843 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007844
7845 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007846 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007847
7848 Constructor->setUsed();
7849 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007850
7851 if (ASTMutationListener *L = getASTMutationListener()) {
7852 L->CompletedImplicitDefinition(Constructor);
7853 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007854}
7855
Richard Smith7a614d82011-06-11 17:19:42 +00007856void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007857 // Check that any explicitly-defaulted methods have exception specifications
7858 // compatible with their implicit exception specifications.
7859 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007860}
7861
Richard Smith4841ca52013-04-10 05:48:59 +00007862namespace {
7863/// Information on inheriting constructors to declare.
7864class InheritingConstructorInfo {
7865public:
7866 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7867 : SemaRef(SemaRef), Derived(Derived) {
7868 // Mark the constructors that we already have in the derived class.
7869 //
7870 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7871 // unless there is a user-declared constructor with the same signature in
7872 // the class where the using-declaration appears.
7873 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7874 }
7875
7876 void inheritAll(CXXRecordDecl *RD) {
7877 visitAll(RD, &InheritingConstructorInfo::inherit);
7878 }
7879
7880private:
7881 /// Information about an inheriting constructor.
7882 struct InheritingConstructor {
7883 InheritingConstructor()
7884 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7885
7886 /// If \c true, a constructor with this signature is already declared
7887 /// in the derived class.
7888 bool DeclaredInDerived;
7889
7890 /// The constructor which is inherited.
7891 const CXXConstructorDecl *BaseCtor;
7892
7893 /// The derived constructor we declared.
7894 CXXConstructorDecl *DerivedCtor;
7895 };
7896
7897 /// Inheriting constructors with a given canonical type. There can be at
7898 /// most one such non-template constructor, and any number of templated
7899 /// constructors.
7900 struct InheritingConstructorsForType {
7901 InheritingConstructor NonTemplate;
7902 llvm::SmallVector<
7903 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7904
7905 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7906 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7907 TemplateParameterList *ParamList = FTD->getTemplateParameters();
7908 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7909 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7910 false, S.TPL_TemplateMatch))
7911 return Templates[I].second;
7912 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7913 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007914 }
Richard Smith4841ca52013-04-10 05:48:59 +00007915
7916 return NonTemplate;
7917 }
7918 };
7919
7920 /// Get or create the inheriting constructor record for a constructor.
7921 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7922 QualType CtorType) {
7923 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7924 .getEntry(SemaRef, Ctor);
7925 }
7926
7927 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7928
7929 /// Process all constructors for a class.
7930 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7931 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7932 CtorE = RD->ctor_end();
7933 CtorIt != CtorE; ++CtorIt)
7934 (this->*Callback)(*CtorIt);
7935 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7936 I(RD->decls_begin()), E(RD->decls_end());
7937 I != E; ++I) {
7938 const FunctionDecl *FD = (*I)->getTemplatedDecl();
7939 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7940 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007941 }
7942 }
Richard Smith4841ca52013-04-10 05:48:59 +00007943
7944 /// Note that a constructor (or constructor template) was declared in Derived.
7945 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7946 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7947 }
7948
7949 /// Inherit a single constructor.
7950 void inherit(const CXXConstructorDecl *Ctor) {
7951 const FunctionProtoType *CtorType =
7952 Ctor->getType()->castAs<FunctionProtoType>();
7953 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7954 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7955
7956 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7957
7958 // Core issue (no number yet): the ellipsis is always discarded.
7959 if (EPI.Variadic) {
7960 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7961 SemaRef.Diag(Ctor->getLocation(),
7962 diag::note_using_decl_constructor_ellipsis);
7963 EPI.Variadic = false;
7964 }
7965
7966 // Declare a constructor for each number of parameters.
7967 //
7968 // C++11 [class.inhctor]p1:
7969 // The candidate set of inherited constructors from the class X named in
7970 // the using-declaration consists of [... modulo defects ...] for each
7971 // constructor or constructor template of X, the set of constructors or
7972 // constructor templates that results from omitting any ellipsis parameter
7973 // specification and successively omitting parameters with a default
7974 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00007975 unsigned MinParams = minParamsToInherit(Ctor);
7976 unsigned Params = Ctor->getNumParams();
7977 if (Params >= MinParams) {
7978 do
7979 declareCtor(UsingLoc, Ctor,
7980 SemaRef.Context.getFunctionType(
7981 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7982 while (Params > MinParams &&
7983 Ctor->getParamDecl(--Params)->hasDefaultArg());
7984 }
Richard Smith4841ca52013-04-10 05:48:59 +00007985 }
7986
7987 /// Find the using-declaration which specified that we should inherit the
7988 /// constructors of \p Base.
7989 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7990 // No fancy lookup required; just look for the base constructor name
7991 // directly within the derived class.
7992 ASTContext &Context = SemaRef.Context;
7993 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7994 Context.getCanonicalType(Context.getRecordType(Base)));
7995 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7996 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7997 }
7998
7999 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8000 // C++11 [class.inhctor]p3:
8001 // [F]or each constructor template in the candidate set of inherited
8002 // constructors, a constructor template is implicitly declared
8003 if (Ctor->getDescribedFunctionTemplate())
8004 return 0;
8005
8006 // For each non-template constructor in the candidate set of inherited
8007 // constructors other than a constructor having no parameters or a
8008 // copy/move constructor having a single parameter, a constructor is
8009 // implicitly declared [...]
8010 if (Ctor->getNumParams() == 0)
8011 return 1;
8012 if (Ctor->isCopyOrMoveConstructor())
8013 return 2;
8014
8015 // Per discussion on core reflector, never inherit a constructor which
8016 // would become a default, copy, or move constructor of Derived either.
8017 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8018 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8019 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8020 }
8021
8022 /// Declare a single inheriting constructor, inheriting the specified
8023 /// constructor, with the given type.
8024 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8025 QualType DerivedType) {
8026 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8027
8028 // C++11 [class.inhctor]p3:
8029 // ... a constructor is implicitly declared with the same constructor
8030 // characteristics unless there is a user-declared constructor with
8031 // the same signature in the class where the using-declaration appears
8032 if (Entry.DeclaredInDerived)
8033 return;
8034
8035 // C++11 [class.inhctor]p7:
8036 // If two using-declarations declare inheriting constructors with the
8037 // same signature, the program is ill-formed
8038 if (Entry.DerivedCtor) {
8039 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8040 // Only diagnose this once per constructor.
8041 if (Entry.DerivedCtor->isInvalidDecl())
8042 return;
8043 Entry.DerivedCtor->setInvalidDecl();
8044
8045 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8046 SemaRef.Diag(BaseCtor->getLocation(),
8047 diag::note_using_decl_constructor_conflict_current_ctor);
8048 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8049 diag::note_using_decl_constructor_conflict_previous_ctor);
8050 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8051 diag::note_using_decl_constructor_conflict_previous_using);
8052 } else {
8053 // Core issue (no number): if the same inheriting constructor is
8054 // produced by multiple base class constructors from the same base
8055 // class, the inheriting constructor is defined as deleted.
8056 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8057 }
8058
8059 return;
8060 }
8061
8062 ASTContext &Context = SemaRef.Context;
8063 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8064 Context.getCanonicalType(Context.getRecordType(Derived)));
8065 DeclarationNameInfo NameInfo(Name, UsingLoc);
8066
8067 TemplateParameterList *TemplateParams = 0;
8068 if (const FunctionTemplateDecl *FTD =
8069 BaseCtor->getDescribedFunctionTemplate()) {
8070 TemplateParams = FTD->getTemplateParameters();
8071 // We're reusing template parameters from a different DeclContext. This
8072 // is questionable at best, but works out because the template depth in
8073 // both places is guaranteed to be 0.
8074 // FIXME: Rebuild the template parameters in the new context, and
8075 // transform the function type to refer to them.
8076 }
8077
8078 // Build type source info pointing at the using-declaration. This is
8079 // required by template instantiation.
8080 TypeSourceInfo *TInfo =
8081 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8082 FunctionProtoTypeLoc ProtoLoc =
8083 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8084
8085 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8086 Context, Derived, UsingLoc, NameInfo, DerivedType,
8087 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8088 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8089
8090 // Build an unevaluated exception specification for this constructor.
8091 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8093 EPI.ExceptionSpecType = EST_Unevaluated;
8094 EPI.ExceptionSpecDecl = DerivedCtor;
8095 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8096 FPT->getArgTypes(), EPI));
8097
8098 // Build the parameter declarations.
8099 SmallVector<ParmVarDecl *, 16> ParamDecls;
8100 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8101 TypeSourceInfo *TInfo =
8102 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8103 ParmVarDecl *PD = ParmVarDecl::Create(
8104 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8105 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8106 PD->setScopeInfo(0, I);
8107 PD->setImplicit();
8108 ParamDecls.push_back(PD);
8109 ProtoLoc.setArg(I, PD);
8110 }
8111
8112 // Set up the new constructor.
8113 DerivedCtor->setAccess(BaseCtor->getAccess());
8114 DerivedCtor->setParams(ParamDecls);
8115 DerivedCtor->setInheritedConstructor(BaseCtor);
8116 if (BaseCtor->isDeleted())
8117 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8118
8119 // If this is a constructor template, build the template declaration.
8120 if (TemplateParams) {
8121 FunctionTemplateDecl *DerivedTemplate =
8122 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8123 TemplateParams, DerivedCtor);
8124 DerivedTemplate->setAccess(BaseCtor->getAccess());
8125 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8126 Derived->addDecl(DerivedTemplate);
8127 } else {
8128 Derived->addDecl(DerivedCtor);
8129 }
8130
8131 Entry.BaseCtor = BaseCtor;
8132 Entry.DerivedCtor = DerivedCtor;
8133 }
8134
8135 Sema &SemaRef;
8136 CXXRecordDecl *Derived;
8137 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8138 MapType Map;
8139};
8140}
8141
8142void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8143 // Defer declaring the inheriting constructors until the class is
8144 // instantiated.
8145 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008146 return;
8147
Richard Smith4841ca52013-04-10 05:48:59 +00008148 // Find base classes from which we might inherit constructors.
8149 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8150 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8151 BaseE = ClassDecl->bases_end();
8152 BaseIt != BaseE; ++BaseIt)
8153 if (BaseIt->getInheritConstructors())
8154 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008155
Richard Smith4841ca52013-04-10 05:48:59 +00008156 // Go no further if we're not inheriting any constructors.
8157 if (InheritedBases.empty())
8158 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008159
Richard Smith4841ca52013-04-10 05:48:59 +00008160 // Declare the inherited constructors.
8161 InheritingConstructorInfo ICI(*this, ClassDecl);
8162 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8163 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008164}
8165
Richard Smith07b0fdc2013-03-18 21:12:30 +00008166void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8167 CXXConstructorDecl *Constructor) {
8168 CXXRecordDecl *ClassDecl = Constructor->getParent();
8169 assert(Constructor->getInheritedConstructor() &&
8170 !Constructor->doesThisDeclarationHaveABody() &&
8171 !Constructor->isDeleted());
8172
8173 SynthesizedFunctionScope Scope(*this, Constructor);
8174 DiagnosticErrorTrap Trap(Diags);
8175 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8176 Trap.hasErrorOccurred()) {
8177 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8178 << Context.getTagDeclType(ClassDecl);
8179 Constructor->setInvalidDecl();
8180 return;
8181 }
8182
8183 SourceLocation Loc = Constructor->getLocation();
8184 Constructor->setBody(new (Context) CompoundStmt(Loc));
8185
8186 Constructor->setUsed();
8187 MarkVTableUsed(CurrentLocation, ClassDecl);
8188
8189 if (ASTMutationListener *L = getASTMutationListener()) {
8190 L->CompletedImplicitDefinition(Constructor);
8191 }
8192}
8193
8194
Sean Huntcb45a0f2011-05-12 22:46:25 +00008195Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008196Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8197 CXXRecordDecl *ClassDecl = MD->getParent();
8198
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008199 // C++ [except.spec]p14:
8200 // An implicitly declared special member function (Clause 12) shall have
8201 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008202 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008203 if (ClassDecl->isInvalidDecl())
8204 return ExceptSpec;
8205
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008206 // Direct base-class destructors.
8207 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8208 BEnd = ClassDecl->bases_end();
8209 B != BEnd; ++B) {
8210 if (B->isVirtual()) // Handled below.
8211 continue;
8212
8213 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008214 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008215 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008216 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008217
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008218 // Virtual base-class destructors.
8219 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8220 BEnd = ClassDecl->vbases_end();
8221 B != BEnd; ++B) {
8222 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008223 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008224 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008225 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008226
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008227 // Field destructors.
8228 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8229 FEnd = ClassDecl->field_end();
8230 F != FEnd; ++F) {
8231 if (const RecordType *RecordTy
8232 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008233 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008234 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008235 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008236
Sean Huntcb45a0f2011-05-12 22:46:25 +00008237 return ExceptSpec;
8238}
8239
8240CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8241 // C++ [class.dtor]p2:
8242 // If a class has no user-declared destructor, a destructor is
8243 // declared implicitly. An implicitly-declared destructor is an
8244 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008245 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008246
Richard Smithafb49182012-11-29 01:34:07 +00008247 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8248 if (DSM.isAlreadyBeingDeclared())
8249 return 0;
8250
Douglas Gregor4923aa22010-07-02 20:37:36 +00008251 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008252 CanQualType ClassType
8253 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008254 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008255 DeclarationName Name
8256 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008257 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008258 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008259 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8260 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008261 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008262 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008263 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008264 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008265
8266 // Build an exception specification pointing back at this destructor.
8267 FunctionProtoType::ExtProtoInfo EPI;
8268 EPI.ExceptionSpecType = EST_Unevaluated;
8269 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008270 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008271
Richard Smithbc2a35d2012-12-08 08:32:28 +00008272 AddOverriddenMethods(ClassDecl, Destructor);
8273
8274 // We don't need to use SpecialMemberIsTrivial here; triviality for
8275 // destructors is easy to compute.
8276 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8277
8278 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008279 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008280
Douglas Gregor4923aa22010-07-02 20:37:36 +00008281 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008282 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008283
Douglas Gregor4923aa22010-07-02 20:37:36 +00008284 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008285 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008286 PushOnScopeChains(Destructor, S, false);
8287 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008288
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008289 return Destructor;
8290}
8291
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008292void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008293 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008294 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008295 !Destructor->doesThisDeclarationHaveABody() &&
8296 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008297 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008298 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008299 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008300
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008301 if (Destructor->isInvalidDecl())
8302 return;
8303
Eli Friedman9a14db32012-10-18 20:14:08 +00008304 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008305
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008306 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008307 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8308 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008309
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008310 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008311 Diag(CurrentLocation, diag::note_member_synthesized_at)
8312 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8313
8314 Destructor->setInvalidDecl();
8315 return;
8316 }
8317
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008318 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008319 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00008320 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008321 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008322 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008323
8324 if (ASTMutationListener *L = getASTMutationListener()) {
8325 L->CompletedImplicitDefinition(Destructor);
8326 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008327}
8328
Richard Smitha4156b82012-04-21 18:42:51 +00008329/// \brief Perform any semantic analysis which needs to be delayed until all
8330/// pending class member declarations have been parsed.
8331void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008332 // If the context is an invalid C++ class, just suppress these checks.
8333 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8334 if (Record->isInvalidDecl()) {
8335 DelayedDestructorExceptionSpecChecks.clear();
8336 return;
8337 }
8338 }
8339
Richard Smitha4156b82012-04-21 18:42:51 +00008340 // Perform any deferred checking of exception specifications for virtual
8341 // destructors.
8342 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8343 i != e; ++i) {
8344 const CXXDestructorDecl *Dtor =
8345 DelayedDestructorExceptionSpecChecks[i].first;
8346 assert(!Dtor->getParent()->isDependentType() &&
8347 "Should not ever add destructors of templates into the list.");
8348 CheckOverridingFunctionExceptionSpec(Dtor,
8349 DelayedDestructorExceptionSpecChecks[i].second);
8350 }
8351 DelayedDestructorExceptionSpecChecks.clear();
8352}
8353
Richard Smithb9d0b762012-07-27 04:22:15 +00008354void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8355 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008356 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008357 "adjusting dtor exception specs was introduced in c++11");
8358
Sebastian Redl0ee33912011-05-19 05:13:44 +00008359 // C++11 [class.dtor]p3:
8360 // A declaration of a destructor that does not have an exception-
8361 // specification is implicitly considered to have the same exception-
8362 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008363 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008364 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008365 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008366 return;
8367
Chandler Carruth3f224b22011-09-20 04:55:26 +00008368 // Replace the destructor's type, building off the existing one. Fortunately,
8369 // the only thing of interest in the destructor type is its extended info.
8370 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008371 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8372 EPI.ExceptionSpecType = EST_Unevaluated;
8373 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008374 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008375
Sebastian Redl0ee33912011-05-19 05:13:44 +00008376 // FIXME: If the destructor has a body that could throw, and the newly created
8377 // spec doesn't allow exceptions, we should emit a warning, because this
8378 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008379 // However, we don't have a body or an exception specification yet, so it
8380 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008381}
8382
Richard Smith8c889532012-11-14 00:50:40 +00008383/// When generating a defaulted copy or move assignment operator, if a field
8384/// should be copied with __builtin_memcpy rather than via explicit assignments,
8385/// do so. This optimization only applies for arrays of scalars, and for arrays
8386/// of class type where the selected copy/move-assignment operator is trivial.
8387static StmtResult
8388buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8389 Expr *To, Expr *From) {
8390 // Compute the size of the memory buffer to be copied.
8391 QualType SizeType = S.Context.getSizeType();
8392 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8393 S.Context.getTypeSizeInChars(T).getQuantity());
8394
8395 // Take the address of the field references for "from" and "to". We
8396 // directly construct UnaryOperators here because semantic analysis
8397 // does not permit us to take the address of an xvalue.
8398 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8399 S.Context.getPointerType(From->getType()),
8400 VK_RValue, OK_Ordinary, Loc);
8401 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8402 S.Context.getPointerType(To->getType()),
8403 VK_RValue, OK_Ordinary, Loc);
8404
8405 const Type *E = T->getBaseElementTypeUnsafe();
8406 bool NeedsCollectableMemCpy =
8407 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8408
8409 // Create a reference to the __builtin_objc_memmove_collectable function
8410 StringRef MemCpyName = NeedsCollectableMemCpy ?
8411 "__builtin_objc_memmove_collectable" :
8412 "__builtin_memcpy";
8413 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8414 Sema::LookupOrdinaryName);
8415 S.LookupName(R, S.TUScope, true);
8416
8417 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8418 if (!MemCpy)
8419 // Something went horribly wrong earlier, and we will have complained
8420 // about it.
8421 return StmtError();
8422
8423 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8424 VK_RValue, Loc, 0);
8425 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8426
8427 Expr *CallArgs[] = {
8428 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8429 };
8430 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8431 Loc, CallArgs, Loc);
8432
8433 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8434 return S.Owned(Call.takeAs<Stmt>());
8435}
8436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008437/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008438/// \c To.
8439///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008440/// This routine is used to copy/move the members of a class with an
8441/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008442/// copied are arrays, this routine builds for loops to copy them.
8443///
8444/// \param S The Sema object used for type-checking.
8445///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008446/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008447///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008448/// \param T The type of the expressions being copied/moved. Both expressions
8449/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008450///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008451/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008452///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008455/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008456/// Otherwise, it's a non-static member subobject.
8457///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458/// \param Copying Whether we're copying or moving.
8459///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008460/// \param Depth Internal parameter recording the depth of the recursion.
8461///
Richard Smith8c889532012-11-14 00:50:40 +00008462/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8463/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008464static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008465buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8466 Expr *To, Expr *From,
8467 bool CopyingBaseSubobject, bool Copying,
8468 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008469 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008470 // Each subobject is assigned in the manner appropriate to its type:
8471 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008472 // - if the subobject is of class type, as if by a call to operator= with
8473 // the subobject as the object expression and the corresponding
8474 // subobject of x as a single function argument (as if by explicit
8475 // qualification; that is, ignoring any possible virtual overriding
8476 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008477 //
8478 // C++03 [class.copy]p13:
8479 // - if the subobject is of class type, the copy assignment operator for
8480 // the class is used (as if by explicit qualification; that is,
8481 // ignoring any possible virtual overriding functions in more derived
8482 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008483 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8484 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008485
Douglas Gregor06a9f362010-05-01 20:49:11 +00008486 // Look for operator=.
8487 DeclarationName Name
8488 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8489 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8490 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008491
Richard Smith044c8aa2012-11-13 00:54:12 +00008492 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8493 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008494 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008495 LookupResult::Filter F = OpLookup.makeFilter();
8496 while (F.hasNext()) {
8497 NamedDecl *D = F.next();
8498 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8499 if (Method->isCopyAssignmentOperator() ||
8500 (!Copying && Method->isMoveAssignmentOperator()))
8501 continue;
8502
8503 F.erase();
8504 }
8505 F.done();
John McCallb0207482010-03-16 06:11:48 +00008506 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008507
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008508 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008509 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008510 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008511 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008512 // ambiguities), we need to cast "this" to that subobject type; to
8513 // ensure that we don't go through the virtual call mechanism, we need
8514 // to qualify the operator= name with the base class (see below). However,
8515 // this means that if the base class has a protected copy assignment
8516 // operator, the protected member access check will fail. So, we
8517 // rewrite "protected" access to "public" access in this case, since we
8518 // know by construction that we're calling from a derived class.
8519 if (CopyingBaseSubobject) {
8520 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8521 L != LEnd; ++L) {
8522 if (L.getAccess() == AS_protected)
8523 L.setAccess(AS_public);
8524 }
8525 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008526
Douglas Gregor06a9f362010-05-01 20:49:11 +00008527 // Create the nested-name-specifier that will be used to qualify the
8528 // reference to operator=; this is required to suppress the virtual
8529 // call mechanism.
8530 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008531 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008532 SS.MakeTrivial(S.Context,
8533 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008534 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008535 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008536
Douglas Gregor06a9f362010-05-01 20:49:11 +00008537 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008538 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008539 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008540 /*TemplateKWLoc=*/SourceLocation(),
8541 /*FirstQualifierInScope=*/0,
8542 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543 /*TemplateArgs=*/0,
8544 /*SuppressQualifierCheck=*/true);
8545 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008546 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008547
Douglas Gregor06a9f362010-05-01 20:49:11 +00008548 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008549
Richard Smith044c8aa2012-11-13 00:54:12 +00008550 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008551 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008552 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008553 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008554 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008555
Richard Smith8c889532012-11-14 00:50:40 +00008556 // If we built a call to a trivial 'operator=' while copying an array,
8557 // bail out. We'll replace the whole shebang with a memcpy.
8558 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8559 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8560 return StmtResult((Stmt*)0);
8561
Richard Smith044c8aa2012-11-13 00:54:12 +00008562 // Convert to an expression-statement, and clean up any produced
8563 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008564 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008565 }
John McCallb0207482010-03-16 06:11:48 +00008566
Richard Smith044c8aa2012-11-13 00:54:12 +00008567 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008568 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008569 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008570 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008571 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008572 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008573 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008574 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008575 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008576
8577 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008578 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008579
Douglas Gregor06a9f362010-05-01 20:49:11 +00008580 // Construct a loop over the array bounds, e.g.,
8581 //
8582 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8583 //
8584 // that will copy each of the array elements.
8585 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008586
Douglas Gregor06a9f362010-05-01 20:49:11 +00008587 // Create the iteration variable.
8588 IdentifierInfo *IterationVarName = 0;
8589 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008590 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008591 llvm::raw_svector_ostream OS(Str);
8592 OS << "__i" << Depth;
8593 IterationVarName = &S.Context.Idents.get(OS.str());
8594 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008595 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008596 IterationVarName, SizeType,
8597 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008598 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008599
Douglas Gregor06a9f362010-05-01 20:49:11 +00008600 // Initialize the iteration variable to zero.
8601 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008602 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008603
8604 // Create a reference to the iteration variable; we'll use this several
8605 // times throughout.
8606 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008607 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008608 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008609 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8610 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8611
Douglas Gregor06a9f362010-05-01 20:49:11 +00008612 // Create the DeclStmt that holds the iteration variable.
8613 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008614
Douglas Gregor06a9f362010-05-01 20:49:11 +00008615 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008616 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008617 IterationVarRefRVal,
8618 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008619 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008620 IterationVarRefRVal,
8621 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008622 if (!Copying) // Cast to rvalue
8623 From = CastForMoving(S, From);
8624
8625 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008626 StmtResult Copy =
8627 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8628 To, From, CopyingBaseSubobject,
8629 Copying, Depth + 1);
8630 // Bail out if copying fails or if we determined that we should use memcpy.
8631 if (Copy.isInvalid() || !Copy.get())
8632 return Copy;
8633
8634 // Create the comparison against the array bound.
8635 llvm::APInt Upper
8636 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8637 Expr *Comparison
8638 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8639 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8640 BO_NE, S.Context.BoolTy,
8641 VK_RValue, OK_Ordinary, Loc, false);
8642
8643 // Create the pre-increment of the iteration variable.
8644 Expr *Increment
8645 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8646 VK_LValue, OK_Ordinary, Loc);
8647
Douglas Gregor06a9f362010-05-01 20:49:11 +00008648 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008649 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008650 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008651 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008652 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008653}
8654
Richard Smith8c889532012-11-14 00:50:40 +00008655static StmtResult
8656buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8657 Expr *To, Expr *From,
8658 bool CopyingBaseSubobject, bool Copying) {
8659 // Maybe we should use a memcpy?
8660 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8661 T.isTriviallyCopyableType(S.Context))
8662 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8663
8664 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8665 CopyingBaseSubobject,
8666 Copying, 0));
8667
8668 // If we ended up picking a trivial assignment operator for an array of a
8669 // non-trivially-copyable class type, just emit a memcpy.
8670 if (!Result.isInvalid() && !Result.get())
8671 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8672
8673 return Result;
8674}
8675
Richard Smithb9d0b762012-07-27 04:22:15 +00008676Sema::ImplicitExceptionSpecification
8677Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8678 CXXRecordDecl *ClassDecl = MD->getParent();
8679
8680 ImplicitExceptionSpecification ExceptSpec(*this);
8681 if (ClassDecl->isInvalidDecl())
8682 return ExceptSpec;
8683
8684 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8685 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8686 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8687
Douglas Gregorb87786f2010-07-01 17:48:08 +00008688 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008689 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008690 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008691
8692 // It is unspecified whether or not an implicit copy assignment operator
8693 // attempts to deduplicate calls to assignment operators of virtual bases are
8694 // made. As such, this exception specification is effectively unspecified.
8695 // Based on a similar decision made for constness in C++0x, we're erring on
8696 // the side of assuming such calls to be made regardless of whether they
8697 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8699 BaseEnd = ClassDecl->bases_end();
8700 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008701 if (Base->isVirtual())
8702 continue;
8703
Douglas Gregora376d102010-07-02 21:50:04 +00008704 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008705 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008706 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8707 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008708 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008709 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008710
8711 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8712 BaseEnd = ClassDecl->vbases_end();
8713 Base != BaseEnd; ++Base) {
8714 CXXRecordDecl *BaseClassDecl
8715 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8716 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8717 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008718 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008719 }
8720
Douglas Gregorb87786f2010-07-01 17:48:08 +00008721 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8722 FieldEnd = ClassDecl->field_end();
8723 Field != FieldEnd;
8724 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008725 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008726 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8727 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008728 LookupCopyingAssignment(FieldClassDecl,
8729 ArgQuals | FieldType.getCVRQualifiers(),
8730 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008731 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008732 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008733 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008734
Richard Smithb9d0b762012-07-27 04:22:15 +00008735 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008736}
8737
8738CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8739 // Note: The following rules are largely analoguous to the copy
8740 // constructor rules. Note that virtual bases are not taken into account
8741 // for determining the argument type of the operator. Note also that
8742 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008743 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008744
Richard Smithafb49182012-11-29 01:34:07 +00008745 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8746 if (DSM.isAlreadyBeingDeclared())
8747 return 0;
8748
Sean Hunt30de05c2011-05-14 05:23:20 +00008749 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8750 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008751 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8752 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008753 ArgType = ArgType.withConst();
8754 ArgType = Context.getLValueReferenceType(ArgType);
8755
Richard Smitha8942d72013-05-07 03:19:20 +00008756 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8757 CXXCopyAssignment,
8758 Const);
8759
Douglas Gregord3c35902010-07-01 16:36:15 +00008760 // An implicitly-declared copy assignment operator is an inline public
8761 // member of its class.
8762 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008763 SourceLocation ClassLoc = ClassDecl->getLocation();
8764 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008765 CXXMethodDecl *CopyAssignment =
8766 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8767 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8768 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008769 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008770 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008771 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008772
8773 // Build an exception specification pointing back at this member.
8774 FunctionProtoType::ExtProtoInfo EPI;
8775 EPI.ExceptionSpecType = EST_Unevaluated;
8776 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008777 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008778
Douglas Gregord3c35902010-07-01 16:36:15 +00008779 // Add the parameter to the operator.
8780 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008781 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008782 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008783 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008784 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008785
Richard Smithbc2a35d2012-12-08 08:32:28 +00008786 AddOverriddenMethods(ClassDecl, CopyAssignment);
8787
8788 CopyAssignment->setTrivial(
8789 ClassDecl->needsOverloadResolutionForCopyAssignment()
8790 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8791 : ClassDecl->hasTrivialCopyAssignment());
8792
Richard Smitha8942d72013-05-07 03:19:20 +00008793 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008794 // .... If the class definition does not explicitly declare a copy
8795 // assignment operator, there is no user-declared move constructor, and
8796 // there is no user-declared move assignment operator, a copy assignment
8797 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008798 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008799 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008800
Richard Smithbc2a35d2012-12-08 08:32:28 +00008801 // Note that we have added this copy-assignment operator.
8802 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8803
8804 if (Scope *S = getScopeForContext(ClassDecl))
8805 PushOnScopeChains(CopyAssignment, S, false);
8806 ClassDecl->addDecl(CopyAssignment);
8807
Douglas Gregord3c35902010-07-01 16:36:15 +00008808 return CopyAssignment;
8809}
8810
Richard Smith36155c12013-06-13 03:23:42 +00008811/// Diagnose an implicit copy operation for a class which is odr-used, but
8812/// which is deprecated because the class has a user-declared copy constructor,
8813/// copy assignment operator, or destructor.
8814static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8815 SourceLocation UseLoc) {
8816 assert(CopyOp->isImplicit());
8817
8818 CXXRecordDecl *RD = CopyOp->getParent();
8819 CXXMethodDecl *UserDeclaredOperation = 0;
8820
8821 // In Microsoft mode, assignment operations don't affect constructors and
8822 // vice versa.
8823 if (RD->hasUserDeclaredDestructor()) {
8824 UserDeclaredOperation = RD->getDestructor();
8825 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8826 RD->hasUserDeclaredCopyConstructor() &&
8827 !S.getLangOpts().MicrosoftMode) {
8828 // Find any user-declared copy constructor.
8829 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8830 E = RD->ctor_end(); I != E; ++I) {
8831 if (I->isCopyConstructor()) {
8832 UserDeclaredOperation = *I;
8833 break;
8834 }
8835 }
8836 assert(UserDeclaredOperation);
8837 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8838 RD->hasUserDeclaredCopyAssignment() &&
8839 !S.getLangOpts().MicrosoftMode) {
8840 // Find any user-declared move assignment operator.
8841 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8842 E = RD->method_end(); I != E; ++I) {
8843 if (I->isCopyAssignmentOperator()) {
8844 UserDeclaredOperation = *I;
8845 break;
8846 }
8847 }
8848 assert(UserDeclaredOperation);
8849 }
8850
8851 if (UserDeclaredOperation) {
8852 S.Diag(UserDeclaredOperation->getLocation(),
8853 diag::warn_deprecated_copy_operation)
8854 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8855 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8856 S.Diag(UseLoc, diag::note_member_synthesized_at)
8857 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8858 : Sema::CXXCopyAssignment)
8859 << RD;
8860 }
8861}
8862
Douglas Gregor06a9f362010-05-01 20:49:11 +00008863void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8864 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008865 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008866 CopyAssignOperator->isOverloadedOperator() &&
8867 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008868 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8869 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008870 "DefineImplicitCopyAssignment called for wrong function");
8871
8872 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8873
8874 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8875 CopyAssignOperator->setInvalidDecl();
8876 return;
8877 }
Richard Smith36155c12013-06-13 03:23:42 +00008878
8879 // C++11 [class.copy]p18:
8880 // The [definition of an implicitly declared copy assignment operator] is
8881 // deprecated if the class has a user-declared copy constructor or a
8882 // user-declared destructor.
8883 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8884 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8885
Douglas Gregor06a9f362010-05-01 20:49:11 +00008886 CopyAssignOperator->setUsed();
8887
Eli Friedman9a14db32012-10-18 20:14:08 +00008888 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008889 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008890
8891 // C++0x [class.copy]p30:
8892 // The implicitly-defined or explicitly-defaulted copy assignment operator
8893 // for a non-union class X performs memberwise copy assignment of its
8894 // subobjects. The direct base classes of X are assigned first, in the
8895 // order of their declaration in the base-specifier-list, and then the
8896 // immediate non-static data members of X are assigned, in the order in
8897 // which they were declared in the class definition.
8898
8899 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008900 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008901
8902 // The parameter for the "other" object, which we are copying from.
8903 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8904 Qualifiers OtherQuals = Other->getType().getQualifiers();
8905 QualType OtherRefType = Other->getType();
8906 if (const LValueReferenceType *OtherRef
8907 = OtherRefType->getAs<LValueReferenceType>()) {
8908 OtherRefType = OtherRef->getPointeeType();
8909 OtherQuals = OtherRefType.getQualifiers();
8910 }
8911
8912 // Our location for everything implicitly-generated.
8913 SourceLocation Loc = CopyAssignOperator->getLocation();
8914
8915 // Construct a reference to the "other" object. We'll be using this
8916 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008917 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008918 assert(OtherRef && "Reference to parameter cannot fail!");
8919
8920 // Construct the "this" pointer. We'll be using this throughout the generated
8921 // ASTs.
8922 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8923 assert(This && "Reference to this cannot fail!");
8924
8925 // Assign base classes.
8926 bool Invalid = false;
8927 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8928 E = ClassDecl->bases_end(); Base != E; ++Base) {
8929 // Form the assignment:
8930 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8931 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008932 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008933 Invalid = true;
8934 continue;
8935 }
8936
John McCallf871d0c2010-08-07 06:22:56 +00008937 CXXCastPath BasePath;
8938 BasePath.push_back(Base);
8939
Douglas Gregor06a9f362010-05-01 20:49:11 +00008940 // Construct the "from" expression, which is an implicit cast to the
8941 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008942 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008943 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8944 CK_UncheckedDerivedToBase,
8945 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008946
8947 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008948 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008949
8950 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008951 To = ImpCastExprToType(To.take(),
8952 Context.getCVRQualifiedType(BaseType,
8953 CopyAssignOperator->getTypeQualifiers()),
8954 CK_UncheckedDerivedToBase,
8955 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008956
8957 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008958 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008959 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008960 /*CopyingBaseSubobject=*/true,
8961 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008962 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008963 Diag(CurrentLocation, diag::note_member_synthesized_at)
8964 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8965 CopyAssignOperator->setInvalidDecl();
8966 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008967 }
8968
8969 // Success! Record the copy.
8970 Statements.push_back(Copy.takeAs<Expr>());
8971 }
8972
Douglas Gregor06a9f362010-05-01 20:49:11 +00008973 // Assign non-static members.
8974 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8975 FieldEnd = ClassDecl->field_end();
8976 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008977 if (Field->isUnnamedBitfield())
8978 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00008979
8980 if (Field->isInvalidDecl()) {
8981 Invalid = true;
8982 continue;
8983 }
8984
Douglas Gregor06a9f362010-05-01 20:49:11 +00008985 // Check for members of reference type; we can't copy those.
8986 if (Field->getType()->isReferenceType()) {
8987 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8988 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8989 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008990 Diag(CurrentLocation, diag::note_member_synthesized_at)
8991 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 Invalid = true;
8993 continue;
8994 }
8995
8996 // Check for members of const-qualified, non-class type.
8997 QualType BaseType = Context.getBaseElementType(Field->getType());
8998 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8999 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9000 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9001 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009002 Diag(CurrentLocation, diag::note_member_synthesized_at)
9003 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009004 Invalid = true;
9005 continue;
9006 }
John McCallb77115d2011-06-17 00:18:42 +00009007
9008 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009009 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9010 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009011
9012 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009013 if (FieldType->isIncompleteArrayType()) {
9014 assert(ClassDecl->hasFlexibleArrayMember() &&
9015 "Incomplete array type is not valid");
9016 continue;
9017 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009018
9019 // Build references to the field in the object we're copying from and to.
9020 CXXScopeSpec SS; // Intentionally empty
9021 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9022 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009023 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009024 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009025 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009026 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009027 SS, SourceLocation(), 0,
9028 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009029 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009030 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009031 SS, SourceLocation(), 0,
9032 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009033 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9034 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009035
Douglas Gregor06a9f362010-05-01 20:49:11 +00009036 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009037 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009038 To.get(), From.get(),
9039 /*CopyingBaseSubobject=*/false,
9040 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009041 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009042 Diag(CurrentLocation, diag::note_member_synthesized_at)
9043 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9044 CopyAssignOperator->setInvalidDecl();
9045 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009046 }
9047
9048 // Success! Record the copy.
9049 Statements.push_back(Copy.takeAs<Stmt>());
9050 }
9051
9052 if (!Invalid) {
9053 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009054 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009055
John McCall60d7b3a2010-08-24 06:29:42 +00009056 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009057 if (Return.isInvalid())
9058 Invalid = true;
9059 else {
9060 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009061
9062 if (Trap.hasErrorOccurred()) {
9063 Diag(CurrentLocation, diag::note_member_synthesized_at)
9064 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9065 Invalid = true;
9066 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009067 }
9068 }
9069
9070 if (Invalid) {
9071 CopyAssignOperator->setInvalidDecl();
9072 return;
9073 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009074
9075 StmtResult Body;
9076 {
9077 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009078 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009079 /*isStmtExpr=*/false);
9080 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9081 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009082 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009083
9084 if (ASTMutationListener *L = getASTMutationListener()) {
9085 L->CompletedImplicitDefinition(CopyAssignOperator);
9086 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009087}
9088
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009089Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009090Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9091 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009092
Richard Smithb9d0b762012-07-27 04:22:15 +00009093 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009094 if (ClassDecl->isInvalidDecl())
9095 return ExceptSpec;
9096
9097 // C++0x [except.spec]p14:
9098 // An implicitly declared special member function (Clause 12) shall have an
9099 // exception-specification. [...]
9100
9101 // It is unspecified whether or not an implicit move assignment operator
9102 // attempts to deduplicate calls to assignment operators of virtual bases are
9103 // made. As such, this exception specification is effectively unspecified.
9104 // Based on a similar decision made for constness in C++0x, we're erring on
9105 // the side of assuming such calls to be made regardless of whether they
9106 // actually happen.
9107 // Note that a move constructor is not implicitly declared when there are
9108 // virtual bases, but it can still be user-declared and explicitly defaulted.
9109 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9110 BaseEnd = ClassDecl->bases_end();
9111 Base != BaseEnd; ++Base) {
9112 if (Base->isVirtual())
9113 continue;
9114
9115 CXXRecordDecl *BaseClassDecl
9116 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9117 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009118 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009119 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009120 }
9121
9122 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9123 BaseEnd = ClassDecl->vbases_end();
9124 Base != BaseEnd; ++Base) {
9125 CXXRecordDecl *BaseClassDecl
9126 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9127 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009128 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009129 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009130 }
9131
9132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9133 FieldEnd = ClassDecl->field_end();
9134 Field != FieldEnd;
9135 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009136 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009137 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009138 if (CXXMethodDecl *MoveAssign =
9139 LookupMovingAssignment(FieldClassDecl,
9140 FieldType.getCVRQualifiers(),
9141 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009142 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009143 }
9144 }
9145
9146 return ExceptSpec;
9147}
9148
Richard Smith1c931be2012-04-02 18:40:40 +00009149/// Determine whether the class type has any direct or indirect virtual base
9150/// classes which have a non-trivial move assignment operator.
9151static bool
9152hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9153 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9154 BaseEnd = ClassDecl->vbases_end();
9155 Base != BaseEnd; ++Base) {
9156 CXXRecordDecl *BaseClass =
9157 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9158
9159 // Try to declare the move assignment. If it would be deleted, then the
9160 // class does not have a non-trivial move assignment.
9161 if (BaseClass->needsImplicitMoveAssignment())
9162 S.DeclareImplicitMoveAssignment(BaseClass);
9163
Richard Smith426391c2012-11-16 00:53:38 +00009164 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009165 return true;
9166 }
9167
9168 return false;
9169}
9170
9171/// Determine whether the given type either has a move constructor or is
9172/// trivially copyable.
9173static bool
9174hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9175 Type = S.Context.getBaseElementType(Type);
9176
9177 // FIXME: Technically, non-trivially-copyable non-class types, such as
9178 // reference types, are supposed to return false here, but that appears
9179 // to be a standard defect.
9180 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009181 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009182 return true;
9183
9184 if (Type.isTriviallyCopyableType(S.Context))
9185 return true;
9186
9187 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009188 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9189 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009190 if (ClassDecl->needsImplicitMoveConstructor())
9191 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009192 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009193 }
9194
Richard Smithe5411b72012-12-01 02:35:44 +00009195 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9196 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009197 if (ClassDecl->needsImplicitMoveAssignment())
9198 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009199 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009200}
9201
9202/// Determine whether all non-static data members and direct or virtual bases
9203/// of class \p ClassDecl have either a move operation, or are trivially
9204/// copyable.
9205static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9206 bool IsConstructor) {
9207 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9208 BaseEnd = ClassDecl->bases_end();
9209 Base != BaseEnd; ++Base) {
9210 if (Base->isVirtual())
9211 continue;
9212
9213 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9214 return false;
9215 }
9216
9217 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9218 BaseEnd = ClassDecl->vbases_end();
9219 Base != BaseEnd; ++Base) {
9220 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9221 return false;
9222 }
9223
9224 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9225 FieldEnd = ClassDecl->field_end();
9226 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009227 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009228 return false;
9229 }
9230
9231 return true;
9232}
9233
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009234CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009235 // C++11 [class.copy]p20:
9236 // If the definition of a class X does not explicitly declare a move
9237 // assignment operator, one will be implicitly declared as defaulted
9238 // if and only if:
9239 //
9240 // - [first 4 bullets]
9241 assert(ClassDecl->needsImplicitMoveAssignment());
9242
Richard Smithafb49182012-11-29 01:34:07 +00009243 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9244 if (DSM.isAlreadyBeingDeclared())
9245 return 0;
9246
Richard Smith1c931be2012-04-02 18:40:40 +00009247 // [Checked after we build the declaration]
9248 // - the move assignment operator would not be implicitly defined as
9249 // deleted,
9250
9251 // [DR1402]:
9252 // - X has no direct or indirect virtual base class with a non-trivial
9253 // move assignment operator, and
9254 // - each of X's non-static data members and direct or virtual base classes
9255 // has a type that either has a move assignment operator or is trivially
9256 // copyable.
9257 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9258 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9259 ClassDecl->setFailedImplicitMoveAssignment();
9260 return 0;
9261 }
9262
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009263 // Note: The following rules are largely analoguous to the move
9264 // constructor rules.
9265
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009266 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9267 QualType RetType = Context.getLValueReferenceType(ArgType);
9268 ArgType = Context.getRValueReferenceType(ArgType);
9269
Richard Smitha8942d72013-05-07 03:19:20 +00009270 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9271 CXXMoveAssignment,
9272 false);
9273
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009274 // An implicitly-declared move assignment operator is an inline public
9275 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009276 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9277 SourceLocation ClassLoc = ClassDecl->getLocation();
9278 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009279 CXXMethodDecl *MoveAssignment =
9280 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9281 /*TInfo=*/0, /*StorageClass=*/SC_None,
9282 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009283 MoveAssignment->setAccess(AS_public);
9284 MoveAssignment->setDefaulted();
9285 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009286
Richard Smithb9d0b762012-07-27 04:22:15 +00009287 // Build an exception specification pointing back at this member.
9288 FunctionProtoType::ExtProtoInfo EPI;
9289 EPI.ExceptionSpecType = EST_Unevaluated;
9290 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009291 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009293 // Add the parameter to the operator.
9294 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9295 ClassLoc, ClassLoc, /*Id=*/0,
9296 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009297 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009298 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009299
Richard Smithbc2a35d2012-12-08 08:32:28 +00009300 AddOverriddenMethods(ClassDecl, MoveAssignment);
9301
9302 MoveAssignment->setTrivial(
9303 ClassDecl->needsOverloadResolutionForMoveAssignment()
9304 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9305 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009306
9307 // C++0x [class.copy]p9:
9308 // If the definition of a class X does not explicitly declare a move
9309 // assignment operator, one will be implicitly declared as defaulted if and
9310 // only if:
9311 // [...]
9312 // - the move assignment operator would not be implicitly defined as
9313 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009314 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009315 // Cache this result so that we don't try to generate this over and over
9316 // on every lookup, leaking memory and wasting time.
9317 ClassDecl->setFailedImplicitMoveAssignment();
9318 return 0;
9319 }
9320
Richard Smithbc2a35d2012-12-08 08:32:28 +00009321 // Note that we have added this copy-assignment operator.
9322 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9323
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009324 if (Scope *S = getScopeForContext(ClassDecl))
9325 PushOnScopeChains(MoveAssignment, S, false);
9326 ClassDecl->addDecl(MoveAssignment);
9327
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009328 return MoveAssignment;
9329}
9330
9331void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9332 CXXMethodDecl *MoveAssignOperator) {
9333 assert((MoveAssignOperator->isDefaulted() &&
9334 MoveAssignOperator->isOverloadedOperator() &&
9335 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009336 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9337 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009338 "DefineImplicitMoveAssignment called for wrong function");
9339
9340 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9341
9342 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9343 MoveAssignOperator->setInvalidDecl();
9344 return;
9345 }
9346
9347 MoveAssignOperator->setUsed();
9348
Eli Friedman9a14db32012-10-18 20:14:08 +00009349 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009350 DiagnosticErrorTrap Trap(Diags);
9351
9352 // C++0x [class.copy]p28:
9353 // The implicitly-defined or move assignment operator for a non-union class
9354 // X performs memberwise move assignment of its subobjects. The direct base
9355 // classes of X are assigned first, in the order of their declaration in the
9356 // base-specifier-list, and then the immediate non-static data members of X
9357 // are assigned, in the order in which they were declared in the class
9358 // definition.
9359
9360 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009361 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009362
9363 // The parameter for the "other" object, which we are move from.
9364 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9365 QualType OtherRefType = Other->getType()->
9366 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009367 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009368 "Bad argument type of defaulted move assignment");
9369
9370 // Our location for everything implicitly-generated.
9371 SourceLocation Loc = MoveAssignOperator->getLocation();
9372
9373 // Construct a reference to the "other" object. We'll be using this
9374 // throughout the generated ASTs.
9375 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9376 assert(OtherRef && "Reference to parameter cannot fail!");
9377 // Cast to rvalue.
9378 OtherRef = CastForMoving(*this, OtherRef);
9379
9380 // Construct the "this" pointer. We'll be using this throughout the generated
9381 // ASTs.
9382 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9383 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009384
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009385 // Assign base classes.
9386 bool Invalid = false;
9387 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9388 E = ClassDecl->bases_end(); Base != E; ++Base) {
9389 // Form the assignment:
9390 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9391 QualType BaseType = Base->getType().getUnqualifiedType();
9392 if (!BaseType->isRecordType()) {
9393 Invalid = true;
9394 continue;
9395 }
9396
9397 CXXCastPath BasePath;
9398 BasePath.push_back(Base);
9399
9400 // Construct the "from" expression, which is an implicit cast to the
9401 // appropriately-qualified base type.
9402 Expr *From = OtherRef;
9403 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009404 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009405
9406 // Dereference "this".
9407 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9408
9409 // Implicitly cast "this" to the appropriately-qualified base type.
9410 To = ImpCastExprToType(To.take(),
9411 Context.getCVRQualifiedType(BaseType,
9412 MoveAssignOperator->getTypeQualifiers()),
9413 CK_UncheckedDerivedToBase,
9414 VK_LValue, &BasePath);
9415
9416 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009417 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009418 To.get(), From,
9419 /*CopyingBaseSubobject=*/true,
9420 /*Copying=*/false);
9421 if (Move.isInvalid()) {
9422 Diag(CurrentLocation, diag::note_member_synthesized_at)
9423 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9424 MoveAssignOperator->setInvalidDecl();
9425 return;
9426 }
9427
9428 // Success! Record the move.
9429 Statements.push_back(Move.takeAs<Expr>());
9430 }
9431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009432 // Assign non-static members.
9433 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9434 FieldEnd = ClassDecl->field_end();
9435 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009436 if (Field->isUnnamedBitfield())
9437 continue;
9438
Eli Friedman8150da32013-06-07 01:48:56 +00009439 if (Field->isInvalidDecl()) {
9440 Invalid = true;
9441 continue;
9442 }
9443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009444 // Check for members of reference type; we can't move those.
9445 if (Field->getType()->isReferenceType()) {
9446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9447 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9448 Diag(Field->getLocation(), diag::note_declared_at);
9449 Diag(CurrentLocation, diag::note_member_synthesized_at)
9450 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9451 Invalid = true;
9452 continue;
9453 }
9454
9455 // Check for members of const-qualified, non-class type.
9456 QualType BaseType = Context.getBaseElementType(Field->getType());
9457 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9458 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9459 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9460 Diag(Field->getLocation(), diag::note_declared_at);
9461 Diag(CurrentLocation, diag::note_member_synthesized_at)
9462 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9463 Invalid = true;
9464 continue;
9465 }
9466
9467 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009468 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9469 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009470
9471 QualType FieldType = Field->getType().getNonReferenceType();
9472 if (FieldType->isIncompleteArrayType()) {
9473 assert(ClassDecl->hasFlexibleArrayMember() &&
9474 "Incomplete array type is not valid");
9475 continue;
9476 }
9477
9478 // Build references to the field in the object we're copying from and to.
9479 CXXScopeSpec SS; // Intentionally empty
9480 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9481 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009482 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009483 MemberLookup.resolveKind();
9484 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9485 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009486 SS, SourceLocation(), 0,
9487 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009488 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9489 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009490 SS, SourceLocation(), 0,
9491 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009492 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9493 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9494
9495 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9496 "Member reference with rvalue base must be rvalue except for reference "
9497 "members, which aren't allowed for move assignment.");
9498
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009499 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009500 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009501 To.get(), From.get(),
9502 /*CopyingBaseSubobject=*/false,
9503 /*Copying=*/false);
9504 if (Move.isInvalid()) {
9505 Diag(CurrentLocation, diag::note_member_synthesized_at)
9506 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9507 MoveAssignOperator->setInvalidDecl();
9508 return;
9509 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009510
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009511 // Success! Record the copy.
9512 Statements.push_back(Move.takeAs<Stmt>());
9513 }
9514
9515 if (!Invalid) {
9516 // Add a "return *this;"
9517 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9518
9519 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9520 if (Return.isInvalid())
9521 Invalid = true;
9522 else {
9523 Statements.push_back(Return.takeAs<Stmt>());
9524
9525 if (Trap.hasErrorOccurred()) {
9526 Diag(CurrentLocation, diag::note_member_synthesized_at)
9527 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9528 Invalid = true;
9529 }
9530 }
9531 }
9532
9533 if (Invalid) {
9534 MoveAssignOperator->setInvalidDecl();
9535 return;
9536 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009537
9538 StmtResult Body;
9539 {
9540 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009541 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009542 /*isStmtExpr=*/false);
9543 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9544 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009545 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9546
9547 if (ASTMutationListener *L = getASTMutationListener()) {
9548 L->CompletedImplicitDefinition(MoveAssignOperator);
9549 }
9550}
9551
Richard Smithb9d0b762012-07-27 04:22:15 +00009552Sema::ImplicitExceptionSpecification
9553Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9554 CXXRecordDecl *ClassDecl = MD->getParent();
9555
9556 ImplicitExceptionSpecification ExceptSpec(*this);
9557 if (ClassDecl->isInvalidDecl())
9558 return ExceptSpec;
9559
9560 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9561 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9562 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9563
Douglas Gregor0d405db2010-07-01 20:59:04 +00009564 // C++ [except.spec]p14:
9565 // An implicitly declared special member function (Clause 12) shall have an
9566 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009567 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9568 BaseEnd = ClassDecl->bases_end();
9569 Base != BaseEnd;
9570 ++Base) {
9571 // Virtual bases are handled below.
9572 if (Base->isVirtual())
9573 continue;
9574
Douglas Gregor22584312010-07-02 23:41:54 +00009575 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009577 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009578 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009579 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009580 }
9581 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9582 BaseEnd = ClassDecl->vbases_end();
9583 Base != BaseEnd;
9584 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009585 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009586 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009587 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009588 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009589 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009590 }
9591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9592 FieldEnd = ClassDecl->field_end();
9593 Field != FieldEnd;
9594 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009595 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009596 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9597 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009598 LookupCopyingConstructor(FieldClassDecl,
9599 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009600 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009601 }
9602 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009603
Richard Smithb9d0b762012-07-27 04:22:15 +00009604 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009605}
9606
9607CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9608 CXXRecordDecl *ClassDecl) {
9609 // C++ [class.copy]p4:
9610 // If the class definition does not explicitly declare a copy
9611 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009612 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009613
Richard Smithafb49182012-11-29 01:34:07 +00009614 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9615 if (DSM.isAlreadyBeingDeclared())
9616 return 0;
9617
Sean Hunt49634cf2011-05-13 06:10:58 +00009618 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9619 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009620 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009621 if (Const)
9622 ArgType = ArgType.withConst();
9623 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009624
Richard Smith7756afa2012-06-10 05:43:50 +00009625 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9626 CXXCopyConstructor,
9627 Const);
9628
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009629 DeclarationName Name
9630 = Context.DeclarationNames.getCXXConstructorName(
9631 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009632 SourceLocation ClassLoc = ClassDecl->getLocation();
9633 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009634
9635 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009636 // member of its class.
9637 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009638 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009639 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009640 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009641 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009642 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009643
Richard Smithb9d0b762012-07-27 04:22:15 +00009644 // Build an exception specification pointing back at this member.
9645 FunctionProtoType::ExtProtoInfo EPI;
9646 EPI.ExceptionSpecType = EST_Unevaluated;
9647 EPI.ExceptionSpecDecl = CopyConstructor;
9648 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009649 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009650
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009651 // Add the parameter to the constructor.
9652 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009653 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009654 /*IdentifierInfo=*/0,
9655 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009656 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009657 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009658
Richard Smithbc2a35d2012-12-08 08:32:28 +00009659 CopyConstructor->setTrivial(
9660 ClassDecl->needsOverloadResolutionForCopyConstructor()
9661 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9662 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009663
Nico Weberafcc96a2012-01-23 03:19:29 +00009664 // C++11 [class.copy]p8:
9665 // ... If the class definition does not explicitly declare a copy
9666 // constructor, there is no user-declared move constructor, and there is no
9667 // user-declared move assignment operator, a copy constructor is implicitly
9668 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009669 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009670 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009671
Richard Smithbc2a35d2012-12-08 08:32:28 +00009672 // Note that we have declared this constructor.
9673 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9674
9675 if (Scope *S = getScopeForContext(ClassDecl))
9676 PushOnScopeChains(CopyConstructor, S, false);
9677 ClassDecl->addDecl(CopyConstructor);
9678
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009679 return CopyConstructor;
9680}
9681
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009682void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009683 CXXConstructorDecl *CopyConstructor) {
9684 assert((CopyConstructor->isDefaulted() &&
9685 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009686 !CopyConstructor->doesThisDeclarationHaveABody() &&
9687 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009688 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009689
Anders Carlsson63010a72010-04-23 16:24:12 +00009690 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009691 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009692
Richard Smith36155c12013-06-13 03:23:42 +00009693 // C++11 [class.copy]p7:
9694 // The [definition of an implicitly declared copy constructro] is
9695 // deprecated if the class has a user-declared copy assignment operator
9696 // or a user-declared destructor.
9697 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9698 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9699
Eli Friedman9a14db32012-10-18 20:14:08 +00009700 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009701 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009702
David Blaikie93c86172013-01-17 05:26:25 +00009703 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009704 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009705 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009706 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009707 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009708 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009709 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009710 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9711 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009712 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009713 /*isStmtExpr=*/false)
9714 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009715 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009716 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009717
9718 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009719 if (ASTMutationListener *L = getASTMutationListener()) {
9720 L->CompletedImplicitDefinition(CopyConstructor);
9721 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009722}
9723
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009724Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009725Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9726 CXXRecordDecl *ClassDecl = MD->getParent();
9727
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009728 // C++ [except.spec]p14:
9729 // An implicitly declared special member function (Clause 12) shall have an
9730 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009731 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009732 if (ClassDecl->isInvalidDecl())
9733 return ExceptSpec;
9734
9735 // Direct base-class constructors.
9736 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9737 BEnd = ClassDecl->bases_end();
9738 B != BEnd; ++B) {
9739 if (B->isVirtual()) // Handled below.
9740 continue;
9741
9742 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9743 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009744 CXXConstructorDecl *Constructor =
9745 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009746 // If this is a deleted function, add it anyway. This might be conformant
9747 // with the standard. This might not. I'm not sure. It might not matter.
9748 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009749 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009750 }
9751 }
9752
9753 // Virtual base-class constructors.
9754 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9755 BEnd = ClassDecl->vbases_end();
9756 B != BEnd; ++B) {
9757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009759 CXXConstructorDecl *Constructor =
9760 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009761 // If this is a deleted function, add it anyway. This might be conformant
9762 // with the standard. This might not. I'm not sure. It might not matter.
9763 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009764 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765 }
9766 }
9767
9768 // Field constructors.
9769 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9770 FEnd = ClassDecl->field_end();
9771 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009772 QualType FieldType = Context.getBaseElementType(F->getType());
9773 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9774 CXXConstructorDecl *Constructor =
9775 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009776 // If this is a deleted function, add it anyway. This might be conformant
9777 // with the standard. This might not. I'm not sure. It might not matter.
9778 // In particular, the problem is that this function never gets called. It
9779 // might just be ill-formed because this function attempts to refer to
9780 // a deleted function here.
9781 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009782 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783 }
9784 }
9785
9786 return ExceptSpec;
9787}
9788
9789CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9790 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009791 // C++11 [class.copy]p9:
9792 // If the definition of a class X does not explicitly declare a move
9793 // constructor, one will be implicitly declared as defaulted if and only if:
9794 //
9795 // - [first 4 bullets]
9796 assert(ClassDecl->needsImplicitMoveConstructor());
9797
Richard Smithafb49182012-11-29 01:34:07 +00009798 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9799 if (DSM.isAlreadyBeingDeclared())
9800 return 0;
9801
Richard Smith1c931be2012-04-02 18:40:40 +00009802 // [Checked after we build the declaration]
9803 // - the move assignment operator would not be implicitly defined as
9804 // deleted,
9805
9806 // [DR1402]:
9807 // - each of X's non-static data members and direct or virtual base classes
9808 // has a type that either has a move constructor or is trivially copyable.
9809 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9810 ClassDecl->setFailedImplicitMoveConstructor();
9811 return 0;
9812 }
9813
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009814 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9815 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009816
Richard Smith7756afa2012-06-10 05:43:50 +00009817 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9818 CXXMoveConstructor,
9819 false);
9820
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009821 DeclarationName Name
9822 = Context.DeclarationNames.getCXXConstructorName(
9823 Context.getCanonicalType(ClassType));
9824 SourceLocation ClassLoc = ClassDecl->getLocation();
9825 DeclarationNameInfo NameInfo(Name, ClassLoc);
9826
Richard Smitha8942d72013-05-07 03:19:20 +00009827 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009828 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009829 // member of its class.
9830 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009831 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009832 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009833 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 MoveConstructor->setAccess(AS_public);
9835 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009836
Richard Smithb9d0b762012-07-27 04:22:15 +00009837 // Build an exception specification pointing back at this member.
9838 FunctionProtoType::ExtProtoInfo EPI;
9839 EPI.ExceptionSpecType = EST_Unevaluated;
9840 EPI.ExceptionSpecDecl = MoveConstructor;
9841 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009842 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009843
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009844 // Add the parameter to the constructor.
9845 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9846 ClassLoc, ClassLoc,
9847 /*IdentifierInfo=*/0,
9848 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009849 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009850 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009851
Richard Smithbc2a35d2012-12-08 08:32:28 +00009852 MoveConstructor->setTrivial(
9853 ClassDecl->needsOverloadResolutionForMoveConstructor()
9854 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9855 : ClassDecl->hasTrivialMoveConstructor());
9856
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009857 // C++0x [class.copy]p9:
9858 // If the definition of a class X does not explicitly declare a move
9859 // constructor, one will be implicitly declared as defaulted if and only if:
9860 // [...]
9861 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009862 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009863 // Cache this result so that we don't try to generate this over and over
9864 // on every lookup, leaking memory and wasting time.
9865 ClassDecl->setFailedImplicitMoveConstructor();
9866 return 0;
9867 }
9868
9869 // Note that we have declared this constructor.
9870 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9871
9872 if (Scope *S = getScopeForContext(ClassDecl))
9873 PushOnScopeChains(MoveConstructor, S, false);
9874 ClassDecl->addDecl(MoveConstructor);
9875
9876 return MoveConstructor;
9877}
9878
9879void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9880 CXXConstructorDecl *MoveConstructor) {
9881 assert((MoveConstructor->isDefaulted() &&
9882 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009883 !MoveConstructor->doesThisDeclarationHaveABody() &&
9884 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009885 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9886
9887 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9888 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9889
Eli Friedman9a14db32012-10-18 20:14:08 +00009890 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009891 DiagnosticErrorTrap Trap(Diags);
9892
David Blaikie93c86172013-01-17 05:26:25 +00009893 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009894 Trap.hasErrorOccurred()) {
9895 Diag(CurrentLocation, diag::note_member_synthesized_at)
9896 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9897 MoveConstructor->setInvalidDecl();
9898 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009899 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009900 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9901 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009902 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009903 /*isStmtExpr=*/false)
9904 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009905 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009906 }
9907
9908 MoveConstructor->setUsed();
9909
9910 if (ASTMutationListener *L = getASTMutationListener()) {
9911 L->CompletedImplicitDefinition(MoveConstructor);
9912 }
9913}
9914
Douglas Gregore4e68d42012-02-15 19:33:52 +00009915bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9916 return FD->isDeleted() &&
9917 (FD->isDefaulted() || FD->isImplicit()) &&
9918 isa<CXXMethodDecl>(FD);
9919}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009920
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009921/// \brief Mark the call operator of the given lambda closure type as "used".
9922static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9923 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009924 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009925 Lambda->lookup(
9926 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009927 CallOperator->setReferenced();
9928 CallOperator->setUsed();
9929}
9930
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009931void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9932 SourceLocation CurrentLocation,
9933 CXXConversionDecl *Conv)
9934{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009935 CXXRecordDecl *Lambda = Conv->getParent();
9936
9937 // Make sure that the lambda call operator is marked used.
9938 markLambdaCallOperatorUsed(*this, Lambda);
9939
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009940 Conv->setUsed();
9941
Eli Friedman9a14db32012-10-18 20:14:08 +00009942 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009943 DiagnosticErrorTrap Trap(Diags);
9944
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009945 // Return the address of the __invoke function.
9946 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9947 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009948 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009949 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9950 VK_LValue, Conv->getLocation()).take();
9951 assert(FunctionRef && "Can't refer to __invoke function?");
9952 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009953 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009954 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009955 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009956
9957 // Fill in the __invoke function with a dummy implementation. IR generation
9958 // will fill in the actual details.
9959 Invoke->setUsed();
9960 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009961 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009962
9963 if (ASTMutationListener *L = getASTMutationListener()) {
9964 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009965 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009966 }
9967}
9968
9969void Sema::DefineImplicitLambdaToBlockPointerConversion(
9970 SourceLocation CurrentLocation,
9971 CXXConversionDecl *Conv)
9972{
9973 Conv->setUsed();
9974
Eli Friedman9a14db32012-10-18 20:14:08 +00009975 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009976 DiagnosticErrorTrap Trap(Diags);
9977
Douglas Gregorac1303e2012-02-22 05:02:47 +00009978 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009979 Expr *This = ActOnCXXThis(CurrentLocation).take();
9980 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009981
Eli Friedman23f02672012-03-01 04:01:32 +00009982 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9983 Conv->getLocation(),
9984 Conv, DerefThis);
9985
9986 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9987 // behavior. Note that only the general conversion function does this
9988 // (since it's unusable otherwise); in the case where we inline the
9989 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009990 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009991 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9992 CK_CopyAndAutoreleaseBlockObject,
9993 BuildBlock.get(), 0, VK_RValue);
9994
9995 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009996 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009997 Conv->setInvalidDecl();
9998 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009999 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010000
Douglas Gregorac1303e2012-02-22 05:02:47 +000010001 // Create the return statement that returns the block from the conversion
10002 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010003 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010004 if (Return.isInvalid()) {
10005 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10006 Conv->setInvalidDecl();
10007 return;
10008 }
10009
10010 // Set the body of the conversion function.
10011 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010012 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010013 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010014 Conv->getLocation()));
10015
Douglas Gregorac1303e2012-02-22 05:02:47 +000010016 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010017 if (ASTMutationListener *L = getASTMutationListener()) {
10018 L->CompletedImplicitDefinition(Conv);
10019 }
10020}
10021
Douglas Gregorf52757d2012-03-10 06:53:13 +000010022/// \brief Determine whether the given list arguments contains exactly one
10023/// "real" (non-default) argument.
10024static bool hasOneRealArgument(MultiExprArg Args) {
10025 switch (Args.size()) {
10026 case 0:
10027 return false;
10028
10029 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010030 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010031 return false;
10032
10033 // fall through
10034 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010035 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010036 }
10037
10038 return false;
10039}
10040
John McCall60d7b3a2010-08-24 06:29:42 +000010041ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010042Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010043 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010044 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010045 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010046 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010047 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010048 unsigned ConstructKind,
10049 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010050 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010051
Douglas Gregor2f599792010-04-02 18:24:57 +000010052 // C++0x [class.copy]p34:
10053 // When certain criteria are met, an implementation is allowed to
10054 // omit the copy/move construction of a class object, even if the
10055 // copy/move constructor and/or destructor for the object have
10056 // side effects. [...]
10057 // - when a temporary class object that has not been bound to a
10058 // reference (12.2) would be copied/moved to a class object
10059 // with the same cv-unqualified type, the copy/move operation
10060 // can be omitted by constructing the temporary object
10061 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010062 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010063 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010064 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010065 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010066 }
Mike Stump1eb44332009-09-09 15:08:12 +000010067
10068 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010069 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010070 IsListInitialization, RequiresZeroInit,
10071 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010072}
10073
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010074/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10075/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010076ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010077Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10078 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010079 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010080 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010081 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010082 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010083 unsigned ConstructKind,
10084 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010085 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010086 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010087 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010088 HadMultipleCandidates,
10089 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010090 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10091 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010092}
10093
John McCall68c6c9a2010-02-02 09:10:11 +000010094void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010095 if (VD->isInvalidDecl()) return;
10096
John McCall68c6c9a2010-02-02 09:10:11 +000010097 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010098 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010099 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010100 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010101
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010102 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010103 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010104 CheckDestructorAccess(VD->getLocation(), Destructor,
10105 PDiag(diag::err_access_dtor_var)
10106 << VD->getDeclName()
10107 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010108 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010109
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010110 if (!VD->hasGlobalStorage()) return;
10111
10112 // Emit warning for non-trivial dtor in global scope (a real global,
10113 // class-static, function-static).
10114 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10115
10116 // TODO: this should be re-enabled for static locals by !CXAAtExit
10117 if (!VD->isStaticLocal())
10118 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010119}
10120
Douglas Gregor39da0b82009-09-09 23:08:42 +000010121/// \brief Given a constructor and the set of arguments provided for the
10122/// constructor, convert the arguments and add any required default arguments
10123/// to form a proper call to this constructor.
10124///
10125/// \returns true if an error occurred, false otherwise.
10126bool
10127Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10128 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010129 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010130 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010131 bool AllowExplicit,
10132 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010133 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10134 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010135 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010136
10137 const FunctionProtoType *Proto
10138 = Constructor->getType()->getAs<FunctionProtoType>();
10139 assert(Proto && "Constructor without a prototype?");
10140 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010141
10142 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010143 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010144 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010145 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010146 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010147
10148 VariadicCallType CallType =
10149 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010150 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010151 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010152 Proto, 0,
10153 llvm::makeArrayRef(Args, NumArgs),
10154 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010155 CallType, AllowExplicit,
10156 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010157 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010158
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010159 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010160
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010161 CheckConstructorCall(Constructor,
10162 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10163 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010164 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010165
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010166 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010167}
10168
Anders Carlsson20d45d22009-12-12 00:32:00 +000010169static inline bool
10170CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10171 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010172 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010173 if (isa<NamespaceDecl>(DC)) {
10174 return SemaRef.Diag(FnDecl->getLocation(),
10175 diag::err_operator_new_delete_declared_in_namespace)
10176 << FnDecl->getDeclName();
10177 }
10178
10179 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010180 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010181 return SemaRef.Diag(FnDecl->getLocation(),
10182 diag::err_operator_new_delete_declared_static)
10183 << FnDecl->getDeclName();
10184 }
10185
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010186 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010187}
10188
Anders Carlsson156c78e2009-12-13 17:53:43 +000010189static inline bool
10190CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10191 CanQualType ExpectedResultType,
10192 CanQualType ExpectedFirstParamType,
10193 unsigned DependentParamTypeDiag,
10194 unsigned InvalidParamTypeDiag) {
10195 QualType ResultType =
10196 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10197
10198 // Check that the result type is not dependent.
10199 if (ResultType->isDependentType())
10200 return SemaRef.Diag(FnDecl->getLocation(),
10201 diag::err_operator_new_delete_dependent_result_type)
10202 << FnDecl->getDeclName() << ExpectedResultType;
10203
10204 // Check that the result type is what we expect.
10205 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10206 return SemaRef.Diag(FnDecl->getLocation(),
10207 diag::err_operator_new_delete_invalid_result_type)
10208 << FnDecl->getDeclName() << ExpectedResultType;
10209
10210 // A function template must have at least 2 parameters.
10211 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10212 return SemaRef.Diag(FnDecl->getLocation(),
10213 diag::err_operator_new_delete_template_too_few_parameters)
10214 << FnDecl->getDeclName();
10215
10216 // The function decl must have at least 1 parameter.
10217 if (FnDecl->getNumParams() == 0)
10218 return SemaRef.Diag(FnDecl->getLocation(),
10219 diag::err_operator_new_delete_too_few_parameters)
10220 << FnDecl->getDeclName();
10221
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010222 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010223 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10224 if (FirstParamType->isDependentType())
10225 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10226 << FnDecl->getDeclName() << ExpectedFirstParamType;
10227
10228 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010229 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010230 ExpectedFirstParamType)
10231 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10232 << FnDecl->getDeclName() << ExpectedFirstParamType;
10233
10234 return false;
10235}
10236
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010237static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010238CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010239 // C++ [basic.stc.dynamic.allocation]p1:
10240 // A program is ill-formed if an allocation function is declared in a
10241 // namespace scope other than global scope or declared static in global
10242 // scope.
10243 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10244 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010245
10246 CanQualType SizeTy =
10247 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10248
10249 // C++ [basic.stc.dynamic.allocation]p1:
10250 // The return type shall be void*. The first parameter shall have type
10251 // std::size_t.
10252 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10253 SizeTy,
10254 diag::err_operator_new_dependent_param_type,
10255 diag::err_operator_new_param_type))
10256 return true;
10257
10258 // C++ [basic.stc.dynamic.allocation]p1:
10259 // The first parameter shall not have an associated default argument.
10260 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010261 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010262 diag::err_operator_new_default_arg)
10263 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10264
10265 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010266}
10267
10268static bool
Richard Smith444d3842012-10-20 08:26:51 +000010269CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010270 // C++ [basic.stc.dynamic.deallocation]p1:
10271 // A program is ill-formed if deallocation functions are declared in a
10272 // namespace scope other than global scope or declared static in global
10273 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010274 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10275 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010276
10277 // C++ [basic.stc.dynamic.deallocation]p2:
10278 // Each deallocation function shall return void and its first parameter
10279 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010280 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10281 SemaRef.Context.VoidPtrTy,
10282 diag::err_operator_delete_dependent_param_type,
10283 diag::err_operator_delete_param_type))
10284 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010285
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010286 return false;
10287}
10288
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010289/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10290/// of this overloaded operator is well-formed. If so, returns false;
10291/// otherwise, emits appropriate diagnostics and returns true.
10292bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010293 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010294 "Expected an overloaded operator declaration");
10295
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010296 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10297
Mike Stump1eb44332009-09-09 15:08:12 +000010298 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010299 // The allocation and deallocation functions, operator new,
10300 // operator new[], operator delete and operator delete[], are
10301 // described completely in 3.7.3. The attributes and restrictions
10302 // found in the rest of this subclause do not apply to them unless
10303 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010304 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010305 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010306
Anders Carlssona3ccda52009-12-12 00:26:23 +000010307 if (Op == OO_New || Op == OO_Array_New)
10308 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010309
10310 // C++ [over.oper]p6:
10311 // An operator function shall either be a non-static member
10312 // function or be a non-member function and have at least one
10313 // parameter whose type is a class, a reference to a class, an
10314 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010315 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10316 if (MethodDecl->isStatic())
10317 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010318 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010319 } else {
10320 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010321 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10322 ParamEnd = FnDecl->param_end();
10323 Param != ParamEnd; ++Param) {
10324 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010325 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10326 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010327 ClassOrEnumParam = true;
10328 break;
10329 }
10330 }
10331
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010332 if (!ClassOrEnumParam)
10333 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010334 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010335 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010336 }
10337
10338 // C++ [over.oper]p8:
10339 // An operator function cannot have default arguments (8.3.6),
10340 // except where explicitly stated below.
10341 //
Mike Stump1eb44332009-09-09 15:08:12 +000010342 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010343 // (C++ [over.call]p1).
10344 if (Op != OO_Call) {
10345 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10346 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010347 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010348 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010349 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010350 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010351 }
10352 }
10353
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010354 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10355 { false, false, false }
10356#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10357 , { Unary, Binary, MemberOnly }
10358#include "clang/Basic/OperatorKinds.def"
10359 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010360
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010361 bool CanBeUnaryOperator = OperatorUses[Op][0];
10362 bool CanBeBinaryOperator = OperatorUses[Op][1];
10363 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010364
10365 // C++ [over.oper]p8:
10366 // [...] Operator functions cannot have more or fewer parameters
10367 // than the number required for the corresponding operator, as
10368 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010369 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010370 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010371 if (Op != OO_Call &&
10372 ((NumParams == 1 && !CanBeUnaryOperator) ||
10373 (NumParams == 2 && !CanBeBinaryOperator) ||
10374 (NumParams < 1) || (NumParams > 2))) {
10375 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010376 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010377 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010378 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010379 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010380 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010381 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010382 assert(CanBeBinaryOperator &&
10383 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010384 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010385 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010386
Chris Lattner416e46f2008-11-21 07:57:12 +000010387 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010388 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010389 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010390
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010391 // Overloaded operators other than operator() cannot be variadic.
10392 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010393 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010394 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010395 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010396 }
10397
10398 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010399 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10400 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010401 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010402 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010403 }
10404
10405 // C++ [over.inc]p1:
10406 // The user-defined function called operator++ implements the
10407 // prefix and postfix ++ operator. If this function is a member
10408 // function with no parameters, or a non-member function with one
10409 // parameter of class or enumeration type, it defines the prefix
10410 // increment operator ++ for objects of that type. If the function
10411 // is a member function with one parameter (which shall be of type
10412 // int) or a non-member function with two parameters (the second
10413 // of which shall be of type int), it defines the postfix
10414 // increment operator ++ for objects of that type.
10415 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10416 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10417 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010418 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010419 ParamIsInt = BT->getKind() == BuiltinType::Int;
10420
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010421 if (!ParamIsInt)
10422 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010423 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010424 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010425 }
10426
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010427 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010428}
Chris Lattner5a003a42008-12-17 07:09:26 +000010429
Sean Hunta6c058d2010-01-13 09:01:02 +000010430/// CheckLiteralOperatorDeclaration - Check whether the declaration
10431/// of this literal operator function is well-formed. If so, returns
10432/// false; otherwise, emits appropriate diagnostics and returns true.
10433bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010434 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010435 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10436 << FnDecl->getDeclName();
10437 return true;
10438 }
10439
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010440 if (FnDecl->isExternC()) {
10441 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10442 return true;
10443 }
10444
Sean Hunta6c058d2010-01-13 09:01:02 +000010445 bool Valid = false;
10446
Richard Smith36f5cfe2012-03-09 08:00:36 +000010447 // This might be the definition of a literal operator template.
10448 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10449 // This might be a specialization of a literal operator template.
10450 if (!TpDecl)
10451 TpDecl = FnDecl->getPrimaryTemplate();
10452
Sean Hunt216c2782010-04-07 23:11:06 +000010453 // template <char...> type operator "" name() is the only valid template
10454 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010455 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010456 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010457 // Must have only one template parameter
10458 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10459 if (Params->size() == 1) {
10460 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010461 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010462
Sean Hunt216c2782010-04-07 23:11:06 +000010463 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010464 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10465 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10466 Valid = true;
10467 }
10468 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010469 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010470 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010471 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10472
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010473 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010474
Sean Hunt30019c02010-04-07 22:57:35 +000010475 // unsigned long long int, long double, and any character type are allowed
10476 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010477 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10478 Context.hasSameType(T, Context.LongDoubleTy) ||
10479 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010480 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010481 Context.hasSameType(T, Context.Char16Ty) ||
10482 Context.hasSameType(T, Context.Char32Ty)) {
10483 if (++Param == FnDecl->param_end())
10484 Valid = true;
10485 goto FinishedParams;
10486 }
10487
Sean Hunt30019c02010-04-07 22:57:35 +000010488 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010489 const PointerType *PT = T->getAs<PointerType>();
10490 if (!PT)
10491 goto FinishedParams;
10492 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010493 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010494 goto FinishedParams;
10495 T = T.getUnqualifiedType();
10496
10497 // Move on to the second parameter;
10498 ++Param;
10499
10500 // If there is no second parameter, the first must be a const char *
10501 if (Param == FnDecl->param_end()) {
10502 if (Context.hasSameType(T, Context.CharTy))
10503 Valid = true;
10504 goto FinishedParams;
10505 }
10506
10507 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10508 // are allowed as the first parameter to a two-parameter function
10509 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010510 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010511 Context.hasSameType(T, Context.Char16Ty) ||
10512 Context.hasSameType(T, Context.Char32Ty)))
10513 goto FinishedParams;
10514
10515 // The second and final parameter must be an std::size_t
10516 T = (*Param)->getType().getUnqualifiedType();
10517 if (Context.hasSameType(T, Context.getSizeType()) &&
10518 ++Param == FnDecl->param_end())
10519 Valid = true;
10520 }
10521
10522 // FIXME: This diagnostic is absolutely terrible.
10523FinishedParams:
10524 if (!Valid) {
10525 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10526 << FnDecl->getDeclName();
10527 return true;
10528 }
10529
Richard Smitha9e88b22012-03-09 08:16:22 +000010530 // A parameter-declaration-clause containing a default argument is not
10531 // equivalent to any of the permitted forms.
10532 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10533 ParamEnd = FnDecl->param_end();
10534 Param != ParamEnd; ++Param) {
10535 if ((*Param)->hasDefaultArg()) {
10536 Diag((*Param)->getDefaultArgRange().getBegin(),
10537 diag::err_literal_operator_default_argument)
10538 << (*Param)->getDefaultArgRange();
10539 break;
10540 }
10541 }
10542
Richard Smith2fb4ae32012-03-08 02:39:21 +000010543 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010544 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10545 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010546 // C++11 [usrlit.suffix]p1:
10547 // Literal suffix identifiers that do not start with an underscore
10548 // are reserved for future standardization.
10549 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010550 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010551
Sean Hunta6c058d2010-01-13 09:01:02 +000010552 return false;
10553}
10554
Douglas Gregor074149e2009-01-05 19:45:36 +000010555/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10556/// linkage specification, including the language and (if present)
10557/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10558/// the location of the language string literal, which is provided
10559/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10560/// the '{' brace. Otherwise, this linkage specification does not
10561/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010562Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10563 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010564 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010565 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010566 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010567 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010568 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010569 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010570 Language = LinkageSpecDecl::lang_cxx;
10571 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010572 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010573 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010574 }
Mike Stump1eb44332009-09-09 15:08:12 +000010575
Chris Lattnercc98eac2008-12-17 07:13:27 +000010576 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010577
Douglas Gregor074149e2009-01-05 19:45:36 +000010578 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010579 ExternLoc, LangLoc, Language,
10580 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010581 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010582 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010583 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010584}
10585
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010586/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010587/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10588/// valid, it's the position of the closing '}' brace in a linkage
10589/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010590Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010591 Decl *LinkageSpec,
10592 SourceLocation RBraceLoc) {
10593 if (LinkageSpec) {
10594 if (RBraceLoc.isValid()) {
10595 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10596 LSDecl->setRBraceLoc(RBraceLoc);
10597 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010598 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010599 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010600 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010601}
10602
Michael Han684aa732013-02-22 17:15:32 +000010603Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10604 AttributeList *AttrList,
10605 SourceLocation SemiLoc) {
10606 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10607 // Attribute declarations appertain to empty declaration so we handle
10608 // them here.
10609 if (AttrList)
10610 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010611
Michael Han684aa732013-02-22 17:15:32 +000010612 CurContext->addDecl(ED);
10613 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010614}
10615
Douglas Gregord308e622009-05-18 20:51:54 +000010616/// \brief Perform semantic analysis for the variable declaration that
10617/// occurs within a C++ catch clause, returning the newly-created
10618/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010619VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010620 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010621 SourceLocation StartLoc,
10622 SourceLocation Loc,
10623 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010624 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010625 QualType ExDeclType = TInfo->getType();
10626
Sebastian Redl4b07b292008-12-22 19:15:10 +000010627 // Arrays and functions decay.
10628 if (ExDeclType->isArrayType())
10629 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10630 else if (ExDeclType->isFunctionType())
10631 ExDeclType = Context.getPointerType(ExDeclType);
10632
10633 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10634 // The exception-declaration shall not denote a pointer or reference to an
10635 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010636 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010637 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010638 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010639 Invalid = true;
10640 }
Douglas Gregord308e622009-05-18 20:51:54 +000010641
Sebastian Redl4b07b292008-12-22 19:15:10 +000010642 QualType BaseType = ExDeclType;
10643 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010644 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010645 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010646 BaseType = Ptr->getPointeeType();
10647 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010648 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010649 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010650 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010651 BaseType = Ref->getPointeeType();
10652 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010653 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010654 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010655 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010656 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010657 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010658
Mike Stump1eb44332009-09-09 15:08:12 +000010659 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010660 RequireNonAbstractType(Loc, ExDeclType,
10661 diag::err_abstract_type_in_decl,
10662 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010663 Invalid = true;
10664
John McCall5a180392010-07-24 00:37:23 +000010665 // Only the non-fragile NeXT runtime currently supports C++ catches
10666 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010667 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010668 QualType T = ExDeclType;
10669 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10670 T = RT->getPointeeType();
10671
10672 if (T->isObjCObjectType()) {
10673 Diag(Loc, diag::err_objc_object_catch);
10674 Invalid = true;
10675 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010676 // FIXME: should this be a test for macosx-fragile specifically?
10677 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010678 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010679 }
10680 }
10681
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010682 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010683 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010684 ExDecl->setExceptionVariable(true);
10685
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010686 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010687 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010688 Invalid = true;
10689
Douglas Gregorc41b8782011-07-06 18:14:43 +000010690 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010691 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010692 // Insulate this from anything else we might currently be parsing.
10693 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10694
Douglas Gregor6d182892010-03-05 23:38:39 +000010695 // C++ [except.handle]p16:
10696 // The object declared in an exception-declaration or, if the
10697 // exception-declaration does not specify a name, a temporary (12.2) is
10698 // copy-initialized (8.5) from the exception object. [...]
10699 // The object is destroyed when the handler exits, after the destruction
10700 // of any automatic objects initialized within the handler.
10701 //
10702 // We just pretend to initialize the object with itself, then make sure
10703 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010704 QualType initType = ExDeclType;
10705
10706 InitializedEntity entity =
10707 InitializedEntity::InitializeVariable(ExDecl);
10708 InitializationKind initKind =
10709 InitializationKind::CreateCopy(Loc, SourceLocation());
10710
10711 Expr *opaqueValue =
10712 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010713 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10714 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010715 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010716 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010717 else {
10718 // If the constructor used was non-trivial, set this as the
10719 // "initializer".
10720 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10721 if (!construct->getConstructor()->isTrivial()) {
10722 Expr *init = MaybeCreateExprWithCleanups(construct);
10723 ExDecl->setInit(init);
10724 }
10725
10726 // And make sure it's destructable.
10727 FinalizeVarWithDestructor(ExDecl, recordType);
10728 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010729 }
10730 }
10731
Douglas Gregord308e622009-05-18 20:51:54 +000010732 if (Invalid)
10733 ExDecl->setInvalidDecl();
10734
10735 return ExDecl;
10736}
10737
10738/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10739/// handler.
John McCalld226f652010-08-21 09:40:31 +000010740Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010742 bool Invalid = D.isInvalidType();
10743
10744 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10746 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010747 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10748 D.getIdentifierLoc());
10749 Invalid = true;
10750 }
10751
Sebastian Redl4b07b292008-12-22 19:15:10 +000010752 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010753 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010754 LookupOrdinaryName,
10755 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010756 // The scope should be freshly made just for us. There is just no way
10757 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010758 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010759 if (PrevDecl->isTemplateParameter()) {
10760 // Maybe we will complain about the shadowed template parameter.
10761 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010762 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010763 }
10764 }
10765
Chris Lattnereaaebc72009-04-25 08:06:05 +000010766 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010767 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10768 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010769 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010770 }
10771
Douglas Gregor83cb9422010-09-09 17:09:21 +000010772 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010773 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010774 D.getIdentifierLoc(),
10775 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010776 if (Invalid)
10777 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010778
Sebastian Redl4b07b292008-12-22 19:15:10 +000010779 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010780 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010781 PushOnScopeChains(ExDecl, S);
10782 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010783 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010784
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010785 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010786 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010787}
Anders Carlssonfb311762009-03-14 00:25:26 +000010788
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010789Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010790 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010791 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010792 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010793 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010794
Richard Smithe3f470a2012-07-11 22:37:56 +000010795 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10796 return 0;
10797
10798 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10799 AssertMessage, RParenLoc, false);
10800}
10801
10802Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10803 Expr *AssertExpr,
10804 StringLiteral *AssertMessage,
10805 SourceLocation RParenLoc,
10806 bool Failed) {
10807 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10808 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010809 // In a static_assert-declaration, the constant-expression shall be a
10810 // constant expression that can be contextually converted to bool.
10811 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10812 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010813 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010814
Richard Smithdaaefc52011-12-14 23:32:26 +000010815 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010816 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010817 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010818 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010819 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010820
Richard Smithe3f470a2012-07-11 22:37:56 +000010821 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010822 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010823 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010824 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010825 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010826 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010827 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010828 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010829 }
Mike Stump1eb44332009-09-09 15:08:12 +000010830
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010831 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010832 AssertExpr, AssertMessage, RParenLoc,
10833 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010834
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010835 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010836 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010837}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010838
Douglas Gregor1d869352010-04-07 16:53:43 +000010839/// \brief Perform semantic analysis of the given friend type declaration.
10840///
10841/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010842FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010843 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010844 TypeSourceInfo *TSInfo) {
10845 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10846
10847 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010848 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010849
Richard Smith6b130222011-10-18 21:39:00 +000010850 // C++03 [class.friend]p2:
10851 // An elaborated-type-specifier shall be used in a friend declaration
10852 // for a class.*
10853 //
10854 // * The class-key of the elaborated-type-specifier is required.
10855 if (!ActiveTemplateInstantiations.empty()) {
10856 // Do not complain about the form of friend template types during
10857 // template instantiation; we will already have complained when the
10858 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010859 } else {
10860 if (!T->isElaboratedTypeSpecifier()) {
10861 // If we evaluated the type to a record type, suggest putting
10862 // a tag in front.
10863 if (const RecordType *RT = T->getAs<RecordType>()) {
10864 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010865
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010866 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010867
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010868 Diag(TypeRange.getBegin(),
10869 getLangOpts().CPlusPlus11 ?
10870 diag::warn_cxx98_compat_unelaborated_friend_type :
10871 diag::ext_unelaborated_friend_type)
10872 << (unsigned) RD->getTagKind()
10873 << T
10874 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10875 InsertionText);
10876 } else {
10877 Diag(FriendLoc,
10878 getLangOpts().CPlusPlus11 ?
10879 diag::warn_cxx98_compat_nonclass_type_friend :
10880 diag::ext_nonclass_type_friend)
10881 << T
10882 << TypeRange;
10883 }
10884 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010885 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010886 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010887 diag::warn_cxx98_compat_enum_friend :
10888 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010889 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010890 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010891 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010892
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010893 // C++11 [class.friend]p3:
10894 // A friend declaration that does not declare a function shall have one
10895 // of the following forms:
10896 // friend elaborated-type-specifier ;
10897 // friend simple-type-specifier ;
10898 // friend typename-specifier ;
10899 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10900 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10901 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010902
Douglas Gregor06245bf2010-04-07 17:57:12 +000010903 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010904 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010905 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010906 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010907}
10908
John McCall9a34edb2010-10-19 01:40:49 +000010909/// Handle a friend tag declaration where the scope specifier was
10910/// templated.
10911Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10912 unsigned TagSpec, SourceLocation TagLoc,
10913 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010914 IdentifierInfo *Name,
10915 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010916 AttributeList *Attr,
10917 MultiTemplateParamsArg TempParamLists) {
10918 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10919
10920 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010921 bool Invalid = false;
10922
10923 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010924 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010925 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010926 TempParamLists.size(),
10927 /*friend*/ true,
10928 isExplicitSpecialization,
10929 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010930 if (TemplateParams->size() > 0) {
10931 // This is a declaration of a class template.
10932 if (Invalid)
10933 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010934
Eric Christopher4110e132011-07-21 05:34:24 +000010935 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10936 SS, Name, NameLoc, Attr,
10937 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010938 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010939 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010940 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010941 } else {
10942 // The "template<>" header is extraneous.
10943 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10944 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10945 isExplicitSpecialization = true;
10946 }
10947 }
10948
10949 if (Invalid) return 0;
10950
John McCall9a34edb2010-10-19 01:40:49 +000010951 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010952 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010953 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010954 isAllExplicitSpecializations = false;
10955 break;
10956 }
10957 }
10958
10959 // FIXME: don't ignore attributes.
10960
10961 // If it's explicit specializations all the way down, just forget
10962 // about the template header and build an appropriate non-templated
10963 // friend. TODO: for source fidelity, remember the headers.
10964 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010965 if (SS.isEmpty()) {
10966 bool Owned = false;
10967 bool IsDependent = false;
10968 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10969 Attr, AS_public,
10970 /*ModulePrivateLoc=*/SourceLocation(),
10971 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010972 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010973 /*ScopedEnumUsesClassTag=*/false,
10974 /*UnderlyingType=*/TypeResult());
10975 }
10976
Douglas Gregor2494dd02011-03-01 01:34:45 +000010977 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010978 ElaboratedTypeKeyword Keyword
10979 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010980 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010981 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010982 if (T.isNull())
10983 return 0;
10984
10985 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10986 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010987 DependentNameTypeLoc TL =
10988 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010989 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010990 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010991 TL.setNameLoc(NameLoc);
10992 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010993 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010994 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010995 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010996 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010997 }
10998
10999 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011000 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011001 Friend->setAccess(AS_public);
11002 CurContext->addDecl(Friend);
11003 return Friend;
11004 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011005
11006 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11007
11008
John McCall9a34edb2010-10-19 01:40:49 +000011009
11010 // Handle the case of a templated-scope friend class. e.g.
11011 // template <class T> class A<T>::B;
11012 // FIXME: we don't support these right now.
11013 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11014 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11015 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011016 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011017 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011018 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011019 TL.setNameLoc(NameLoc);
11020
11021 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011022 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011023 Friend->setAccess(AS_public);
11024 Friend->setUnsupportedFriend(true);
11025 CurContext->addDecl(Friend);
11026 return Friend;
11027}
11028
11029
John McCalldd4a3b02009-09-16 22:47:08 +000011030/// Handle a friend type declaration. This works in tandem with
11031/// ActOnTag.
11032///
11033/// Notes on friend class templates:
11034///
11035/// We generally treat friend class declarations as if they were
11036/// declaring a class. So, for example, the elaborated type specifier
11037/// in a friend declaration is required to obey the restrictions of a
11038/// class-head (i.e. no typedefs in the scope chain), template
11039/// parameters are required to match up with simple template-ids, &c.
11040/// However, unlike when declaring a template specialization, it's
11041/// okay to refer to a template specialization without an empty
11042/// template parameter declaration, e.g.
11043/// friend class A<T>::B<unsigned>;
11044/// We permit this as a special case; if there are any template
11045/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011046/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011047Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011048 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011049 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011050
11051 assert(DS.isFriendSpecified());
11052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11053
John McCalldd4a3b02009-09-16 22:47:08 +000011054 // Try to convert the decl specifier to a type. This works for
11055 // friend templates because ActOnTag never produces a ClassTemplateDecl
11056 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011057 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011058 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11059 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011060 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011061 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011062
Douglas Gregor6ccab972010-12-16 01:14:37 +000011063 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11064 return 0;
11065
John McCalldd4a3b02009-09-16 22:47:08 +000011066 // This is definitely an error in C++98. It's probably meant to
11067 // be forbidden in C++0x, too, but the specification is just
11068 // poorly written.
11069 //
11070 // The problem is with declarations like the following:
11071 // template <T> friend A<T>::foo;
11072 // where deciding whether a class C is a friend or not now hinges
11073 // on whether there exists an instantiation of A that causes
11074 // 'foo' to equal C. There are restrictions on class-heads
11075 // (which we declare (by fiat) elaborated friend declarations to
11076 // be) that makes this tractable.
11077 //
11078 // FIXME: handle "template <> friend class A<T>;", which
11079 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011080 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011081 Diag(Loc, diag::err_tagless_friend_type_template)
11082 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011083 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011084 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011085
John McCall02cace72009-08-28 07:59:38 +000011086 // C++98 [class.friend]p1: A friend of a class is a function
11087 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011088 // This is fixed in DR77, which just barely didn't make the C++03
11089 // deadline. It's also a very silly restriction that seriously
11090 // affects inner classes and which nobody else seems to implement;
11091 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011092 //
11093 // But note that we could warn about it: it's always useless to
11094 // friend one of your own members (it's not, however, worthless to
11095 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011096
John McCalldd4a3b02009-09-16 22:47:08 +000011097 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011098 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011099 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011100 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011101 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011102 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011103 DS.getFriendSpecLoc());
11104 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011105 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011106
11107 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011108 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011109
John McCalldd4a3b02009-09-16 22:47:08 +000011110 D->setAccess(AS_public);
11111 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011112
John McCalld226f652010-08-21 09:40:31 +000011113 return D;
John McCall02cace72009-08-28 07:59:38 +000011114}
11115
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011116NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11117 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011118 const DeclSpec &DS = D.getDeclSpec();
11119
11120 assert(DS.isFriendSpecified());
11121 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11122
11123 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011124 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011125
11126 // C++ [class.friend]p1
11127 // A friend of a class is a function or class....
11128 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011129 // It *doesn't* see through dependent types, which is correct
11130 // according to [temp.arg.type]p3:
11131 // If a declaration acquires a function type through a
11132 // type dependent on a template-parameter and this causes
11133 // a declaration that does not use the syntactic form of a
11134 // function declarator to have a function type, the program
11135 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011136 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011137 Diag(Loc, diag::err_unexpected_friend);
11138
11139 // It might be worthwhile to try to recover by creating an
11140 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011141 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011142 }
11143
11144 // C++ [namespace.memdef]p3
11145 // - If a friend declaration in a non-local class first declares a
11146 // class or function, the friend class or function is a member
11147 // of the innermost enclosing namespace.
11148 // - The name of the friend is not found by simple name lookup
11149 // until a matching declaration is provided in that namespace
11150 // scope (either before or after the class declaration granting
11151 // friendship).
11152 // - If a friend function is called, its name may be found by the
11153 // name lookup that considers functions from namespaces and
11154 // classes associated with the types of the function arguments.
11155 // - When looking for a prior declaration of a class or a function
11156 // declared as a friend, scopes outside the innermost enclosing
11157 // namespace scope are not considered.
11158
John McCall337ec3d2010-10-12 23:13:28 +000011159 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011160 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11161 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011162 assert(Name);
11163
Douglas Gregor6ccab972010-12-16 01:14:37 +000011164 // Check for unexpanded parameter packs.
11165 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11166 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11167 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11168 return 0;
11169
John McCall67d1a672009-08-06 02:15:43 +000011170 // The context we found the declaration in, or in which we should
11171 // create the declaration.
11172 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011173 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011174 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011175 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011176
John McCall337ec3d2010-10-12 23:13:28 +000011177 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000011178
John McCall337ec3d2010-10-12 23:13:28 +000011179 // There are four cases here.
11180 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000011181 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000011182 // there as appropriate.
11183 // Recover from invalid scope qualifiers as if they just weren't there.
11184 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000011185 // C++0x [namespace.memdef]p3:
11186 // If the name in a friend declaration is neither qualified nor
11187 // a template-id and the declaration is a function or an
11188 // elaborated-type-specifier, the lookup to determine whether
11189 // the entity has been previously declared shall not consider
11190 // any scopes outside the innermost enclosing namespace.
11191 // C++0x [class.friend]p11:
11192 // If a friend declaration appears in a local class and the name
11193 // specified is an unqualified name, a prior declaration is
11194 // looked up without considering scopes that are outside the
11195 // innermost enclosing non-class scope. For a friend function
11196 // declaration, if there is no prior declaration, the program is
11197 // ill-formed.
11198 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000011199 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011200
John McCall29ae6e52010-10-13 05:45:15 +000011201 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011202 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011203
Rafael Espindola11dc6342013-04-25 20:12:36 +000011204 // Skip class contexts. If someone can cite chapter and verse
11205 // for this behavior, that would be nice --- it's what GCC and
11206 // EDG do, and it seems like a reasonable intent, but the spec
11207 // really only says that checks for unqualified existing
11208 // declarations should stop at the nearest enclosing namespace,
11209 // not that they should only consider the nearest enclosing
11210 // namespace.
11211 while (DC->isRecord())
11212 DC = DC->getParent();
11213
11214 DeclContext *LookupDC = DC;
11215 while (LookupDC->isTransparentContext())
11216 LookupDC = LookupDC->getParent();
11217
11218 while (true) {
11219 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011220
11221 // TODO: decide what we think about using declarations.
Rafael Espindola11dc6342013-04-25 20:12:36 +000011222 if (isLocal)
John McCall67d1a672009-08-06 02:15:43 +000011223 break;
John McCall29ae6e52010-10-13 05:45:15 +000011224
Rafael Espindola11dc6342013-04-25 20:12:36 +000011225 if (!Previous.empty()) {
11226 DC = LookupDC;
11227 break;
John McCall8a407372010-10-14 22:22:28 +000011228 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011229
11230 if (isTemplateId) {
11231 if (isa<TranslationUnitDecl>(LookupDC)) break;
11232 } else {
11233 if (LookupDC->isFileContext()) break;
11234 }
11235 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011236 }
11237
John McCall380aaa42010-10-13 06:22:15 +000011238 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011239
Douglas Gregor883af832011-10-10 01:11:59 +000011240 // C++ [class.friend]p6:
11241 // A function can be defined in a friend declaration of a class if and
11242 // only if the class is a non-local class (9.8), the function name is
11243 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011244 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011245 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11246 }
11247
John McCall337ec3d2010-10-12 23:13:28 +000011248 // - There's a non-dependent scope specifier, in which case we
11249 // compute it and do a previous lookup there for a function
11250 // or function template.
11251 } else if (!SS.getScopeRep()->isDependent()) {
11252 DC = computeDeclContext(SS);
11253 if (!DC) return 0;
11254
11255 if (RequireCompleteDeclContext(SS, DC)) return 0;
11256
11257 LookupQualifiedName(Previous, DC);
11258
11259 // Ignore things found implicitly in the wrong scope.
11260 // TODO: better diagnostics for this case. Suggesting the right
11261 // qualified scope would be nice...
11262 LookupResult::Filter F = Previous.makeFilter();
11263 while (F.hasNext()) {
11264 NamedDecl *D = F.next();
11265 if (!DC->InEnclosingNamespaceSetOf(
11266 D->getDeclContext()->getRedeclContext()))
11267 F.erase();
11268 }
11269 F.done();
11270
11271 if (Previous.empty()) {
11272 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011273 Diag(Loc, diag::err_qualified_friend_not_found)
11274 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011275 return 0;
11276 }
11277
11278 // C++ [class.friend]p1: A friend of a class is a function or
11279 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011280 if (DC->Equals(CurContext))
11281 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011282 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011283 diag::warn_cxx98_compat_friend_is_member :
11284 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011285
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011286 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011287 // C++ [class.friend]p6:
11288 // A function can be defined in a friend declaration of a class if and
11289 // only if the class is a non-local class (9.8), the function name is
11290 // unqualified, and the function has namespace scope.
11291 SemaDiagnosticBuilder DB
11292 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11293
11294 DB << SS.getScopeRep();
11295 if (DC->isFileContext())
11296 DB << FixItHint::CreateRemoval(SS.getRange());
11297 SS.clear();
11298 }
John McCall337ec3d2010-10-12 23:13:28 +000011299
11300 // - There's a scope specifier that does not match any template
11301 // parameter lists, in which case we use some arbitrary context,
11302 // create a method or method template, and wait for instantiation.
11303 // - There's a scope specifier that does match some template
11304 // parameter lists, which we don't handle right now.
11305 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011306 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011307 // C++ [class.friend]p6:
11308 // A function can be defined in a friend declaration of a class if and
11309 // only if the class is a non-local class (9.8), the function name is
11310 // unqualified, and the function has namespace scope.
11311 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11312 << SS.getScopeRep();
11313 }
11314
John McCall337ec3d2010-10-12 23:13:28 +000011315 DC = CurContext;
11316 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011317 }
Douglas Gregor883af832011-10-10 01:11:59 +000011318
John McCall29ae6e52010-10-13 05:45:15 +000011319 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011320 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011321 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11322 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11323 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011324 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011325 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11326 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011327 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011328 }
John McCall67d1a672009-08-06 02:15:43 +000011329 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011330
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011331 // FIXME: This is an egregious hack to cope with cases where the scope stack
11332 // does not contain the declaration context, i.e., in an out-of-line
11333 // definition of a class.
11334 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11335 if (!DCScope) {
11336 FakeDCScope.setEntity(DC);
11337 DCScope = &FakeDCScope;
11338 }
11339
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011340 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011341 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011342 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011343 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011344
Douglas Gregor182ddf02009-09-28 00:08:27 +000011345 assert(ND->getDeclContext() == DC);
11346 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011347
John McCallab88d972009-08-31 22:39:49 +000011348 // Add the function declaration to the appropriate lookup tables,
11349 // adjusting the redeclarations list as necessary. We don't
11350 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011351 //
John McCallab88d972009-08-31 22:39:49 +000011352 // Also update the scope-based lookup if the target context's
11353 // lookup context is in lexical scope.
11354 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011355 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011356 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011357 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011358 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011359 }
John McCall02cace72009-08-28 07:59:38 +000011360
11361 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011362 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011363 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011364 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011365 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011366
John McCall1f2e1a92012-08-10 03:15:35 +000011367 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011368 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011369 } else {
11370 if (DC->isRecord()) CheckFriendAccess(ND);
11371
John McCall6102ca12010-10-16 06:59:13 +000011372 FunctionDecl *FD;
11373 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11374 FD = FTD->getTemplatedDecl();
11375 else
11376 FD = cast<FunctionDecl>(ND);
11377
11378 // Mark templated-scope function declarations as unsupported.
11379 if (FD->getNumTemplateParameterLists())
11380 FrD->setUnsupportedFriend(true);
11381 }
John McCall337ec3d2010-10-12 23:13:28 +000011382
John McCalld226f652010-08-21 09:40:31 +000011383 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011384}
11385
John McCalld226f652010-08-21 09:40:31 +000011386void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11387 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011388
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011389 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011390 if (!Fn) {
11391 Diag(DelLoc, diag::err_deleted_non_function);
11392 return;
11393 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011394
Douglas Gregoref96ee02012-01-14 16:38:05 +000011395 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011396 // Don't consider the implicit declaration we generate for explicit
11397 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011398 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11399 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011400 Diag(DelLoc, diag::err_deleted_decl_not_first);
11401 Diag(Prev->getLocation(), diag::note_previous_declaration);
11402 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011403 // If the declaration wasn't the first, we delete the function anyway for
11404 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011405 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011406 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011407
11408 if (Fn->isDeleted())
11409 return;
11410
11411 // See if we're deleting a function which is already known to override a
11412 // non-deleted virtual function.
11413 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11414 bool IssuedDiagnostic = false;
11415 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11416 E = MD->end_overridden_methods();
11417 I != E; ++I) {
11418 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11419 if (!IssuedDiagnostic) {
11420 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11421 IssuedDiagnostic = true;
11422 }
11423 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11424 }
11425 }
11426 }
11427
Sean Hunt10620eb2011-05-06 20:44:56 +000011428 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011429}
Sebastian Redl13e88542009-04-27 21:33:24 +000011430
Sean Hunte4246a62011-05-12 06:15:49 +000011431void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011432 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011433
11434 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011435 if (MD->getParent()->isDependentType()) {
11436 MD->setDefaulted();
11437 MD->setExplicitlyDefaulted();
11438 return;
11439 }
11440
Sean Hunte4246a62011-05-12 06:15:49 +000011441 CXXSpecialMember Member = getSpecialMember(MD);
11442 if (Member == CXXInvalid) {
11443 Diag(DefaultLoc, diag::err_default_special_members);
11444 return;
11445 }
11446
11447 MD->setDefaulted();
11448 MD->setExplicitlyDefaulted();
11449
Sean Huntcd10dec2011-05-23 23:14:04 +000011450 // If this definition appears within the record, do the checking when
11451 // the record is complete.
11452 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011453 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011454 // Find the uninstantiated declaration that actually had the '= default'
11455 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011456 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011457
Richard Smith12fef492013-03-27 00:22:47 +000011458 // If the method was defaulted on its first declaration, we will have
11459 // already performed the checking in CheckCompletedCXXClass. Such a
11460 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011461 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011462 return;
11463
Richard Smithb9d0b762012-07-27 04:22:15 +000011464 CheckExplicitlyDefaultedSpecialMember(MD);
11465
Richard Smith1d28caf2012-12-11 01:14:52 +000011466 // The exception specification is needed because we are defining the
11467 // function.
11468 ResolveExceptionSpec(DefaultLoc,
11469 MD->getType()->castAs<FunctionProtoType>());
11470
Sean Hunte4246a62011-05-12 06:15:49 +000011471 switch (Member) {
11472 case CXXDefaultConstructor: {
11473 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011474 if (!CD->isInvalidDecl())
11475 DefineImplicitDefaultConstructor(DefaultLoc, CD);
11476 break;
11477 }
11478
11479 case CXXCopyConstructor: {
11480 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011481 if (!CD->isInvalidDecl())
11482 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000011483 break;
11484 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000011485
Sean Hunt2b188082011-05-14 05:23:28 +000011486 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000011487 if (!MD->isInvalidDecl())
11488 DefineImplicitCopyAssignment(DefaultLoc, MD);
11489 break;
11490 }
11491
Sean Huntcb45a0f2011-05-12 22:46:25 +000011492 case CXXDestructor: {
11493 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000011494 if (!DD->isInvalidDecl())
11495 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000011496 break;
11497 }
11498
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011499 case CXXMoveConstructor: {
11500 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011501 if (!CD->isInvalidDecl())
11502 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000011503 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011504 }
Sean Hunt82713172011-05-25 23:16:36 +000011505
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011506 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011507 if (!MD->isInvalidDecl())
11508 DefineImplicitMoveAssignment(DefaultLoc, MD);
11509 break;
11510 }
11511
11512 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011513 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011514 }
11515 } else {
11516 Diag(DefaultLoc, diag::err_default_special_members);
11517 }
11518}
11519
Sebastian Redl13e88542009-04-27 21:33:24 +000011520static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011521 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011522 Stmt *SubStmt = *CI;
11523 if (!SubStmt)
11524 continue;
11525 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011526 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011527 diag::err_return_in_constructor_handler);
11528 if (!isa<Expr>(SubStmt))
11529 SearchForReturnInStmt(Self, SubStmt);
11530 }
11531}
11532
11533void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11534 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11535 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11536 SearchForReturnInStmt(*this, Handler);
11537 }
11538}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011539
David Blaikie299adab2013-01-18 23:03:15 +000011540bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011541 const CXXMethodDecl *Old) {
11542 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11543 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11544
11545 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11546
11547 // If the calling conventions match, everything is fine
11548 if (NewCC == OldCC)
11549 return false;
11550
11551 // If either of the calling conventions are set to "default", we need to pick
11552 // something more sensible based on the target. This supports code where the
11553 // one method explicitly sets thiscall, and another has no explicit calling
11554 // convention.
11555 CallingConv Default =
11556 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11557 if (NewCC == CC_Default)
11558 NewCC = Default;
11559 if (OldCC == CC_Default)
11560 OldCC = Default;
11561
11562 // If the calling conventions still don't match, then report the error
11563 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011564 Diag(New->getLocation(),
11565 diag::err_conflicting_overriding_cc_attributes)
11566 << New->getDeclName() << New->getType() << Old->getType();
11567 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11568 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011569 }
11570
11571 return false;
11572}
11573
Mike Stump1eb44332009-09-09 15:08:12 +000011574bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011575 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011576 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11577 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011578
Chandler Carruth73857792010-02-15 11:53:20 +000011579 if (Context.hasSameType(NewTy, OldTy) ||
11580 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011582
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011583 // Check if the return types are covariant
11584 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011585
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011586 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011587 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11588 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011589 NewClassTy = NewPT->getPointeeType();
11590 OldClassTy = OldPT->getPointeeType();
11591 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011592 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11593 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11594 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11595 NewClassTy = NewRT->getPointeeType();
11596 OldClassTy = OldRT->getPointeeType();
11597 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011598 }
11599 }
Mike Stump1eb44332009-09-09 15:08:12 +000011600
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011601 // The return types aren't either both pointers or references to a class type.
11602 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011603 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011604 diag::err_different_return_type_for_overriding_virtual_function)
11605 << New->getDeclName() << NewTy << OldTy;
11606 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011607
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011608 return true;
11609 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011610
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011611 // C++ [class.virtual]p6:
11612 // If the return type of D::f differs from the return type of B::f, the
11613 // class type in the return type of D::f shall be complete at the point of
11614 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011615 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11616 if (!RT->isBeingDefined() &&
11617 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011618 diag::err_covariant_return_incomplete,
11619 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011620 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011621 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011622
Douglas Gregora4923eb2009-11-16 21:35:15 +000011623 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011624 // Check if the new class derives from the old class.
11625 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11626 Diag(New->getLocation(),
11627 diag::err_covariant_return_not_derived)
11628 << New->getDeclName() << NewTy << OldTy;
11629 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11630 return true;
11631 }
Mike Stump1eb44332009-09-09 15:08:12 +000011632
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011633 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011634 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011635 diag::err_covariant_return_inaccessible_base,
11636 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11637 // FIXME: Should this point to the return type?
11638 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011639 // FIXME: this note won't trigger for delayed access control
11640 // diagnostics, and it's impossible to get an undelayed error
11641 // here from access control during the original parse because
11642 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11644 return true;
11645 }
11646 }
Mike Stump1eb44332009-09-09 15:08:12 +000011647
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011648 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011649 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011650 Diag(New->getLocation(),
11651 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011652 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011653 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11654 return true;
11655 };
Mike Stump1eb44332009-09-09 15:08:12 +000011656
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011657
11658 // The new class type must have the same or less qualifiers as the old type.
11659 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11660 Diag(New->getLocation(),
11661 diag::err_covariant_return_type_class_type_more_qualified)
11662 << New->getDeclName() << NewTy << OldTy;
11663 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11664 return true;
11665 };
Mike Stump1eb44332009-09-09 15:08:12 +000011666
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011667 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011668}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011669
Douglas Gregor4ba31362009-12-01 17:24:26 +000011670/// \brief Mark the given method pure.
11671///
11672/// \param Method the method to be marked pure.
11673///
11674/// \param InitRange the source range that covers the "0" initializer.
11675bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011676 SourceLocation EndLoc = InitRange.getEnd();
11677 if (EndLoc.isValid())
11678 Method->setRangeEnd(EndLoc);
11679
Douglas Gregor4ba31362009-12-01 17:24:26 +000011680 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11681 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011682 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011683 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011684
11685 if (!Method->isInvalidDecl())
11686 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11687 << Method->getDeclName() << InitRange;
11688 return true;
11689}
11690
Douglas Gregor552e2992012-02-21 02:22:07 +000011691/// \brief Determine whether the given declaration is a static data member.
11692static bool isStaticDataMember(Decl *D) {
11693 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11694 if (!Var)
11695 return false;
11696
11697 return Var->isStaticDataMember();
11698}
John McCall731ad842009-12-19 09:28:58 +000011699/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11700/// an initializer for the out-of-line declaration 'Dcl'. The scope
11701/// is a fresh scope pushed for just this purpose.
11702///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011703/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11704/// static data member of class X, names should be looked up in the scope of
11705/// class X.
John McCalld226f652010-08-21 09:40:31 +000011706void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011707 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011708 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011709
John McCall731ad842009-12-19 09:28:58 +000011710 // We should only get called for declarations with scope specifiers, like:
11711 // int foo::bar;
11712 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011713 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011714
11715 // If we are parsing the initializer for a static data member, push a
11716 // new expression evaluation context that is associated with this static
11717 // data member.
11718 if (isStaticDataMember(D))
11719 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011720}
11721
11722/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011723/// initializer for the out-of-line declaration 'D'.
11724void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011725 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011726 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011727
Douglas Gregor552e2992012-02-21 02:22:07 +000011728 if (isStaticDataMember(D))
11729 PopExpressionEvaluationContext();
11730
John McCall731ad842009-12-19 09:28:58 +000011731 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011732 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011733}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011734
11735/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11736/// C++ if/switch/while/for statement.
11737/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011738DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011739 // C++ 6.4p2:
11740 // The declarator shall not specify a function or an array.
11741 // The type-specifier-seq shall not contain typedef and shall not declare a
11742 // new class or enumeration.
11743 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11744 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011745
11746 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011747 if (!Dcl)
11748 return true;
11749
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011750 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11751 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011752 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011753 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011754 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011755
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011756 return Dcl;
11757}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011758
Douglas Gregordfe65432011-07-28 19:11:31 +000011759void Sema::LoadExternalVTableUses() {
11760 if (!ExternalSource)
11761 return;
11762
11763 SmallVector<ExternalVTableUse, 4> VTables;
11764 ExternalSource->ReadUsedVTables(VTables);
11765 SmallVector<VTableUse, 4> NewUses;
11766 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11767 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11768 = VTablesUsed.find(VTables[I].Record);
11769 // Even if a definition wasn't required before, it may be required now.
11770 if (Pos != VTablesUsed.end()) {
11771 if (!Pos->second && VTables[I].DefinitionRequired)
11772 Pos->second = true;
11773 continue;
11774 }
11775
11776 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11777 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11778 }
11779
11780 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11781}
11782
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011783void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11784 bool DefinitionRequired) {
11785 // Ignore any vtable uses in unevaluated operands or for classes that do
11786 // not have a vtable.
11787 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011788 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011789 return;
11790
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011791 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011792 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011793 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11794 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11795 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11796 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011797 // If we already had an entry, check to see if we are promoting this vtable
11798 // to required a definition. If so, we need to reappend to the VTableUses
11799 // list, since we may have already processed the first entry.
11800 if (DefinitionRequired && !Pos.first->second) {
11801 Pos.first->second = true;
11802 } else {
11803 // Otherwise, we can early exit.
11804 return;
11805 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011806 }
11807
11808 // Local classes need to have their virtual members marked
11809 // immediately. For all other classes, we mark their virtual members
11810 // at the end of the translation unit.
11811 if (Class->isLocalClass())
11812 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011813 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011814 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011815}
11816
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011817bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011818 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011819 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011820 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011821
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011822 // Note: The VTableUses vector could grow as a result of marking
11823 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011824 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011825 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011826 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011827 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011828 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011829 if (!Class)
11830 continue;
11831
11832 SourceLocation Loc = VTableUses[I].second;
11833
Richard Smithb9d0b762012-07-27 04:22:15 +000011834 bool DefineVTable = true;
11835
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011836 // If this class has a key function, but that key function is
11837 // defined in another translation unit, we don't need to emit the
11838 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011839 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011840 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011841 switch (KeyFunction->getTemplateSpecializationKind()) {
11842 case TSK_Undeclared:
11843 case TSK_ExplicitSpecialization:
11844 case TSK_ExplicitInstantiationDeclaration:
11845 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011846 DefineVTable = false;
11847 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011848
11849 case TSK_ExplicitInstantiationDefinition:
11850 case TSK_ImplicitInstantiation:
11851 // We will be instantiating the key function.
11852 break;
11853 }
11854 } else if (!KeyFunction) {
11855 // If we have a class with no key function that is the subject
11856 // of an explicit instantiation declaration, suppress the
11857 // vtable; it will live with the explicit instantiation
11858 // definition.
11859 bool IsExplicitInstantiationDeclaration
11860 = Class->getTemplateSpecializationKind()
11861 == TSK_ExplicitInstantiationDeclaration;
11862 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11863 REnd = Class->redecls_end();
11864 R != REnd; ++R) {
11865 TemplateSpecializationKind TSK
11866 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11867 if (TSK == TSK_ExplicitInstantiationDeclaration)
11868 IsExplicitInstantiationDeclaration = true;
11869 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11870 IsExplicitInstantiationDeclaration = false;
11871 break;
11872 }
11873 }
11874
11875 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011876 DefineVTable = false;
11877 }
11878
11879 // The exception specifications for all virtual members may be needed even
11880 // if we are not providing an authoritative form of the vtable in this TU.
11881 // We may choose to emit it available_externally anyway.
11882 if (!DefineVTable) {
11883 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11884 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011885 }
11886
11887 // Mark all of the virtual members of this class as referenced, so
11888 // that we can build a vtable. Then, tell the AST consumer that a
11889 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011890 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011891 MarkVirtualMembersReferenced(Loc, Class);
11892 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11893 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11894
11895 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011896 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011897 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011898 const FunctionDecl *KeyFunctionDef = 0;
11899 if (!KeyFunction ||
11900 (KeyFunction->hasBody(KeyFunctionDef) &&
11901 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011902 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11903 TSK_ExplicitInstantiationDefinition
11904 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11905 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011906 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011907 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011908 VTableUses.clear();
11909
Douglas Gregor78844032011-04-22 22:25:37 +000011910 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011911}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011912
Richard Smithb9d0b762012-07-27 04:22:15 +000011913void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11914 const CXXRecordDecl *RD) {
11915 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11916 E = RD->method_end(); I != E; ++I)
11917 if ((*I)->isVirtual() && !(*I)->isPure())
11918 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11919}
11920
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011921void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11922 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011923 // Mark all functions which will appear in RD's vtable as used.
11924 CXXFinalOverriderMap FinalOverriders;
11925 RD->getFinalOverriders(FinalOverriders);
11926 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11927 E = FinalOverriders.end();
11928 I != E; ++I) {
11929 for (OverridingMethods::const_iterator OI = I->second.begin(),
11930 OE = I->second.end();
11931 OI != OE; ++OI) {
11932 assert(OI->second.size() > 0 && "no final overrider");
11933 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011934
Richard Smithff817f72012-07-07 06:59:51 +000011935 // C++ [basic.def.odr]p2:
11936 // [...] A virtual member function is used if it is not pure. [...]
11937 if (!Overrider->isPure())
11938 MarkFunctionReferenced(Loc, Overrider);
11939 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011940 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011941
11942 // Only classes that have virtual bases need a VTT.
11943 if (RD->getNumVBases() == 0)
11944 return;
11945
11946 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11947 e = RD->bases_end(); i != e; ++i) {
11948 const CXXRecordDecl *Base =
11949 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011950 if (Base->getNumVBases() == 0)
11951 continue;
11952 MarkVirtualMembersReferenced(Loc, Base);
11953 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011954}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011955
11956/// SetIvarInitializers - This routine builds initialization ASTs for the
11957/// Objective-C implementation whose ivars need be initialized.
11958void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011959 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011960 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011961 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011962 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011963 CollectIvarsToConstructOrDestruct(OID, ivars);
11964 if (ivars.empty())
11965 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011966 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011967 for (unsigned i = 0; i < ivars.size(); i++) {
11968 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011969 if (Field->isInvalidDecl())
11970 continue;
11971
Sean Huntcbb67482011-01-08 20:30:50 +000011972 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011973 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11974 InitializationKind InitKind =
11975 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011976
11977 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11978 ExprResult MemberInit =
11979 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000011980 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011981 // Note, MemberInit could actually come back empty if no initialization
11982 // is required (e.g., because it would call a trivial default constructor)
11983 if (!MemberInit.get() || MemberInit.isInvalid())
11984 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011985
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011986 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011987 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11988 SourceLocation(),
11989 MemberInit.takeAs<Expr>(),
11990 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011991 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011992
11993 // Be sure that the destructor is accessible and is marked as referenced.
11994 if (const RecordType *RecordTy
11995 = Context.getBaseElementType(Field->getType())
11996 ->getAs<RecordType>()) {
11997 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011998 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011999 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012000 CheckDestructorAccess(Field->getLocation(), Destructor,
12001 PDiag(diag::err_access_dtor_ivar)
12002 << Context.getBaseElementType(Field->getType()));
12003 }
12004 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012005 }
12006 ObjCImplementation->setIvarInitializers(Context,
12007 AllToInit.data(), AllToInit.size());
12008 }
12009}
Sean Huntfe57eef2011-05-04 05:57:24 +000012010
Sean Huntebcbe1d2011-05-04 23:29:54 +000012011static
12012void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12013 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12014 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12015 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12016 Sema &S) {
12017 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12018 CE = Current.end();
12019 if (Ctor->isInvalidDecl())
12020 return;
12021
Richard Smitha8eaf002012-08-23 06:16:52 +000012022 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12023
12024 // Target may not be determinable yet, for instance if this is a dependent
12025 // call in an uninstantiated template.
12026 if (Target) {
12027 const FunctionDecl *FNTarget = 0;
12028 (void)Target->hasBody(FNTarget);
12029 Target = const_cast<CXXConstructorDecl*>(
12030 cast_or_null<CXXConstructorDecl>(FNTarget));
12031 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012032
12033 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12034 // Avoid dereferencing a null pointer here.
12035 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12036
12037 if (!Current.insert(Canonical))
12038 return;
12039
12040 // We know that beyond here, we aren't chaining into a cycle.
12041 if (!Target || !Target->isDelegatingConstructor() ||
12042 Target->isInvalidDecl() || Valid.count(TCanonical)) {
12043 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12044 Valid.insert(*CI);
12045 Current.clear();
12046 // We've hit a cycle.
12047 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12048 Current.count(TCanonical)) {
12049 // If we haven't diagnosed this cycle yet, do so now.
12050 if (!Invalid.count(TCanonical)) {
12051 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012052 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012053 << Ctor;
12054
Richard Smitha8eaf002012-08-23 06:16:52 +000012055 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012056 if (TCanonical != Canonical)
12057 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12058
12059 CXXConstructorDecl *C = Target;
12060 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012061 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012062 (void)C->getTargetConstructor()->hasBody(FNTarget);
12063 assert(FNTarget && "Ctor cycle through bodiless function");
12064
Richard Smitha8eaf002012-08-23 06:16:52 +000012065 C = const_cast<CXXConstructorDecl*>(
12066 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012067 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12068 }
12069 }
12070
12071 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12072 Invalid.insert(*CI);
12073 Current.clear();
12074 } else {
12075 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12076 }
12077}
12078
12079
Sean Huntfe57eef2011-05-04 05:57:24 +000012080void Sema::CheckDelegatingCtorCycles() {
12081 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12082
Sean Huntebcbe1d2011-05-04 23:29:54 +000012083 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12084 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000012085
Douglas Gregor0129b562011-07-27 21:57:17 +000012086 for (DelegatingCtorDeclsType::iterator
12087 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012088 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012089 I != E; ++I)
12090 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012091
12092 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12093 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012094}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012095
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012096namespace {
12097 /// \brief AST visitor that finds references to the 'this' expression.
12098 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12099 Sema &S;
12100
12101 public:
12102 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12103
12104 bool VisitCXXThisExpr(CXXThisExpr *E) {
12105 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12106 << E->isImplicit();
12107 return false;
12108 }
12109 };
12110}
12111
12112bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12113 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12114 if (!TSInfo)
12115 return false;
12116
12117 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012118 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012119 if (!ProtoTL)
12120 return false;
12121
12122 // C++11 [expr.prim.general]p3:
12123 // [The expression this] shall not appear before the optional
12124 // cv-qualifier-seq and it shall not appear within the declaration of a
12125 // static member function (although its type and value category are defined
12126 // within a static member function as they are within a non-static member
12127 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012128 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012129 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012130 FindCXXThisExpr Finder(*this);
12131
12132 // If the return type came after the cv-qualifier-seq, check it now.
12133 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012134 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012135 return true;
12136
12137 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012138 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12139 return true;
12140
12141 return checkThisInStaticMemberFunctionAttributes(Method);
12142}
12143
12144bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12145 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12146 if (!TSInfo)
12147 return false;
12148
12149 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012150 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012151 if (!ProtoTL)
12152 return false;
12153
David Blaikie39e6ab42013-02-18 22:06:02 +000012154 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012155 FindCXXThisExpr Finder(*this);
12156
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012157 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012158 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012159 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012160 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012161 case EST_DynamicNone:
12162 case EST_MSAny:
12163 case EST_None:
12164 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012165
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012166 case EST_ComputedNoexcept:
12167 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12168 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012169
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012170 case EST_Dynamic:
12171 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012172 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012173 E != EEnd; ++E) {
12174 if (!Finder.TraverseType(*E))
12175 return true;
12176 }
12177 break;
12178 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012179
12180 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012181}
12182
12183bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12184 FindCXXThisExpr Finder(*this);
12185
12186 // Check attributes.
12187 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12188 A != AEnd; ++A) {
12189 // FIXME: This should be emitted by tblgen.
12190 Expr *Arg = 0;
12191 ArrayRef<Expr *> Args;
12192 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12193 Arg = G->getArg();
12194 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12195 Arg = G->getArg();
12196 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12197 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12198 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12199 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12200 else if (ExclusiveLockFunctionAttr *ELF
12201 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12202 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12203 else if (SharedLockFunctionAttr *SLF
12204 = dyn_cast<SharedLockFunctionAttr>(*A))
12205 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12206 else if (ExclusiveTrylockFunctionAttr *ETLF
12207 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12208 Arg = ETLF->getSuccessValue();
12209 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12210 } else if (SharedTrylockFunctionAttr *STLF
12211 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12212 Arg = STLF->getSuccessValue();
12213 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12214 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12215 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12216 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12217 Arg = LR->getArg();
12218 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12219 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12220 else if (ExclusiveLocksRequiredAttr *ELR
12221 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12222 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12223 else if (SharedLocksRequiredAttr *SLR
12224 = dyn_cast<SharedLocksRequiredAttr>(*A))
12225 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12226
12227 if (Arg && !Finder.TraverseStmt(Arg))
12228 return true;
12229
12230 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12231 if (!Finder.TraverseStmt(Args[I]))
12232 return true;
12233 }
12234 }
12235
12236 return false;
12237}
12238
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012239void
12240Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12241 ArrayRef<ParsedType> DynamicExceptions,
12242 ArrayRef<SourceRange> DynamicExceptionRanges,
12243 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012244 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012245 FunctionProtoType::ExtProtoInfo &EPI) {
12246 Exceptions.clear();
12247 EPI.ExceptionSpecType = EST;
12248 if (EST == EST_Dynamic) {
12249 Exceptions.reserve(DynamicExceptions.size());
12250 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12251 // FIXME: Preserve type source info.
12252 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12253
12254 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12255 collectUnexpandedParameterPacks(ET, Unexpanded);
12256 if (!Unexpanded.empty()) {
12257 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12258 UPPC_ExceptionType,
12259 Unexpanded);
12260 continue;
12261 }
12262
12263 // Check that the type is valid for an exception spec, and
12264 // drop it if not.
12265 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12266 Exceptions.push_back(ET);
12267 }
12268 EPI.NumExceptions = Exceptions.size();
12269 EPI.Exceptions = Exceptions.data();
12270 return;
12271 }
12272
12273 if (EST == EST_ComputedNoexcept) {
12274 // If an error occurred, there's no expression here.
12275 if (NoexceptExpr) {
12276 assert((NoexceptExpr->isTypeDependent() ||
12277 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12278 Context.BoolTy) &&
12279 "Parser should have made sure that the expression is boolean");
12280 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12281 EPI.ExceptionSpecType = EST_BasicNoexcept;
12282 return;
12283 }
12284
12285 if (!NoexceptExpr->isValueDependent())
12286 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012287 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012288 /*AllowFold*/ false).take();
12289 EPI.NoexceptExpr = NoexceptExpr;
12290 }
12291 return;
12292 }
12293}
12294
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012295/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12296Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12297 // Implicitly declared functions (e.g. copy constructors) are
12298 // __host__ __device__
12299 if (D->isImplicit())
12300 return CFT_HostDevice;
12301
12302 if (D->hasAttr<CUDAGlobalAttr>())
12303 return CFT_Global;
12304
12305 if (D->hasAttr<CUDADeviceAttr>()) {
12306 if (D->hasAttr<CUDAHostAttr>())
12307 return CFT_HostDevice;
12308 else
12309 return CFT_Device;
12310 }
12311
12312 return CFT_Host;
12313}
12314
12315bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12316 CUDAFunctionTarget CalleeTarget) {
12317 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12318 // Callable from the device only."
12319 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12320 return true;
12321
12322 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12323 // Callable from the host only."
12324 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12325 // Callable from the host only."
12326 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12327 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12328 return true;
12329
12330 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12331 return true;
12332
12333 return false;
12334}
John McCall76da55d2013-04-16 07:28:30 +000012335
12336/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12337///
12338MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12339 SourceLocation DeclStart,
12340 Declarator &D, Expr *BitWidth,
12341 InClassInitStyle InitStyle,
12342 AccessSpecifier AS,
12343 AttributeList *MSPropertyAttr) {
12344 IdentifierInfo *II = D.getIdentifier();
12345 if (!II) {
12346 Diag(DeclStart, diag::err_anonymous_property);
12347 return NULL;
12348 }
12349 SourceLocation Loc = D.getIdentifierLoc();
12350
12351 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12352 QualType T = TInfo->getType();
12353 if (getLangOpts().CPlusPlus) {
12354 CheckExtraCXXDefaultArguments(D);
12355
12356 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12357 UPPC_DataMemberType)) {
12358 D.setInvalidType();
12359 T = Context.IntTy;
12360 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12361 }
12362 }
12363
12364 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12365
12366 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12367 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12368 diag::err_invalid_thread)
12369 << DeclSpec::getSpecifierName(TSCS);
12370
12371 // Check to see if this name was declared as a member previously
12372 NamedDecl *PrevDecl = 0;
12373 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12374 LookupName(Previous, S);
12375 switch (Previous.getResultKind()) {
12376 case LookupResult::Found:
12377 case LookupResult::FoundUnresolvedValue:
12378 PrevDecl = Previous.getAsSingle<NamedDecl>();
12379 break;
12380
12381 case LookupResult::FoundOverloaded:
12382 PrevDecl = Previous.getRepresentativeDecl();
12383 break;
12384
12385 case LookupResult::NotFound:
12386 case LookupResult::NotFoundInCurrentInstantiation:
12387 case LookupResult::Ambiguous:
12388 break;
12389 }
12390
12391 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12392 // Maybe we will complain about the shadowed template parameter.
12393 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12394 // Just pretend that we didn't see the previous declaration.
12395 PrevDecl = 0;
12396 }
12397
12398 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12399 PrevDecl = 0;
12400
12401 SourceLocation TSSL = D.getLocStart();
12402 MSPropertyDecl *NewPD;
12403 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12404 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12405 II, T, TInfo, TSSL,
12406 Data.GetterId, Data.SetterId);
12407 ProcessDeclAttributes(TUScope, NewPD, D);
12408 NewPD->setAccess(AS);
12409
12410 if (NewPD->isInvalidDecl())
12411 Record->setInvalidDecl();
12412
12413 if (D.getDeclSpec().isModulePrivateSpecified())
12414 NewPD->setModulePrivate();
12415
12416 if (NewPD->isInvalidDecl() && PrevDecl) {
12417 // Don't introduce NewFD into scope; there's already something
12418 // with the same name in the same scope.
12419 } else if (II) {
12420 PushOnScopeChains(NewPD, S);
12421 } else
12422 Record->addDecl(NewPD);
12423
12424 return NewPD;
12425}