blob: f488296336cfc2e4b86c2899447e460ecf92ba1d [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000028#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000029#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000030#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000031#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000034#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000035#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000036#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000038#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000039#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000040
41using namespace clang;
42
Chris Lattner8123a952008-04-10 02:22:51 +000043//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
Chris Lattner9e979552008-04-12 23:52:44 +000047namespace {
48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
49 /// the default argument of a parameter to determine whether it
50 /// contains any ill-formed subexpressions. For example, this will
51 /// diagnose the use of local variables or parameters within the
52 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000053 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000054 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000055 Expr *DefaultArg;
56 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 public:
Mike Stump1eb44332009-09-09 15:08:12 +000059 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000060 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 bool VisitExpr(Expr *Node);
63 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000064 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000065 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000066 };
Chris Lattner8123a952008-04-10 02:22:51 +000067
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitExpr - Visit all of the children of this expression.
69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
70 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000071 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000072 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000073 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000074 }
75
Chris Lattner9e979552008-04-12 23:52:44 +000076 /// VisitDeclRefExpr - Visit a reference to a declaration, to
77 /// determine whether this declaration can be used in the default
78 /// argument expression.
79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000081 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
82 // C++ [dcl.fct.default]p9
83 // Default arguments are evaluated each time the function is
84 // called. The order of evaluation of function arguments is
85 // unspecified. Consequently, parameters of a function shall not
86 // be used in default argument expressions, even if they are not
87 // evaluated. Parameters of a function declared before a default
88 // argument expression are in scope and can hide namespace and
89 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000090 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000093 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000094 // C++ [dcl.fct.default]p7
95 // Local variables shall not be used in default argument
96 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000097 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000098 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000100 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102
Douglas Gregor3996f232008-11-04 13:41:56 +0000103 return false;
104 }
Chris Lattner9e979552008-04-12 23:52:44 +0000105
Douglas Gregor796da182008-11-04 14:32:21 +0000106 /// VisitCXXThisExpr - Visit a C++ "this" expression.
107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
108 // C++ [dcl.fct.default]p8:
109 // The keyword this shall not be used in a default argument of a
110 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000111 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000112 diag::err_param_default_argument_references_this)
113 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000114 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000115
116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
117 // C++11 [expr.lambda.prim]p13:
118 // A lambda-expression appearing in a default argument shall not
119 // implicitly or explicitly capture any entity.
120 if (Lambda->capture_begin() == Lambda->capture_end())
121 return false;
122
123 return S->Diag(Lambda->getLocStart(),
124 diag::err_lambda_capture_default_arg);
125 }
Chris Lattner8123a952008-04-10 02:22:51 +0000126}
127
Sean Hunt001cad92011-05-10 00:49:42 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000129 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000130 // If we have an MSAny or unknown spec already, don't bother.
131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000132 return;
133
134 const FunctionProtoType *Proto
135 = Method->getType()->getAs<FunctionProtoType>();
136
137 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
138
139 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000141 ClearExceptions();
142 ComputedEST = EST;
143 return;
144 }
145
Richard Smith7a614d82011-06-11 17:19:42 +0000146 // FIXME: If the call to this decl is using any of its default arguments, we
147 // need to search them for potentially-throwing calls.
148
Sean Hunt001cad92011-05-10 00:49:42 +0000149 // If this function has a basic noexcept, it doesn't affect the outcome.
150 if (EST == EST_BasicNoexcept)
151 return;
152
153 // If we have a throw-all spec at this point, ignore the function.
154 if (ComputedEST == EST_None)
155 return;
156
157 // If we're still at noexcept(true) and there's a nothrow() callee,
158 // change to that specification.
159 if (EST == EST_DynamicNone) {
160 if (ComputedEST == EST_BasicNoexcept)
161 ComputedEST = EST_DynamicNone;
162 return;
163 }
164
165 // Check out noexcept specs.
166 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000168 assert(NR != FunctionProtoType::NR_NoNoexcept &&
169 "Must have noexcept result for EST_ComputedNoexcept.");
170 assert(NR != FunctionProtoType::NR_Dependent &&
171 "Should not generate implicit declarations for dependent cases, "
172 "and don't know how to handle them anyway.");
173
174 // noexcept(false) -> no spec on the new function
175 if (NR == FunctionProtoType::NR_Throw) {
176 ClearExceptions();
177 ComputedEST = EST_None;
178 }
179 // noexcept(true) won't change anything either.
180 return;
181 }
182
183 assert(EST == EST_Dynamic && "EST case not considered earlier.");
184 assert(ComputedEST != EST_None &&
185 "Shouldn't collect exceptions when throw-all is guaranteed.");
186 ComputedEST = EST_Dynamic;
187 // Record the exceptions in this function's exception specification.
188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
189 EEnd = Proto->exception_end();
190 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000192 Exceptions.push_back(*E);
193}
194
Richard Smith7a614d82011-06-11 17:19:42 +0000195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
197 return;
198
199 // FIXME:
200 //
201 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000202 // [An] implicit exception-specification specifies the type-id T if and
203 // only if T is allowed by the exception-specification of a function directly
204 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000205 // function it directly invokes allows all exceptions, and f shall allow no
206 // exceptions if every function it directly invokes allows no exceptions.
207 //
208 // Note in particular that if an implicit exception-specification is generated
209 // for a function containing a throw-expression, that specification can still
210 // be noexcept(true).
211 //
212 // Note also that 'directly invoked' is not defined in the standard, and there
213 // is no indication that we should only consider potentially-evaluated calls.
214 //
215 // Ultimately we should implement the intent of the standard: the exception
216 // specification should be the set of exceptions which can be thrown by the
217 // implicit definition. For now, we assume that any non-nothrow expression can
218 // throw any exception.
219
220 if (E->CanThrow(*Context))
221 ComputedEST = EST_None;
222}
223
Anders Carlssoned961f92009-08-25 02:29:20 +0000224bool
John McCall9ae2f072010-08-23 23:25:46 +0000225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000226 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000227 if (RequireCompleteType(Param->getLocation(), Param->getType(),
228 diag::err_typecheck_decl_incomplete_type)) {
229 Param->setInvalidDecl();
230 return true;
231 }
232
Anders Carlssoned961f92009-08-25 02:29:20 +0000233 // C++ [dcl.fct.default]p5
234 // A default argument expression is implicitly converted (clause
235 // 4) to the parameter type. The default argument expression has
236 // the same semantic constraints as the initializer expression in
237 // a declaration of a variable of the parameter type, using the
238 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000245 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000246 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000247 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000249
John McCallb4eb64d2010-10-08 02:01:28 +0000250 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000251 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Anders Carlssoned961f92009-08-25 02:29:20 +0000253 // Okay: add the default argument to the parameter
254 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000256 // We have already instantiated this parameter; provide each of the
257 // instantiations with the uninstantiated default argument.
258 UnparsedDefaultArgInstantiationsMap::iterator InstPos
259 = UnparsedDefaultArgInstantiations.find(Param);
260 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
263
264 // We're done tracking this parameter's instantiations.
265 UnparsedDefaultArgInstantiations.erase(InstPos);
266 }
267
Anders Carlsson9351c172009-08-25 03:18:48 +0000268 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000269}
270
Chris Lattner8123a952008-04-10 02:22:51 +0000271/// ActOnParamDefaultArgument - Check whether the default argument
272/// provided for a function parameter is well-formed. If so, attach it
273/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274void
John McCalld226f652010-08-21 09:40:31 +0000275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000276 Expr *DefaultArg) {
277 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000278 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
John McCalld226f652010-08-21 09:40:31 +0000280 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000281 UnparsedDefaultArgLocs.erase(Param);
282
Chris Lattner3d1cee32008-04-08 05:04:30 +0000283 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000284 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 Diag(EqualLoc, diag::err_param_default_argument)
286 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000287 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 return;
289 }
290
Douglas Gregor6f526752010-12-16 08:48:57 +0000291 // Check for unexpanded parameter packs.
292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
293 Param->setInvalidDecl();
294 return;
295 }
296
Anders Carlsson66e30672009-08-25 01:02:06 +0000297 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000300 Param->setInvalidDecl();
301 return;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCall9ae2f072010-08-23 23:25:46 +0000304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000305}
306
Douglas Gregor61366e92008-12-24 00:01:03 +0000307/// ActOnParamUnparsedDefaultArgument - We've seen a default
308/// argument for a function parameter, but we can't parse it yet
309/// because we're inside a class definition. Note that this default
310/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000312 SourceLocation EqualLoc,
313 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCalld226f652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000318 if (Param)
319 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlsson5e300d12009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000322}
323
Douglas Gregor72b505b2008-12-16 21:30:33 +0000324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000327 if (!param)
328 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCalld226f652010-08-21 09:40:31 +0000330 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlsson5e300d12009-06-12 16:51:40 +0000332 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Anders Carlsson5e300d12009-06-12 16:51:40 +0000334 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000335}
336
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337/// CheckExtraCXXDefaultArguments - Check for any extra default
338/// arguments in the declarator, which is not a function declaration
339/// or definition and therefore is not permitted to have default
340/// arguments. This routine should be invoked for every declarator
341/// that is not a function declaration or definition.
342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
343 // C++ [dcl.fct.default]p3
344 // A default argument expression shall be specified only in the
345 // parameter-declaration-clause of a function declaration or in a
346 // template-parameter (14.1). It shall not be specified for a
347 // parameter pack. If it is specified in a
348 // parameter-declaration-clause, it shall not occur within a
349 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000351 DeclaratorChunk &chunk = D.getTypeObject(i);
352 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000356 if (Param->hasUnparsedDefaultArg()) {
357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
360 delete Toks;
361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000362 } else if (Param->getDefaultArg()) {
363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << Param->getDefaultArg()->getSourceRange();
365 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000366 }
367 }
368 }
369 }
370}
371
Chris Lattner3d1cee32008-04-08 05:04:30 +0000372// MergeCXXFunctionDecl - Merge two declarations of the same C++
373// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000374// type. Subroutine of MergeFunctionDecl. Returns true if there was an
375// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
377 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000378 bool Invalid = false;
379
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000381 // For non-template functions, default arguments can be added in
382 // later declarations of a function in the same
383 // scope. Declarations in different scopes have completely
384 // distinct sets of default arguments. That is, declarations in
385 // inner scopes do not acquire default arguments from
386 // declarations in outer scopes, and vice versa. In a given
387 // function declaration, all parameters subsequent to a
388 // parameter with a default argument shall have default
389 // arguments supplied in this or previous declarations. A
390 // default argument shall not be redefined by a later
391 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000392 //
393 // C++ [dcl.fct.default]p6:
394 // Except for member functions of class templates, the default arguments
395 // in a member function definition that appears outside of the class
396 // definition are added to the set of default arguments provided by the
397 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
399 ParmVarDecl *OldParam = Old->getParamDecl(p);
400 ParmVarDecl *NewParam = New->getParamDecl(p);
401
James Molloy9cda03f2012-03-13 08:55:35 +0000402 bool OldParamHasDfl = OldParam->hasDefaultArg();
403 bool NewParamHasDfl = NewParam->hasDefaultArg();
404
405 NamedDecl *ND = Old;
406 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
407 // Ignore default parameters of old decl if they are not in
408 // the same scope.
409 OldParamHasDfl = false;
410
411 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000412
Francois Pichet8d051e02011-04-10 03:03:52 +0000413 unsigned DiagDefaultParamID =
414 diag::err_param_default_argument_redefinition;
415
416 // MSVC accepts that default parameters be redefined for member functions
417 // of template class. The new default parameter's value is ignored.
418 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000419 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000420 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
421 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000422 // Merge the old default argument into the new parameter.
423 NewParam->setHasInheritedDefaultArg();
424 if (OldParam->hasUninstantiatedDefaultArg())
425 NewParam->setUninstantiatedDefaultArg(
426 OldParam->getUninstantiatedDefaultArg());
427 else
428 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000429 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000430 Invalid = false;
431 }
432 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000433
Francois Pichet8cf90492011-04-10 04:58:30 +0000434 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
435 // hint here. Alternatively, we could walk the type-source information
436 // for NewParam to find the last source location in the type... but it
437 // isn't worth the effort right now. This is the kind of test case that
438 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000439 // int f(int);
440 // void g(int (*fp)(int) = f);
441 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000442 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444
445 // Look for the function declaration where the default argument was
446 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000447 for (FunctionDecl *Older = Old->getPreviousDecl();
448 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449 if (!Older->getParamDecl(p)->hasDefaultArg())
450 break;
451
452 OldParam = Older->getParamDecl(p);
453 }
454
455 Diag(OldParam->getLocation(), diag::note_previous_definition)
456 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000457 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000458 // Merge the old default argument into the new parameter.
459 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000460 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000461 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000462 if (OldParam->hasUninstantiatedDefaultArg())
463 NewParam->setUninstantiatedDefaultArg(
464 OldParam->getUninstantiatedDefaultArg());
465 else
John McCall3d6c1782010-05-04 01:53:42 +0000466 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000467 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000468 if (New->getDescribedFunctionTemplate()) {
469 // Paragraph 4, quoted above, only applies to non-template functions.
470 Diag(NewParam->getLocation(),
471 diag::err_param_default_argument_template_redecl)
472 << NewParam->getDefaultArgRange();
473 Diag(Old->getLocation(), diag::note_template_prev_declaration)
474 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000475 } else if (New->getTemplateSpecializationKind()
476 != TSK_ImplicitInstantiation &&
477 New->getTemplateSpecializationKind() != TSK_Undeclared) {
478 // C++ [temp.expr.spec]p21:
479 // Default function arguments shall not be specified in a declaration
480 // or a definition for one of the following explicit specializations:
481 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000482 // - the explicit specialization of a member function template;
483 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000484 // template where the class template specialization to which the
485 // member function specialization belongs is implicitly
486 // instantiated.
487 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
488 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
489 << New->getDeclName()
490 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000491 } else if (New->getDeclContext()->isDependentContext()) {
492 // C++ [dcl.fct.default]p6 (DR217):
493 // Default arguments for a member function of a class template shall
494 // be specified on the initial declaration of the member function
495 // within the class template.
496 //
497 // Reading the tea leaves a bit in DR217 and its reference to DR205
498 // leads me to the conclusion that one cannot add default function
499 // arguments for an out-of-line definition of a member function of a
500 // dependent type.
501 int WhichKind = 2;
502 if (CXXRecordDecl *Record
503 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
504 if (Record->getDescribedClassTemplate())
505 WhichKind = 0;
506 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
507 WhichKind = 1;
508 else
509 WhichKind = 2;
510 }
511
512 Diag(NewParam->getLocation(),
513 diag::err_param_default_argument_member_template_redecl)
514 << WhichKind
515 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000516 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
517 CXXSpecialMember NewSM = getSpecialMember(Ctor),
518 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
519 if (NewSM != OldSM) {
520 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
521 << NewParam->getDefaultArgRange() << NewSM;
522 Diag(Old->getLocation(), diag::note_previous_declaration_special)
523 << OldSM;
524 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000525 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000526 }
527 }
528
Richard Smithff234882012-02-20 23:28:05 +0000529 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000530 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000531 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000532 if (New->isConstexpr() != Old->isConstexpr()) {
533 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
534 << New << New->isConstexpr();
535 Diag(Old->getLocation(), diag::note_previous_declaration);
536 Invalid = true;
537 }
538
Douglas Gregore13ad832010-02-12 07:32:17 +0000539 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000540 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000541
Douglas Gregorcda9c672009-02-16 17:45:42 +0000542 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000543}
544
Sebastian Redl60618fa2011-03-12 11:50:43 +0000545/// \brief Merge the exception specifications of two variable declarations.
546///
547/// This is called when there's a redeclaration of a VarDecl. The function
548/// checks if the redeclaration might have an exception specification and
549/// validates compatibility and merges the specs if necessary.
550void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
551 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000552 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000553 return;
554
555 assert(Context.hasSameType(New->getType(), Old->getType()) &&
556 "Should only be called if types are otherwise the same.");
557
558 QualType NewType = New->getType();
559 QualType OldType = Old->getType();
560
561 // We're only interested in pointers and references to functions, as well
562 // as pointers to member functions.
563 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
564 NewType = R->getPointeeType();
565 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
566 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
567 NewType = P->getPointeeType();
568 OldType = OldType->getAs<PointerType>()->getPointeeType();
569 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
570 NewType = M->getPointeeType();
571 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
572 }
573
574 if (!NewType->isFunctionProtoType())
575 return;
576
577 // There's lots of special cases for functions. For function pointers, system
578 // libraries are hopefully not as broken so that we don't need these
579 // workarounds.
580 if (CheckEquivalentExceptionSpec(
581 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
582 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
583 New->setInvalidDecl();
584 }
585}
586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587/// CheckCXXDefaultArguments - Verify that the default arguments for a
588/// function declaration are well-formed according to C++
589/// [dcl.fct.default].
590void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
591 unsigned NumParams = FD->getNumParams();
592 unsigned p;
593
Douglas Gregorc6889e72012-02-14 22:28:59 +0000594 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
595 isa<CXXMethodDecl>(FD) &&
596 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
597
Chris Lattner3d1cee32008-04-08 05:04:30 +0000598 // Find first parameter with a default argument
599 for (p = 0; p < NumParams; ++p) {
600 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000601 if (Param->hasDefaultArg()) {
602 // C++11 [expr.prim.lambda]p5:
603 // [...] Default arguments (8.3.6) shall not be specified in the
604 // parameter-declaration-clause of a lambda-declarator.
605 //
606 // FIXME: Core issue 974 strikes this sentence, we only provide an
607 // extension warning.
608 if (IsLambda)
609 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
610 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000611 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000612 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000613 }
614
615 // C++ [dcl.fct.default]p4:
616 // In a given function declaration, all parameters
617 // subsequent to a parameter with a default argument shall
618 // have default arguments supplied in this or previous
619 // declarations. A default argument shall not be redefined
620 // by a later declaration (not even to the same value).
621 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000622 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000624 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000625 if (Param->isInvalidDecl())
626 /* We already complained about this parameter. */;
627 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000628 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000629 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000630 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000631 else
Mike Stump1eb44332009-09-09 15:08:12 +0000632 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000633 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 LastMissingDefaultArg = p;
636 }
637 }
638
639 if (LastMissingDefaultArg > 0) {
640 // Some default arguments were missing. Clear out all of the
641 // default arguments up to (and including) the last missing
642 // default argument, so that we leave the function parameters
643 // in a semantically valid state.
644 for (p = 0; p <= LastMissingDefaultArg; ++p) {
645 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000646 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 Param->setDefaultArg(0);
648 }
649 }
650 }
651}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000652
Richard Smith9f569cc2011-10-01 02:31:28 +0000653// CheckConstexprParameterTypes - Check whether a function's parameter types
654// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000655// diagnostic and return false.
656static bool CheckConstexprParameterTypes(Sema &SemaRef,
657 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000658 unsigned ArgIndex = 0;
659 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
660 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
661 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
662 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
663 SourceLocation ParamLoc = PD->getLocation();
664 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000665 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smith9f569cc2011-10-01 02:31:28 +0000666 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
667 << ArgIndex+1 << PD->getSourceRange()
Richard Smith86c3ae42012-02-13 03:54:03 +0000668 << isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000669 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 }
671 return true;
672}
673
674// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000675// the requirements of a constexpr function definition or a constexpr
676// constructor definition. If so, return true. If not, produce appropriate
677// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000678//
Richard Smith86c3ae42012-02-13 03:54:03 +0000679// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
680bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000681 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
682 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000683 // C++11 [dcl.constexpr]p4:
684 // The definition of a constexpr constructor shall satisfy the following
685 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000687 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000688 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000689 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
690 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
691 << RD->getNumVBases();
692 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
693 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000694 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000695 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000696 return false;
697 }
Richard Smith35340502012-01-13 04:54:00 +0000698 }
699
700 if (!isa<CXXConstructorDecl>(NewFD)) {
701 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000702 // The definition of a constexpr function shall satisfy the following
703 // constraints:
704 // - it shall not be virtual;
705 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
706 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000707 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000708
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // If it's not obvious why this function is virtual, find an overridden
710 // function which uses the 'virtual' keyword.
711 const CXXMethodDecl *WrittenVirtual = Method;
712 while (!WrittenVirtual->isVirtualAsWritten())
713 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
714 if (WrittenVirtual != Method)
715 Diag(WrittenVirtual->getLocation(),
716 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000717 return false;
718 }
719
720 // - its return type shall be a literal type;
721 QualType RT = NewFD->getResultType();
722 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000723 RequireLiteralType(NewFD->getLocation(), RT,
724 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 }
727
Richard Smith35340502012-01-13 04:54:00 +0000728 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000729 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000730 return false;
731
Richard Smith9f569cc2011-10-01 02:31:28 +0000732 return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740 DeclStmt *DS) {
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
743 // contain only
744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746 switch ((*DclIt)->getKind()) {
747 case Decl::StaticAssert:
748 case Decl::Using:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
755 continue;
756
757 case Decl::Typedef:
758 case Decl::TypeAlias: {
759 // - typedef declarations and alias-declarations that do not define
760 // classes or enumerations,
761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763 // Don't allow variably-modified types in constexpr functions.
764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766 << TL.getSourceRange() << TL.getType()
767 << isa<CXXConstructorDecl>(Dcl);
768 return false;
769 }
770 continue;
771 }
772
773 case Decl::Enum:
774 case Decl::CXXRecord:
775 // As an extension, we allow the declaration (but not the definition) of
776 // classes and enumerations in all declarations, not just in typedef and
777 // alias declarations.
778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780 << isa<CXXConstructorDecl>(Dcl);
781 return false;
782 }
783 continue;
784
785 case Decl::Var:
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789
790 default:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 }
796
797 return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804/// struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806/// indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
810 FieldDecl *Field,
811 llvm::SmallSet<Decl*, 16> &Inits,
812 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000813 if (Field->isUnnamedBitfield())
814 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000815
816 if (Field->isAnonymousStructOrUnion() &&
817 Field->getType()->getAsCXXRecordDecl()->isEmpty())
818 return;
819
Richard Smith9f569cc2011-10-01 02:31:28 +0000820 if (!Inits.count(Field)) {
821 if (!Diagnosed) {
822 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
823 Diagnosed = true;
824 }
825 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
826 } else if (Field->isAnonymousStructOrUnion()) {
827 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
828 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
829 I != E; ++I)
830 // If an anonymous union contains an anonymous struct of which any member
831 // is initialized, all members must be initialized.
832 if (!RD->isUnion() || Inits.count(*I))
833 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
834 }
835}
836
837/// Check the body for the given constexpr function declaration only contains
838/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
839///
840/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000841bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000842 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000843 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000844 // The definition of a constexpr function shall satisfy the following
845 // constraints: [...]
846 // - its function-body shall be = delete, = default, or a
847 // compound-statement
848 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000849 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000850 // In the definition of a constexpr constructor, [...]
851 // - its function-body shall not be a function-try-block;
852 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
853 << isa<CXXConstructorDecl>(Dcl);
854 return false;
855 }
856
857 // - its function-body shall be [...] a compound-statement that contains only
858 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
859
860 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
861 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
862 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
863 switch ((*BodyIt)->getStmtClass()) {
864 case Stmt::NullStmtClass:
865 // - null statements,
866 continue;
867
868 case Stmt::DeclStmtClass:
869 // - static_assert-declarations
870 // - using-declarations,
871 // - using-directives,
872 // - typedef declarations and alias-declarations that do not define
873 // classes or enumerations,
874 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
875 return false;
876 continue;
877
878 case Stmt::ReturnStmtClass:
879 // - and exactly one return statement;
880 if (isa<CXXConstructorDecl>(Dcl))
881 break;
882
883 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000884 continue;
885
886 default:
887 break;
888 }
889
890 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894
895 if (const CXXConstructorDecl *Constructor
896 = dyn_cast<CXXConstructorDecl>(Dcl)) {
897 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000898 // DR1359:
899 // - every non-variant non-static data member and base class sub-object
900 // shall be initialized;
901 // - if the class is a non-empty union, or for each non-empty anonymous
902 // union member of a non-union class, exactly one non-static data member
903 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000904 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000905 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000906 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
907 return false;
908 }
Richard Smith6e433752011-10-10 16:38:04 +0000909 } else if (!Constructor->isDependentContext() &&
910 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000911 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
912
913 // Skip detailed checking if we have enough initializers, and we would
914 // allow at most one initializer per member.
915 bool AnyAnonStructUnionMembers = false;
916 unsigned Fields = 0;
917 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
918 E = RD->field_end(); I != E; ++I, ++Fields) {
919 if ((*I)->isAnonymousStructOrUnion()) {
920 AnyAnonStructUnionMembers = true;
921 break;
922 }
923 }
924 if (AnyAnonStructUnionMembers ||
925 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
926 // Check initialization of non-static data members. Base classes are
927 // always initialized so do not need to be checked. Dependent bases
928 // might not have initializers in the member initializer list.
929 llvm::SmallSet<Decl*, 16> Inits;
930 for (CXXConstructorDecl::init_const_iterator
931 I = Constructor->init_begin(), E = Constructor->init_end();
932 I != E; ++I) {
933 if (FieldDecl *FD = (*I)->getMember())
934 Inits.insert(FD);
935 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
936 Inits.insert(ID->chain_begin(), ID->chain_end());
937 }
938
939 bool Diagnosed = false;
940 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941 E = RD->field_end(); I != E; ++I)
942 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
943 if (Diagnosed)
944 return false;
945 }
946 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 } else {
948 if (ReturnStmts.empty()) {
949 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
950 return false;
951 }
952 if (ReturnStmts.size() > 1) {
953 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
954 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
955 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
956 return false;
957 }
958 }
959
Richard Smith5ba73e12012-02-04 00:33:54 +0000960 // C++11 [dcl.constexpr]p5:
961 // if no function argument values exist such that the function invocation
962 // substitution would produce a constant expression, the program is
963 // ill-formed; no diagnostic required.
964 // C++11 [dcl.constexpr]p3:
965 // - every constructor call and implicit conversion used in initializing the
966 // return value shall be one of those allowed in a constant expression.
967 // C++11 [dcl.constexpr]p4:
968 // - every constructor involved in initializing non-static data members and
969 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000970 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000971 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000972 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
973 << isa<CXXConstructorDecl>(Dcl);
974 for (size_t I = 0, N = Diags.size(); I != N; ++I)
975 Diag(Diags[I].first, Diags[I].second);
976 return false;
977 }
978
Richard Smith9f569cc2011-10-01 02:31:28 +0000979 return true;
980}
981
Douglas Gregorb48fe382008-10-31 09:07:45 +0000982/// isCurrentClassName - Determine whether the identifier II is the
983/// name of the class type currently being defined. In the case of
984/// nested classes, this will only return true if II is the name of
985/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000986bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
987 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000988 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000989
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000990 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000991 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000992 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000993 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
994 } else
995 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
996
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000997 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000998 return &II == CurDecl->getIdentifier();
999 else
1000 return false;
1001}
1002
Mike Stump1eb44332009-09-09 15:08:12 +00001003/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001004///
1005/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1006/// and returns NULL otherwise.
1007CXXBaseSpecifier *
1008Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1009 SourceRange SpecifierRange,
1010 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001011 TypeSourceInfo *TInfo,
1012 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001013 QualType BaseType = TInfo->getType();
1014
Douglas Gregor2943aed2009-03-03 04:44:36 +00001015 // C++ [class.union]p1:
1016 // A union shall not have base classes.
1017 if (Class->isUnion()) {
1018 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1019 << SpecifierRange;
1020 return 0;
1021 }
1022
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001023 if (EllipsisLoc.isValid() &&
1024 !TInfo->getType()->containsUnexpandedParameterPack()) {
1025 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1026 << TInfo->getTypeLoc().getSourceRange();
1027 EllipsisLoc = SourceLocation();
1028 }
1029
Douglas Gregor2943aed2009-03-03 04:44:36 +00001030 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001031 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001032 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001033 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001034
1035 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001036
1037 // Base specifiers must be record types.
1038 if (!BaseType->isRecordType()) {
1039 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1040 return 0;
1041 }
1042
1043 // C++ [class.union]p1:
1044 // A union shall not be used as a base class.
1045 if (BaseType->isUnionType()) {
1046 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1047 return 0;
1048 }
1049
1050 // C++ [class.derived]p2:
1051 // The class-name in a base-specifier shall not be an incompletely
1052 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001053 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001054 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001055 << SpecifierRange)) {
1056 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001057 return 0;
John McCall572fc622010-08-17 07:23:57 +00001058 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001059
Eli Friedman1d954f62009-08-15 21:55:26 +00001060 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001063 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001064 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001065 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1066 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001067
Anders Carlsson1d209272011-03-25 14:55:14 +00001068 // C++ [class]p3:
1069 // If a class is marked final and it appears as a base-type-specifier in
1070 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001071 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001072 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1073 << CXXBaseDecl->getDeclName();
1074 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1075 << CXXBaseDecl->getDeclName();
1076 return 0;
1077 }
1078
John McCall572fc622010-08-17 07:23:57 +00001079 if (BaseDecl->isInvalidDecl())
1080 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001081
1082 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001083 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001084 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001086}
1087
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001088/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1089/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001090/// example:
1091/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001092/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001093BaseResult
John McCalld226f652010-08-21 09:40:31 +00001094Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001095 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001096 ParsedType basetype, SourceLocation BaseLoc,
1097 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001098 if (!classdecl)
1099 return true;
1100
Douglas Gregor40808ce2009-03-09 23:48:35 +00001101 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001102 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001103 if (!Class)
1104 return true;
1105
Nick Lewycky56062202010-07-26 16:56:01 +00001106 TypeSourceInfo *TInfo = 0;
1107 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001108
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001109 if (EllipsisLoc.isInvalid() &&
1110 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001111 UPPC_BaseType))
1112 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113
Douglas Gregor2943aed2009-03-03 04:44:36 +00001114 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 Virtual, Access, TInfo,
1116 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Douglas Gregor2943aed2009-03-03 04:44:36 +00001119 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001120}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001121
Douglas Gregor2943aed2009-03-03 04:44:36 +00001122/// \brief Performs the actual work of attaching the given base class
1123/// specifiers to a C++ class.
1124bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1125 unsigned NumBases) {
1126 if (NumBases == 0)
1127 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001128
1129 // Used to keep track of which base types we have already seen, so
1130 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001131 // that the key is always the unqualified canonical type of the base
1132 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001133 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1134
1135 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001136 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001138 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001139 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001141 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001142
1143 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1144 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001145 // C++ [class.mi]p3:
1146 // A class shall not be specified as a direct base class of a
1147 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001148 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001149 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001150 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001152
1153 // Delete the duplicate base class specifier; we're going to
1154 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001155 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156
1157 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001158 } else {
1159 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001160 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001162 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001163 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1164 if (RD->hasAttr<WeakAttr>())
1165 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001166 }
1167 }
1168
1169 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001170 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001171
1172 // Delete the remaining (good) base class specifiers, since their
1173 // data has been copied into the CXXRecordDecl.
1174 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001175 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001176
1177 return Invalid;
1178}
1179
1180/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1181/// class, after checking whether there are any duplicate base
1182/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001183void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001184 unsigned NumBases) {
1185 if (!ClassDecl || !Bases || !NumBases)
1186 return;
1187
1188 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001189 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001190 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001191}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001192
John McCall3cb0ebd2010-03-10 03:28:59 +00001193static CXXRecordDecl *GetClassForType(QualType T) {
1194 if (const RecordType *RT = T->getAs<RecordType>())
1195 return cast<CXXRecordDecl>(RT->getDecl());
1196 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1197 return ICT->getDecl();
1198 else
1199 return 0;
1200}
1201
Douglas Gregora8f32e02009-10-06 17:59:45 +00001202/// \brief Determine whether the type \p Derived is a C++ class that is
1203/// derived from the type \p Base.
1204bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001205 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001206 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001207
1208 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1209 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001210 return false;
1211
John McCall3cb0ebd2010-03-10 03:28:59 +00001212 CXXRecordDecl *BaseRD = GetClassForType(Base);
1213 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001214 return false;
1215
John McCall86ff3082010-02-04 22:26:26 +00001216 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1217 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218}
1219
1220/// \brief Determine whether the type \p Derived is a C++ class that is
1221/// derived from the type \p Base.
1222bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001223 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001224 return false;
1225
John McCall3cb0ebd2010-03-10 03:28:59 +00001226 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1227 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001228 return false;
1229
John McCall3cb0ebd2010-03-10 03:28:59 +00001230 CXXRecordDecl *BaseRD = GetClassForType(Base);
1231 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001232 return false;
1233
Douglas Gregora8f32e02009-10-06 17:59:45 +00001234 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1235}
1236
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001237void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001238 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001239 assert(BasePathArray.empty() && "Base path array must be empty!");
1240 assert(Paths.isRecordingPaths() && "Must record paths!");
1241
1242 const CXXBasePath &Path = Paths.front();
1243
1244 // We first go backward and check if we have a virtual base.
1245 // FIXME: It would be better if CXXBasePath had the base specifier for
1246 // the nearest virtual base.
1247 unsigned Start = 0;
1248 for (unsigned I = Path.size(); I != 0; --I) {
1249 if (Path[I - 1].Base->isVirtual()) {
1250 Start = I - 1;
1251 break;
1252 }
1253 }
1254
1255 // Now add all bases.
1256 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001257 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001258}
1259
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001260/// \brief Determine whether the given base path includes a virtual
1261/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001262bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1263 for (CXXCastPath::const_iterator B = BasePath.begin(),
1264 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001265 B != BEnd; ++B)
1266 if ((*B)->isVirtual())
1267 return true;
1268
1269 return false;
1270}
1271
Douglas Gregora8f32e02009-10-06 17:59:45 +00001272/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1273/// conversion (where Derived and Base are class types) is
1274/// well-formed, meaning that the conversion is unambiguous (and
1275/// that all of the base classes are accessible). Returns true
1276/// and emits a diagnostic if the code is ill-formed, returns false
1277/// otherwise. Loc is the location where this routine should point to
1278/// if there is an error, and Range is the source range to highlight
1279/// if there is an error.
1280bool
1281Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001282 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001283 unsigned AmbigiousBaseConvID,
1284 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001285 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001286 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001287 // First, determine whether the path from Derived to Base is
1288 // ambiguous. This is slightly more expensive than checking whether
1289 // the Derived to Base conversion exists, because here we need to
1290 // explore multiple paths to determine if there is an ambiguity.
1291 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1292 /*DetectVirtual=*/false);
1293 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1294 assert(DerivationOkay &&
1295 "Can only be used with a derived-to-base conversion");
1296 (void)DerivationOkay;
1297
1298 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001299 if (InaccessibleBaseID) {
1300 // Check that the base class can be accessed.
1301 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1302 InaccessibleBaseID)) {
1303 case AR_inaccessible:
1304 return true;
1305 case AR_accessible:
1306 case AR_dependent:
1307 case AR_delayed:
1308 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001309 }
John McCall6b2accb2010-02-10 09:31:12 +00001310 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001311
1312 // Build a base path if necessary.
1313 if (BasePath)
1314 BuildBasePathArray(Paths, *BasePath);
1315 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001316 }
1317
1318 // We know that the derived-to-base conversion is ambiguous, and
1319 // we're going to produce a diagnostic. Perform the derived-to-base
1320 // search just one more time to compute all of the possible paths so
1321 // that we can print them out. This is more expensive than any of
1322 // the previous derived-to-base checks we've done, but at this point
1323 // performance isn't as much of an issue.
1324 Paths.clear();
1325 Paths.setRecordingPaths(true);
1326 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1327 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1328 (void)StillOkay;
1329
1330 // Build up a textual representation of the ambiguous paths, e.g.,
1331 // D -> B -> A, that will be used to illustrate the ambiguous
1332 // conversions in the diagnostic. We only print one of the paths
1333 // to each base class subobject.
1334 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1335
1336 Diag(Loc, AmbigiousBaseConvID)
1337 << Derived << Base << PathDisplayStr << Range << Name;
1338 return true;
1339}
1340
1341bool
1342Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001343 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001344 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001345 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001346 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001347 IgnoreAccess ? 0
1348 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001350 Loc, Range, DeclarationName(),
1351 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352}
1353
1354
1355/// @brief Builds a string representing ambiguous paths from a
1356/// specific derived class to different subobjects of the same base
1357/// class.
1358///
1359/// This function builds a string that can be used in error messages
1360/// to show the different paths that one can take through the
1361/// inheritance hierarchy to go from the derived class to different
1362/// subobjects of a base class. The result looks something like this:
1363/// @code
1364/// struct D -> struct B -> struct A
1365/// struct D -> struct C -> struct A
1366/// @endcode
1367std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1368 std::string PathDisplayStr;
1369 std::set<unsigned> DisplayedPaths;
1370 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1371 Path != Paths.end(); ++Path) {
1372 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1373 // We haven't displayed a path to this particular base
1374 // class subobject yet.
1375 PathDisplayStr += "\n ";
1376 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1377 for (CXXBasePath::const_iterator Element = Path->begin();
1378 Element != Path->end(); ++Element)
1379 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1380 }
1381 }
1382
1383 return PathDisplayStr;
1384}
1385
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001386//===----------------------------------------------------------------------===//
1387// C++ class member Handling
1388//===----------------------------------------------------------------------===//
1389
Abramo Bagnara6206d532010-06-05 05:09:32 +00001390/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001391bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1392 SourceLocation ASLoc,
1393 SourceLocation ColonLoc,
1394 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001395 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001396 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001397 ASLoc, ColonLoc);
1398 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001399 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400}
1401
Anders Carlsson9e682d92011-01-20 05:57:14 +00001402/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001403void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001404 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001405 if (!MD || !MD->isVirtual())
1406 return;
1407
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001408 if (MD->isDependentContext())
1409 return;
1410
Anders Carlsson9e682d92011-01-20 05:57:14 +00001411 // C++0x [class.virtual]p3:
1412 // If a virtual function is marked with the virt-specifier override and does
1413 // not override a member function of a base class,
1414 // the program is ill-formed.
1415 bool HasOverriddenMethods =
1416 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001417 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001418 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001419 diag::err_function_marked_override_not_overriding)
1420 << MD->getDeclName();
1421 return;
1422 }
1423}
1424
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001425/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1426/// function overrides a virtual member function marked 'final', according to
1427/// C++0x [class.virtual]p3.
1428bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1429 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001430 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001431 return false;
1432
1433 Diag(New->getLocation(), diag::err_final_function_overridden)
1434 << New->getDeclName();
1435 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1436 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001437}
1438
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001439/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1440/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001441/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1442/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1443/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001444Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001445Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001446 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001447 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001448 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001449 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001450 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1451 DeclarationName Name = NameInfo.getName();
1452 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001453
1454 // For anonymous bitfields, the location should point to the type.
1455 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001456 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001457
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001458 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459
John McCall4bde1e12010-06-04 08:34:12 +00001460 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001461 assert(!DS.isFriendSpecified());
1462
Richard Smith1ab0d902011-06-25 02:28:38 +00001463 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001464
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001465 // C++ 9.2p6: A member shall not be declared to have automatic storage
1466 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001467 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1468 // data members and cannot be applied to names declared const or static,
1469 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001470 switch (DS.getStorageClassSpec()) {
1471 case DeclSpec::SCS_unspecified:
1472 case DeclSpec::SCS_typedef:
1473 case DeclSpec::SCS_static:
1474 // FALL THROUGH.
1475 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001476 case DeclSpec::SCS_mutable:
1477 if (isFunc) {
1478 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001479 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001480 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001481 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Sebastian Redla11f42f2008-11-17 23:24:37 +00001483 // FIXME: It would be nicer if the keyword was ignored only for this
1484 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001485 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001486 }
1487 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001488 default:
1489 if (DS.getStorageClassSpecLoc().isValid())
1490 Diag(DS.getStorageClassSpecLoc(),
1491 diag::err_storageclass_invalid_for_member);
1492 else
1493 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1494 D.getMutableDeclSpec().ClearStorageClassSpecs();
1495 }
1496
Sebastian Redl669d5d72008-11-14 23:42:31 +00001497 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1498 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001499 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001500
1501 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001502 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001503 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001504
1505 // Data members must have identifiers for names.
1506 if (Name.getNameKind() != DeclarationName::Identifier) {
1507 Diag(Loc, diag::err_bad_variable_name)
1508 << Name;
1509 return 0;
1510 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001511
Douglas Gregorf2503652011-09-21 14:40:46 +00001512 IdentifierInfo *II = Name.getAsIdentifierInfo();
1513
1514 // Member field could not be with "template" keyword.
1515 // So TemplateParameterLists should be empty in this case.
1516 if (TemplateParameterLists.size()) {
1517 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1518 if (TemplateParams->size()) {
1519 // There is no such thing as a member field template.
1520 Diag(D.getIdentifierLoc(), diag::err_template_member)
1521 << II
1522 << SourceRange(TemplateParams->getTemplateLoc(),
1523 TemplateParams->getRAngleLoc());
1524 } else {
1525 // There is an extraneous 'template<>' for this member.
1526 Diag(TemplateParams->getTemplateLoc(),
1527 diag::err_template_member_noparams)
1528 << II
1529 << SourceRange(TemplateParams->getTemplateLoc(),
1530 TemplateParams->getRAngleLoc());
1531 }
1532 return 0;
1533 }
1534
Douglas Gregor922fff22010-10-13 22:19:53 +00001535 if (SS.isSet() && !SS.isInvalid()) {
1536 // The user provided a superfluous scope specifier inside a class
1537 // definition:
1538 //
1539 // class X {
1540 // int X::member;
1541 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001542 if (DeclContext *DC = computeDeclContext(SS, false))
1543 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001544 else
1545 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1546 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001547
Douglas Gregor922fff22010-10-13 22:19:53 +00001548 SS.clear();
1549 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001550
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001551 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001552 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001553 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001554 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001555 assert(!HasDeferredInit);
1556
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001557 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001558 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001559 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001560 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001561
1562 // Non-instance-fields can't have a bitfield.
1563 if (BitWidth) {
1564 if (Member->isInvalidDecl()) {
1565 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001566 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001567 // C++ 9.6p3: A bit-field shall not be a static member.
1568 // "static member 'A' cannot be a bit-field"
1569 Diag(Loc, diag::err_static_not_bitfield)
1570 << Name << BitWidth->getSourceRange();
1571 } else if (isa<TypedefDecl>(Member)) {
1572 // "typedef member 'x' cannot be a bit-field"
1573 Diag(Loc, diag::err_typedef_not_bitfield)
1574 << Name << BitWidth->getSourceRange();
1575 } else {
1576 // A function typedef ("typedef int f(); f a;").
1577 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1578 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001579 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001580 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattner8b963ef2009-03-05 23:01:03 +00001583 BitWidth = 0;
1584 Member->setInvalidDecl();
1585 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001586
1587 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Douglas Gregor37b372b2009-08-20 22:52:58 +00001589 // If we have declared a member function template, set the access of the
1590 // templated declaration as well.
1591 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1592 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001593 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001594
Anders Carlssonaae5af22011-01-20 04:34:22 +00001595 if (VS.isOverrideSpecified()) {
1596 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1597 if (!MD || !MD->isVirtual()) {
1598 Diag(Member->getLocStart(),
1599 diag::override_keyword_only_allowed_on_virtual_member_functions)
1600 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001601 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001602 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001603 }
1604 if (VS.isFinalSpecified()) {
1605 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1606 if (!MD || !MD->isVirtual()) {
1607 Diag(Member->getLocStart(),
1608 diag::override_keyword_only_allowed_on_virtual_member_functions)
1609 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001610 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001611 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001612 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001613
Douglas Gregorf5251602011-03-08 17:10:18 +00001614 if (VS.getLastLocation().isValid()) {
1615 // Update the end location of a method that has a virt-specifiers.
1616 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1617 MD->setRangeEnd(VS.getLastLocation());
1618 }
1619
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001620 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001621
Douglas Gregor10bd3682008-11-17 22:58:34 +00001622 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001623
John McCallb25b2952011-02-15 07:12:36 +00001624 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001625 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001626 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001627}
1628
Richard Smith7a614d82011-06-11 17:19:42 +00001629/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001630/// in-class initializer for a non-static C++ class member, and after
1631/// instantiating an in-class initializer in a class template. Such actions
1632/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001633void
1634Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1635 Expr *InitExpr) {
1636 FieldDecl *FD = cast<FieldDecl>(D);
1637
1638 if (!InitExpr) {
1639 FD->setInvalidDecl();
1640 FD->removeInClassInitializer();
1641 return;
1642 }
1643
Peter Collingbournefef21892011-10-23 18:59:44 +00001644 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1645 FD->setInvalidDecl();
1646 FD->removeInClassInitializer();
1647 return;
1648 }
1649
Richard Smith7a614d82011-06-11 17:19:42 +00001650 ExprResult Init = InitExpr;
1651 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001652 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001653 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001654 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1655 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001656 Expr **Inits = &InitExpr;
1657 unsigned NumInits = 1;
1658 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1659 InitializationKind Kind = EqualLoc.isInvalid()
1660 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1661 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1662 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1663 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001664 if (Init.isInvalid()) {
1665 FD->setInvalidDecl();
1666 return;
1667 }
1668
1669 CheckImplicitConversions(Init.get(), EqualLoc);
1670 }
1671
1672 // C++0x [class.base.init]p7:
1673 // The initialization of each base and member constitutes a
1674 // full-expression.
1675 Init = MaybeCreateExprWithCleanups(Init);
1676 if (Init.isInvalid()) {
1677 FD->setInvalidDecl();
1678 return;
1679 }
1680
1681 InitExpr = Init.release();
1682
1683 FD->setInClassInitializer(InitExpr);
1684}
1685
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001686/// \brief Find the direct and/or virtual base specifiers that
1687/// correspond to the given base type, for use in base initialization
1688/// within a constructor.
1689static bool FindBaseInitializer(Sema &SemaRef,
1690 CXXRecordDecl *ClassDecl,
1691 QualType BaseType,
1692 const CXXBaseSpecifier *&DirectBaseSpec,
1693 const CXXBaseSpecifier *&VirtualBaseSpec) {
1694 // First, check for a direct base class.
1695 DirectBaseSpec = 0;
1696 for (CXXRecordDecl::base_class_const_iterator Base
1697 = ClassDecl->bases_begin();
1698 Base != ClassDecl->bases_end(); ++Base) {
1699 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1700 // We found a direct base of this type. That's what we're
1701 // initializing.
1702 DirectBaseSpec = &*Base;
1703 break;
1704 }
1705 }
1706
1707 // Check for a virtual base class.
1708 // FIXME: We might be able to short-circuit this if we know in advance that
1709 // there are no virtual bases.
1710 VirtualBaseSpec = 0;
1711 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1712 // We haven't found a base yet; search the class hierarchy for a
1713 // virtual base class.
1714 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1715 /*DetectVirtual=*/false);
1716 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1717 BaseType, Paths)) {
1718 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1719 Path != Paths.end(); ++Path) {
1720 if (Path->back().Base->isVirtual()) {
1721 VirtualBaseSpec = Path->back().Base;
1722 break;
1723 }
1724 }
1725 }
1726 }
1727
1728 return DirectBaseSpec || VirtualBaseSpec;
1729}
1730
Sebastian Redl6df65482011-09-24 17:48:25 +00001731/// \brief Handle a C++ member initializer using braced-init-list syntax.
1732MemInitResult
1733Sema::ActOnMemInitializer(Decl *ConstructorD,
1734 Scope *S,
1735 CXXScopeSpec &SS,
1736 IdentifierInfo *MemberOrBase,
1737 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001738 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001739 SourceLocation IdLoc,
1740 Expr *InitList,
1741 SourceLocation EllipsisLoc) {
1742 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001743 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001744 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001745}
1746
1747/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001748MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001749Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001750 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001751 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001752 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001753 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001754 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001755 SourceLocation IdLoc,
1756 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001757 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001758 SourceLocation RParenLoc,
1759 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001760 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1761 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001762 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001763 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001764}
1765
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001766namespace {
1767
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001768// Callback to only accept typo corrections that can be a valid C++ member
1769// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001770class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1771 public:
1772 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1773 : ClassDecl(ClassDecl) {}
1774
1775 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1776 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1777 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1778 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1779 else
1780 return isa<TypeDecl>(ND);
1781 }
1782 return false;
1783 }
1784
1785 private:
1786 CXXRecordDecl *ClassDecl;
1787};
1788
1789}
1790
Sebastian Redl6df65482011-09-24 17:48:25 +00001791/// \brief Handle a C++ member initializer.
1792MemInitResult
1793Sema::BuildMemInitializer(Decl *ConstructorD,
1794 Scope *S,
1795 CXXScopeSpec &SS,
1796 IdentifierInfo *MemberOrBase,
1797 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001798 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001799 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001800 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001801 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001802 if (!ConstructorD)
1803 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001805 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001806
1807 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001808 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001809 if (!Constructor) {
1810 // The user wrote a constructor initializer on a function that is
1811 // not a C++ constructor. Ignore the error for now, because we may
1812 // have more member initializers coming; we'll diagnose it just
1813 // once in ActOnMemInitializers.
1814 return true;
1815 }
1816
1817 CXXRecordDecl *ClassDecl = Constructor->getParent();
1818
1819 // C++ [class.base.init]p2:
1820 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001821 // constructor's class and, if not found in that scope, are looked
1822 // up in the scope containing the constructor's definition.
1823 // [Note: if the constructor's class contains a member with the
1824 // same name as a direct or virtual base class of the class, a
1825 // mem-initializer-id naming the member or base class and composed
1826 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001827 // mem-initializer-id for the hidden base class may be specified
1828 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001829 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001830 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001831 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001832 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001833 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001834 ValueDecl *Member;
1835 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1836 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001837 if (EllipsisLoc.isValid())
1838 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001839 << MemberOrBase
1840 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001841
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001842 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001843 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001844 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001845 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001846 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001847 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001848 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001849
1850 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001851 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001852 } else if (DS.getTypeSpecType() == TST_decltype) {
1853 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001854 } else {
1855 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1856 LookupParsedName(R, S, &SS);
1857
1858 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1859 if (!TyD) {
1860 if (R.isAmbiguous()) return true;
1861
John McCallfd225442010-04-09 19:01:14 +00001862 // We don't want access-control diagnostics here.
1863 R.suppressDiagnostics();
1864
Douglas Gregor7a886e12010-01-19 06:46:48 +00001865 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1866 bool NotUnknownSpecialization = false;
1867 DeclContext *DC = computeDeclContext(SS, false);
1868 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1869 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1870
1871 if (!NotUnknownSpecialization) {
1872 // When the scope specifier can refer to a member of an unknown
1873 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001874 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1875 SS.getWithLocInContext(Context),
1876 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001877 if (BaseType.isNull())
1878 return true;
1879
Douglas Gregor7a886e12010-01-19 06:46:48 +00001880 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001881 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001882 }
1883 }
1884
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001885 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001886 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001887 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001888 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001889 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001890 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001891 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1892 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001893 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001894 // We have found a non-static data member with a similar
1895 // name to what was typed; complain and initialize that
1896 // member.
1897 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1898 << MemberOrBase << true << CorrectedQuotedStr
1899 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1900 Diag(Member->getLocation(), diag::note_previous_decl)
1901 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001902
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001903 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001904 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001905 const CXXBaseSpecifier *DirectBaseSpec;
1906 const CXXBaseSpecifier *VirtualBaseSpec;
1907 if (FindBaseInitializer(*this, ClassDecl,
1908 Context.getTypeDeclType(Type),
1909 DirectBaseSpec, VirtualBaseSpec)) {
1910 // We have found a direct or virtual base class with a
1911 // similar name to what was typed; complain and initialize
1912 // that base class.
1913 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001914 << MemberOrBase << false << CorrectedQuotedStr
1915 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001916
1917 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1918 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001919 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001920 diag::note_base_class_specified_here)
1921 << BaseSpec->getType()
1922 << BaseSpec->getSourceRange();
1923
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001924 TyD = Type;
1925 }
1926 }
1927 }
1928
Douglas Gregor7a886e12010-01-19 06:46:48 +00001929 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001930 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001931 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001932 return true;
1933 }
John McCall2b194412009-12-21 10:41:20 +00001934 }
1935
Douglas Gregor7a886e12010-01-19 06:46:48 +00001936 if (BaseType.isNull()) {
1937 BaseType = Context.getTypeDeclType(TyD);
1938 if (SS.isSet()) {
1939 NestedNameSpecifier *Qualifier =
1940 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001941
Douglas Gregor7a886e12010-01-19 06:46:48 +00001942 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001943 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001944 }
John McCall2b194412009-12-21 10:41:20 +00001945 }
1946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
John McCalla93c9342009-12-07 02:54:59 +00001948 if (!TInfo)
1949 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001950
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001951 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001952}
1953
Chandler Carruth81c64772011-09-03 01:14:15 +00001954/// Checks a member initializer expression for cases where reference (or
1955/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001956static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1957 Expr *Init,
1958 SourceLocation IdLoc) {
1959 QualType MemberTy = Member->getType();
1960
1961 // We only handle pointers and references currently.
1962 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1963 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1964 return;
1965
1966 const bool IsPointer = MemberTy->isPointerType();
1967 if (IsPointer) {
1968 if (const UnaryOperator *Op
1969 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1970 // The only case we're worried about with pointers requires taking the
1971 // address.
1972 if (Op->getOpcode() != UO_AddrOf)
1973 return;
1974
1975 Init = Op->getSubExpr();
1976 } else {
1977 // We only handle address-of expression initializers for pointers.
1978 return;
1979 }
1980 }
1981
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001982 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1983 // Taking the address of a temporary will be diagnosed as a hard error.
1984 if (IsPointer)
1985 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001986
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001987 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1988 << Member << Init->getSourceRange();
1989 } else if (const DeclRefExpr *DRE
1990 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1991 // We only warn when referring to a non-reference parameter declaration.
1992 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1993 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001994 return;
1995
1996 S.Diag(Init->getExprLoc(),
1997 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1998 : diag::warn_bind_ref_member_to_parameter)
1999 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002000 } else {
2001 // Other initializers are fine.
2002 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002003 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002004
2005 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2006 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002007}
2008
John McCallb4190042009-11-04 23:02:40 +00002009/// Checks an initializer expression for use of uninitialized fields, such as
2010/// containing the field that is being initialized. Returns true if there is an
2011/// uninitialized field was used an updates the SourceLocation parameter; false
2012/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002013static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002014 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002015 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002016 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2017
Nick Lewycky43ad1822010-06-15 07:32:55 +00002018 if (isa<CallExpr>(S)) {
2019 // Do not descend into function calls or constructors, as the use
2020 // of an uninitialized field may be valid. One would have to inspect
2021 // the contents of the function/ctor to determine if it is safe or not.
2022 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2023 // may be safe, depending on what the function/ctor does.
2024 return false;
2025 }
2026 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2027 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002028
2029 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2030 // The member expression points to a static data member.
2031 assert(VD->isStaticDataMember() &&
2032 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002033 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002034 return false;
2035 }
2036
2037 if (isa<EnumConstantDecl>(RhsField)) {
2038 // The member expression points to an enum.
2039 return false;
2040 }
2041
John McCallb4190042009-11-04 23:02:40 +00002042 if (RhsField == LhsField) {
2043 // Initializing a field with itself. Throw a warning.
2044 // But wait; there are exceptions!
2045 // Exception #1: The field may not belong to this record.
2046 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002047 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002048 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2049 // Even though the field matches, it does not belong to this record.
2050 return false;
2051 }
2052 // None of the exceptions triggered; return true to indicate an
2053 // uninitialized field was used.
2054 *L = ME->getMemberLoc();
2055 return true;
2056 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002057 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002058 // sizeof/alignof doesn't reference contents, do not warn.
2059 return false;
2060 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2061 // address-of doesn't reference contents (the pointer may be dereferenced
2062 // in the same expression but it would be rare; and weird).
2063 if (UOE->getOpcode() == UO_AddrOf)
2064 return false;
John McCallb4190042009-11-04 23:02:40 +00002065 }
John McCall7502c1d2011-02-13 04:07:26 +00002066 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002067 if (!*it) {
2068 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002069 continue;
2070 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002071 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2072 return true;
John McCallb4190042009-11-04 23:02:40 +00002073 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002074 return false;
John McCallb4190042009-11-04 23:02:40 +00002075}
2076
John McCallf312b1e2010-08-26 23:41:50 +00002077MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002078Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002079 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002080 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2081 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2082 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002083 "Member must be a FieldDecl or IndirectFieldDecl");
2084
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002085 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002086 return true;
2087
Douglas Gregor464b2f02010-11-05 22:21:31 +00002088 if (Member->isInvalidDecl())
2089 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002090
John McCallb4190042009-11-04 23:02:40 +00002091 // Diagnose value-uses of fields to initialize themselves, e.g.
2092 // foo(foo)
2093 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002094 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002095 Expr **Args;
2096 unsigned NumArgs;
2097 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2098 Args = ParenList->getExprs();
2099 NumArgs = ParenList->getNumExprs();
2100 } else {
2101 InitListExpr *InitList = cast<InitListExpr>(Init);
2102 Args = InitList->getInits();
2103 NumArgs = InitList->getNumInits();
2104 }
2105 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002106 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002107 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002108 // FIXME: Return true in the case when other fields are used before being
2109 // uninitialized. For example, let this field be the i'th field. When
2110 // initializing the i'th field, throw a warning if any of the >= i'th
2111 // fields are used, as they are not yet initialized.
2112 // Right now we are only handling the case where the i'th field uses
2113 // itself in its initializer.
2114 Diag(L, diag::warn_field_is_uninit);
2115 }
2116 }
2117
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002118 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002119
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002120 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002121 // Can't check initialization for a member of dependent type or when
2122 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002123 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002124 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002125 bool InitList = false;
2126 if (isa<InitListExpr>(Init)) {
2127 InitList = true;
2128 Args = &Init;
2129 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002130
2131 if (isStdInitializerList(Member->getType(), 0)) {
2132 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2133 << /*at end of ctor*/1 << InitRange;
2134 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002135 }
2136
Chandler Carruth894aed92010-12-06 09:23:57 +00002137 // Initialize the member.
2138 InitializedEntity MemberEntity =
2139 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2140 : InitializedEntity::InitializeMember(IndirectMember, 0);
2141 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002142 InitList ? InitializationKind::CreateDirectList(IdLoc)
2143 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2144 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002145
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002146 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2147 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2148 MultiExprArg(*this, Args, NumArgs),
2149 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002150 if (MemberInit.isInvalid())
2151 return true;
2152
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002153 CheckImplicitConversions(MemberInit.get(),
2154 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002155
2156 // C++0x [class.base.init]p7:
2157 // The initialization of each base and member constitutes a
2158 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002159 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002160 if (MemberInit.isInvalid())
2161 return true;
2162
2163 // If we are in a dependent context, template instantiation will
2164 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002165 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002166 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2167 // of the information that we have about the member
2168 // initializer. However, deconstructing the ASTs is a dicey process,
2169 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002170 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002171 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002172 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002173 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002174 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2175 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002176 }
2177
Chandler Carruth894aed92010-12-06 09:23:57 +00002178 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2180 InitRange.getBegin(), Init,
2181 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002182 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002183 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2184 InitRange.getBegin(), Init,
2185 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002186 }
Eli Friedman59c04372009-07-29 19:44:27 +00002187}
2188
John McCallf312b1e2010-08-26 23:41:50 +00002189MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002190Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002191 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002192 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002193 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002194 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002195 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002196 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002197
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002198 bool InitList = true;
2199 Expr **Args = &Init;
2200 unsigned NumArgs = 1;
2201 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2202 InitList = false;
2203 Args = ParenList->getExprs();
2204 NumArgs = ParenList->getNumExprs();
2205 }
2206
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002207 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002208 // Initialize the object.
2209 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2210 QualType(ClassDecl->getTypeForDecl(), 0));
2211 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002212 InitList ? InitializationKind::CreateDirectList(NameLoc)
2213 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2214 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002215 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2216 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2217 MultiExprArg(*this, Args,NumArgs),
2218 0);
Sean Hunt41717662011-02-26 19:13:13 +00002219 if (DelegationInit.isInvalid())
2220 return true;
2221
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002222 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2223 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002224
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002225 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002226
2227 // C++0x [class.base.init]p7:
2228 // The initialization of each base and member constitutes a
2229 // full-expression.
2230 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2231 if (DelegationInit.isInvalid())
2232 return true;
2233
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002234 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002235 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002236 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002237}
2238
2239MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002240Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002242 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002243 SourceLocation BaseLoc
2244 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002245
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002246 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2247 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2248 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2249
2250 // C++ [class.base.init]p2:
2251 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002252 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002253 // of that class, the mem-initializer is ill-formed. A
2254 // mem-initializer-list can initialize a base class using any
2255 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002256 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002257
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002258 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002259 if (EllipsisLoc.isValid()) {
2260 // This is a pack expansion.
2261 if (!BaseType->containsUnexpandedParameterPack()) {
2262 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002264
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002265 EllipsisLoc = SourceLocation();
2266 }
2267 } else {
2268 // Check for any unexpanded parameter packs.
2269 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2270 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002271
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002272 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002273 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002274 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002275
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002276 // Check for direct and virtual base classes.
2277 const CXXBaseSpecifier *DirectBaseSpec = 0;
2278 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2279 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002280 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2281 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002282 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002283
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002284 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2285 VirtualBaseSpec);
2286
2287 // C++ [base.class.init]p2:
2288 // Unless the mem-initializer-id names a nonstatic data member of the
2289 // constructor's class or a direct or virtual base of that class, the
2290 // mem-initializer is ill-formed.
2291 if (!DirectBaseSpec && !VirtualBaseSpec) {
2292 // If the class has any dependent bases, then it's possible that
2293 // one of those types will resolve to the same type as
2294 // BaseType. Therefore, just treat this as a dependent base
2295 // class initialization. FIXME: Should we try to check the
2296 // initialization anyway? It seems odd.
2297 if (ClassDecl->hasAnyDependentBases())
2298 Dependent = true;
2299 else
2300 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2301 << BaseType << Context.getTypeDeclType(ClassDecl)
2302 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2303 }
2304 }
2305
2306 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002307 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Sebastian Redl6df65482011-09-24 17:48:25 +00002309 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2310 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002311 InitRange.getBegin(), Init,
2312 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002313 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002314
2315 // C++ [base.class.init]p2:
2316 // If a mem-initializer-id is ambiguous because it designates both
2317 // a direct non-virtual base class and an inherited virtual base
2318 // class, the mem-initializer is ill-formed.
2319 if (DirectBaseSpec && VirtualBaseSpec)
2320 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002321 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002322
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002323 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324 if (!BaseSpec)
2325 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2326
2327 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002328 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 Expr **Args = &Init;
2330 unsigned NumArgs = 1;
2331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002332 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002333 Args = ParenList->getExprs();
2334 NumArgs = ParenList->getNumExprs();
2335 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002336
2337 InitializedEntity BaseEntity =
2338 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2339 InitializationKind Kind =
2340 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2341 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2342 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002343 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2344 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2345 MultiExprArg(*this, Args, NumArgs),
2346 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 if (BaseInit.isInvalid())
2348 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002349
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002351
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002352 // C++0x [class.base.init]p7:
2353 // The initialization of each base and member constitutes a
2354 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002355 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002356 if (BaseInit.isInvalid())
2357 return true;
2358
2359 // If we are in a dependent context, template instantiation will
2360 // perform this type-checking again. Just save the arguments that we
2361 // received in a ParenListExpr.
2362 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2363 // of the information that we have about the base
2364 // initializer. However, deconstructing the ASTs is a dicey process,
2365 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002366 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002368
Sean Huntcbb67482011-01-08 20:30:50 +00002369 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002370 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002372 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002374}
2375
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002376// Create a static_cast\<T&&>(expr).
2377static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2378 QualType ExprType = E->getType();
2379 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2380 SourceLocation ExprLoc = E->getLocStart();
2381 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2382 TargetType, ExprLoc);
2383
2384 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2385 SourceRange(ExprLoc, ExprLoc),
2386 E->getSourceRange()).take();
2387}
2388
Anders Carlssone5ef7402010-04-23 03:10:23 +00002389/// ImplicitInitializerKind - How an implicit base or member initializer should
2390/// initialize its base or member.
2391enum ImplicitInitializerKind {
2392 IIK_Default,
2393 IIK_Copy,
2394 IIK_Move
2395};
2396
Anders Carlssondefefd22010-04-23 02:00:02 +00002397static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002398BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002399 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002400 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002401 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002402 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002403 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002404 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2405 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002406
John McCall60d7b3a2010-08-24 06:29:42 +00002407 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002408
2409 switch (ImplicitInitKind) {
2410 case IIK_Default: {
2411 InitializationKind InitKind
2412 = InitializationKind::CreateDefault(Constructor->getLocation());
2413 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002415 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002416 break;
2417 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002418
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002419 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002420 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002421 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002422 ParmVarDecl *Param = Constructor->getParamDecl(0);
2423 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002424
Anders Carlssone5ef7402010-04-23 03:10:23 +00002425 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002426 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002427 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002428 Constructor->getLocation(), ParamType,
2429 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002430
Eli Friedman5f2987c2012-02-02 03:46:19 +00002431 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2432
Anders Carlssonc7957502010-04-24 22:02:54 +00002433 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002434 QualType ArgTy =
2435 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2436 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002437
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438 if (Moving) {
2439 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2440 }
2441
John McCallf871d0c2010-08-07 06:22:56 +00002442 CXXCastPath BasePath;
2443 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002444 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2445 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002446 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002447 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002448
Anders Carlssone5ef7402010-04-23 03:10:23 +00002449 InitializationKind InitKind
2450 = InitializationKind::CreateDirect(Constructor->getLocation(),
2451 SourceLocation(), SourceLocation());
2452 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2453 &CopyCtorArg, 1);
2454 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002455 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002456 break;
2457 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002458 }
John McCall9ae2f072010-08-23 23:25:46 +00002459
Douglas Gregor53c374f2010-12-07 00:41:46 +00002460 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002461 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002462 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002463
Anders Carlssondefefd22010-04-23 02:00:02 +00002464 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002465 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002466 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2467 SourceLocation()),
2468 BaseSpec->isVirtual(),
2469 SourceLocation(),
2470 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002471 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002472 SourceLocation());
2473
Anders Carlssondefefd22010-04-23 02:00:02 +00002474 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002475}
2476
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002477static bool RefersToRValueRef(Expr *MemRef) {
2478 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2479 return Referenced->getType()->isRValueReferenceType();
2480}
2481
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002482static bool
2483BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002484 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002485 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002486 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002487 if (Field->isInvalidDecl())
2488 return true;
2489
Chandler Carruthf186b542010-06-29 23:50:44 +00002490 SourceLocation Loc = Constructor->getLocation();
2491
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002492 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2493 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002494 ParmVarDecl *Param = Constructor->getParamDecl(0);
2495 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002496
2497 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002498 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2499 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002500
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002501 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002502 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002503 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002504 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505
Eli Friedman5f2987c2012-02-02 03:46:19 +00002506 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2507
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 if (Moving) {
2509 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2510 }
2511
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002512 // Build a reference to this field within the parameter.
2513 CXXScopeSpec SS;
2514 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2515 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2517 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002518 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002519 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002520 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002521 ParamType, Loc,
2522 /*IsArrow=*/false,
2523 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002524 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002525 /*FirstQualifierInScope=*/0,
2526 MemberLookup,
2527 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002528 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002529 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002530
2531 // C++11 [class.copy]p15:
2532 // - if a member m has rvalue reference type T&&, it is direct-initialized
2533 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002534 if (RefersToRValueRef(CtorArg.get())) {
2535 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002536 }
2537
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 // When the field we are copying is an array, create index variables for
2539 // each dimension of the array. We use these index variables to subscript
2540 // the source array, and other clients (e.g., CodeGen) will perform the
2541 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002543 QualType BaseType = Field->getType();
2544 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002545 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002546 while (const ConstantArrayType *Array
2547 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002548 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002549 // Create the iteration variable for this array index.
2550 IdentifierInfo *IterationVarName = 0;
2551 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002552 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002553 llvm::raw_svector_ostream OS(Str);
2554 OS << "__i" << IndexVariables.size();
2555 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2556 }
2557 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002559 IterationVarName, SizeType,
2560 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002561 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002562 IndexVariables.push_back(IterationVar);
2563
2564 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002565 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002566 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002567 assert(!IterationVarRef.isInvalid() &&
2568 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002569 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2570 assert(!IterationVarRef.isInvalid() &&
2571 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002572
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002573 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002574 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002575 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002576 Loc);
2577 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002578 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002579
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002580 BaseType = Array->getElementType();
2581 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002582
2583 // The array subscript expression is an lvalue, which is wrong for moving.
2584 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002585 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002586
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 // Construct the entity that we will be initializing. For an array, this
2588 // will be first element in the array, which may require several levels
2589 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002590 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002591 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002592 if (Indirect)
2593 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2594 else
2595 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2597 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2598 0,
2599 Entities.back()));
2600
2601 // Direct-initialize to use the copy constructor.
2602 InitializationKind InitKind =
2603 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2604
Sebastian Redl74e611a2011-09-04 18:14:28 +00002605 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002606 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002607 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002608
John McCall60d7b3a2010-08-24 06:29:42 +00002609 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002611 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002612 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002613 if (MemberInit.isInvalid())
2614 return true;
2615
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002616 if (Indirect) {
2617 assert(IndexVariables.size() == 0 &&
2618 "Indirect field improperly initialized");
2619 CXXMemberInit
2620 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2621 Loc, Loc,
2622 MemberInit.takeAs<Expr>(),
2623 Loc);
2624 } else
2625 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2626 Loc, MemberInit.takeAs<Expr>(),
2627 Loc,
2628 IndexVariables.data(),
2629 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 return false;
2631 }
2632
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002633 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2634
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002635 QualType FieldBaseElementType =
2636 SemaRef.Context.getBaseElementType(Field->getType());
2637
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002638 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002639 InitializedEntity InitEntity
2640 = Indirect? InitializedEntity::InitializeMember(Indirect)
2641 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002642 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002643 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002644
2645 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002646 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002647 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002648
Douglas Gregor53c374f2010-12-07 00:41:46 +00002649 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002650 if (MemberInit.isInvalid())
2651 return true;
2652
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002653 if (Indirect)
2654 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2655 Indirect, Loc,
2656 Loc,
2657 MemberInit.get(),
2658 Loc);
2659 else
2660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2661 Field, Loc, Loc,
2662 MemberInit.get(),
2663 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002664 return false;
2665 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002666
Sean Hunt1f2f3842011-05-17 00:19:05 +00002667 if (!Field->getParent()->isUnion()) {
2668 if (FieldBaseElementType->isReferenceType()) {
2669 SemaRef.Diag(Constructor->getLocation(),
2670 diag::err_uninitialized_member_in_ctor)
2671 << (int)Constructor->isImplicit()
2672 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2673 << 0 << Field->getDeclName();
2674 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2675 return true;
2676 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002677
Sean Hunt1f2f3842011-05-17 00:19:05 +00002678 if (FieldBaseElementType.isConstQualified()) {
2679 SemaRef.Diag(Constructor->getLocation(),
2680 diag::err_uninitialized_member_in_ctor)
2681 << (int)Constructor->isImplicit()
2682 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2683 << 1 << Field->getDeclName();
2684 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2685 return true;
2686 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002687 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002688
David Blaikie4e4d0842012-03-11 07:00:24 +00002689 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002690 FieldBaseElementType->isObjCRetainableType() &&
2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2692 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2693 // Instant objects:
2694 // Default-initialize Objective-C pointers to NULL.
2695 CXXMemberInit
2696 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2697 Loc, Loc,
2698 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2699 Loc);
2700 return false;
2701 }
2702
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002703 // Nothing to initialize.
2704 CXXMemberInit = 0;
2705 return false;
2706}
John McCallf1860e52010-05-20 23:23:51 +00002707
2708namespace {
2709struct BaseAndFieldInfo {
2710 Sema &S;
2711 CXXConstructorDecl *Ctor;
2712 bool AnyErrorsInInits;
2713 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002714 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002715 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002716
2717 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2718 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002719 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2720 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002721 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002722 else if (Generated && Ctor->isMoveConstructor())
2723 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002724 else
2725 IIK = IIK_Default;
2726 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002727
2728 bool isImplicitCopyOrMove() const {
2729 switch (IIK) {
2730 case IIK_Copy:
2731 case IIK_Move:
2732 return true;
2733
2734 case IIK_Default:
2735 return false;
2736 }
David Blaikie30263482012-01-20 21:50:17 +00002737
2738 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002739 }
John McCallf1860e52010-05-20 23:23:51 +00002740};
2741}
2742
Richard Smitha4950662011-09-19 13:34:43 +00002743/// \brief Determine whether the given indirect field declaration is somewhere
2744/// within an anonymous union.
2745static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2746 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2747 CEnd = F->chain_end();
2748 C != CEnd; ++C)
2749 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2750 if (Record->isUnion())
2751 return true;
2752
2753 return false;
2754}
2755
Douglas Gregorddb21472011-11-02 23:04:16 +00002756/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2757/// array type.
2758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2759 if (T->isIncompleteArrayType())
2760 return true;
2761
2762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2763 if (!ArrayT->getSize())
2764 return true;
2765
2766 T = ArrayT->getElementType();
2767 }
2768
2769 return false;
2770}
2771
Richard Smith7a614d82011-06-11 17:19:42 +00002772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002773 FieldDecl *Field,
2774 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002775
Chandler Carruthe861c602010-06-30 02:59:29 +00002776 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002777 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002778 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002779 return false;
2780 }
2781
Richard Smith7a614d82011-06-11 17:19:42 +00002782 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2783 // has a brace-or-equal-initializer, the entity is initialized as specified
2784 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002785 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002786 CXXCtorInitializer *Init;
2787 if (Indirect)
2788 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2789 SourceLocation(),
2790 SourceLocation(), 0,
2791 SourceLocation());
2792 else
2793 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2794 SourceLocation(),
2795 SourceLocation(), 0,
2796 SourceLocation());
2797 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002798 return false;
2799 }
2800
Richard Smithc115f632011-09-18 11:14:50 +00002801 // Don't build an implicit initializer for union members if none was
2802 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002803 if (Field->getParent()->isUnion() ||
2804 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002805 return false;
2806
Douglas Gregorddb21472011-11-02 23:04:16 +00002807 // Don't initialize incomplete or zero-length arrays.
2808 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2809 return false;
2810
John McCallf1860e52010-05-20 23:23:51 +00002811 // Don't try to build an implicit initializer if there were semantic
2812 // errors in any of the initializers (and therefore we might be
2813 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002814 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002815 return false;
2816
Sean Huntcbb67482011-01-08 20:30:50 +00002817 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002818 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2819 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002820 return true;
John McCallf1860e52010-05-20 23:23:51 +00002821
Francois Pichet00eb3f92010-12-04 09:14:42 +00002822 if (Init)
2823 Info.AllToInit.push_back(Init);
2824
John McCallf1860e52010-05-20 23:23:51 +00002825 return false;
2826}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002827
2828bool
2829Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2830 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002831 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002832 Constructor->setNumCtorInitializers(1);
2833 CXXCtorInitializer **initializer =
2834 new (Context) CXXCtorInitializer*[1];
2835 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2836 Constructor->setCtorInitializers(initializer);
2837
Sean Huntb76af9c2011-05-03 23:05:34 +00002838 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002839 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002840 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2841 }
2842
Sean Huntc1598702011-05-05 00:05:47 +00002843 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002844
Sean Hunt059ce0d2011-05-01 07:04:31 +00002845 return false;
2846}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002847
John McCallb77115d2011-06-17 00:18:42 +00002848bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2849 CXXCtorInitializer **Initializers,
2850 unsigned NumInitializers,
2851 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002852 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002853 // Just store the initializers as written, they will be checked during
2854 // instantiation.
2855 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002856 Constructor->setNumCtorInitializers(NumInitializers);
2857 CXXCtorInitializer **baseOrMemberInitializers =
2858 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002859 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002860 NumInitializers * sizeof(CXXCtorInitializer*));
2861 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002862 }
2863
2864 return false;
2865 }
2866
John McCallf1860e52010-05-20 23:23:51 +00002867 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002868
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002869 // We need to build the initializer AST according to order of construction
2870 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002871 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002872 if (!ClassDecl)
2873 return true;
2874
Eli Friedman80c30da2009-11-09 19:20:36 +00002875 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002877 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002878 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002879
2880 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002881 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002882 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002883 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002884 }
2885
Anders Carlsson711f34a2010-04-21 19:52:01 +00002886 // Keep track of the direct virtual bases.
2887 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2888 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2889 E = ClassDecl->bases_end(); I != E; ++I) {
2890 if (I->isVirtual())
2891 DirectVBases.insert(I);
2892 }
2893
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002894 // Push virtual bases before others.
2895 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2896 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2897
Sean Huntcbb67482011-01-08 20:30:50 +00002898 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002899 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2900 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002901 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002902 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002903 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002904 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002905 VBase, IsInheritedVirtualBase,
2906 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 HadError = true;
2908 continue;
2909 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002910
John McCallf1860e52010-05-20 23:23:51 +00002911 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002912 }
2913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCallf1860e52010-05-20 23:23:51 +00002915 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002916 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2917 E = ClassDecl->bases_end(); Base != E; ++Base) {
2918 // Virtuals are in the virtual base list and already constructed.
2919 if (Base->isVirtual())
2920 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Sean Huntcbb67482011-01-08 20:30:50 +00002922 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002923 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2924 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002925 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002926 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002929 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002930 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002931 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002932 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002933
John McCallf1860e52010-05-20 23:23:51 +00002934 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002935 }
2936 }
Mike Stump1eb44332009-09-09 15:08:12 +00002937
John McCallf1860e52010-05-20 23:23:51 +00002938 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002939 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2940 MemEnd = ClassDecl->decls_end();
2941 Mem != MemEnd; ++Mem) {
2942 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002943 // C++ [class.bit]p2:
2944 // A declaration for a bit-field that omits the identifier declares an
2945 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2946 // initialized.
2947 if (F->isUnnamedBitfield())
2948 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002949
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002950 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002951 // handle anonymous struct/union fields based on their individual
2952 // indirect fields.
2953 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2954 continue;
2955
2956 if (CollectFieldInitializer(*this, Info, F))
2957 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002958 continue;
2959 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002960
2961 // Beyond this point, we only consider default initialization.
2962 if (Info.IIK != IIK_Default)
2963 continue;
2964
2965 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2966 if (F->getType()->isIncompleteArrayType()) {
2967 assert(ClassDecl->hasFlexibleArrayMember() &&
2968 "Incomplete array type is not valid");
2969 continue;
2970 }
2971
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002972 // Initialize each field of an anonymous struct individually.
2973 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2974 HadError = true;
2975
2976 continue;
2977 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCallf1860e52010-05-20 23:23:51 +00002980 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002981 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002982 Constructor->setNumCtorInitializers(NumInitializers);
2983 CXXCtorInitializer **baseOrMemberInitializers =
2984 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002985 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002986 NumInitializers * sizeof(CXXCtorInitializer*));
2987 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002988
John McCallef027fe2010-03-16 21:39:52 +00002989 // Constructors implicitly reference the base and member
2990 // destructors.
2991 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2992 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002993 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002994
2995 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002996}
2997
Eli Friedman6347f422009-07-21 19:28:10 +00002998static void *GetKeyForTopLevelField(FieldDecl *Field) {
2999 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003000 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003001 if (RT->getDecl()->isAnonymousStructOrUnion())
3002 return static_cast<void *>(RT->getDecl());
3003 }
3004 return static_cast<void *>(Field);
3005}
3006
Anders Carlssonea356fb2010-04-02 05:42:15 +00003007static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003008 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003009}
3010
Anders Carlssonea356fb2010-04-02 05:42:15 +00003011static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003012 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003013 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003014 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003015
Eli Friedman6347f422009-07-21 19:28:10 +00003016 // For fields injected into the class via declaration of an anonymous union,
3017 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003018 FieldDecl *Field = Member->getAnyMember();
3019
John McCall3c3ccdb2010-04-10 09:28:51 +00003020 // If the field is a member of an anonymous struct or union, our key
3021 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003022 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003023 if (RD->isAnonymousStructOrUnion()) {
3024 while (true) {
3025 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3026 if (Parent->isAnonymousStructOrUnion())
3027 RD = Parent;
3028 else
3029 break;
3030 }
3031
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003032 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003033 }
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003035 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003036}
3037
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003038static void
3039DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003040 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003041 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003042 unsigned NumInits) {
3043 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003044 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003046 // Don't check initializers order unless the warning is enabled at the
3047 // location of at least one initializer.
3048 bool ShouldCheckOrder = false;
3049 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003050 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003051 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3052 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003053 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003054 ShouldCheckOrder = true;
3055 break;
3056 }
3057 }
3058 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003059 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003060
John McCalld6ca8da2010-04-10 07:37:23 +00003061 // Build the list of bases and members in the order that they'll
3062 // actually be initialized. The explicit initializers should be in
3063 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003064 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Anders Carlsson071d6102010-04-02 03:38:04 +00003066 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3067
John McCalld6ca8da2010-04-10 07:37:23 +00003068 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003069 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003070 ClassDecl->vbases_begin(),
3071 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003072 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003073
John McCalld6ca8da2010-04-10 07:37:23 +00003074 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003075 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003076 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003077 if (Base->isVirtual())
3078 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003079 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003080 }
Mike Stump1eb44332009-09-09 15:08:12 +00003081
John McCalld6ca8da2010-04-10 07:37:23 +00003082 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003084 E = ClassDecl->field_end(); Field != E; ++Field) {
3085 if (Field->isUnnamedBitfield())
3086 continue;
3087
John McCalld6ca8da2010-04-10 07:37:23 +00003088 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003089 }
3090
John McCalld6ca8da2010-04-10 07:37:23 +00003091 unsigned NumIdealInits = IdealInitKeys.size();
3092 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003093
Sean Huntcbb67482011-01-08 20:30:50 +00003094 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003095 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003096 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003097 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003098
3099 // Scan forward to try to find this initializer in the idealized
3100 // initializers list.
3101 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3102 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003103 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003104
3105 // If we didn't find this initializer, it must be because we
3106 // scanned past it on a previous iteration. That can only
3107 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003108 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003109 Sema::SemaDiagnosticBuilder D =
3110 SemaRef.Diag(PrevInit->getSourceLocation(),
3111 diag::warn_initializer_out_of_order);
3112
Francois Pichet00eb3f92010-12-04 09:14:42 +00003113 if (PrevInit->isAnyMemberInitializer())
3114 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003115 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003116 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003117
Francois Pichet00eb3f92010-12-04 09:14:42 +00003118 if (Init->isAnyMemberInitializer())
3119 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003120 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003121 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003122
3123 // Move back to the initializer's location in the ideal list.
3124 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3125 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003126 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003127
3128 assert(IdealIndex != NumIdealInits &&
3129 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003130 }
John McCalld6ca8da2010-04-10 07:37:23 +00003131
3132 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003133 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003134}
3135
John McCall3c3ccdb2010-04-10 09:28:51 +00003136namespace {
3137bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003138 CXXCtorInitializer *Init,
3139 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003140 if (!PrevInit) {
3141 PrevInit = Init;
3142 return false;
3143 }
3144
3145 if (FieldDecl *Field = Init->getMember())
3146 S.Diag(Init->getSourceLocation(),
3147 diag::err_multiple_mem_initialization)
3148 << Field->getDeclName()
3149 << Init->getSourceRange();
3150 else {
John McCallf4c73712011-01-19 06:33:43 +00003151 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003152 assert(BaseClass && "neither field nor base");
3153 S.Diag(Init->getSourceLocation(),
3154 diag::err_multiple_base_initialization)
3155 << QualType(BaseClass, 0)
3156 << Init->getSourceRange();
3157 }
3158 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3159 << 0 << PrevInit->getSourceRange();
3160
3161 return true;
3162}
3163
Sean Huntcbb67482011-01-08 20:30:50 +00003164typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003165typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3166
3167bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003168 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003169 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003170 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003171 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003172 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003173
3174 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003175 if (Parent->isUnion()) {
3176 UnionEntry &En = Unions[Parent];
3177 if (En.first && En.first != Child) {
3178 S.Diag(Init->getSourceLocation(),
3179 diag::err_multiple_mem_union_initialization)
3180 << Field->getDeclName()
3181 << Init->getSourceRange();
3182 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3183 << 0 << En.second->getSourceRange();
3184 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003185 }
3186 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003187 En.first = Child;
3188 En.second = Init;
3189 }
David Blaikie6fe29652011-11-17 06:01:57 +00003190 if (!Parent->isAnonymousStructOrUnion())
3191 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003192 }
3193
3194 Child = Parent;
3195 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003196 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003197
3198 return false;
3199}
3200}
3201
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003202/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003203void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003204 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003205 CXXCtorInitializer **meminits,
3206 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003207 bool AnyErrors) {
3208 if (!ConstructorDecl)
3209 return;
3210
3211 AdjustDeclIfTemplate(ConstructorDecl);
3212
3213 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003214 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003215
3216 if (!Constructor) {
3217 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3218 return;
3219 }
3220
Sean Huntcbb67482011-01-08 20:30:50 +00003221 CXXCtorInitializer **MemInits =
3222 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003223
3224 // Mapping for the duplicate initializers check.
3225 // For member initializers, this is keyed with a FieldDecl*.
3226 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003227 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003228
3229 // Mapping for the inconsistent anonymous-union initializers check.
3230 RedundantUnionMap MemberUnions;
3231
Anders Carlssonea356fb2010-04-02 05:42:15 +00003232 bool HadError = false;
3233 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003234 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003235
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003236 // Set the source order index.
3237 Init->setSourceOrder(i);
3238
Francois Pichet00eb3f92010-12-04 09:14:42 +00003239 if (Init->isAnyMemberInitializer()) {
3240 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003241 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3242 CheckRedundantUnionInit(*this, Init, MemberUnions))
3243 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003244 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003245 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3246 if (CheckRedundantInit(*this, Init, Members[Key]))
3247 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003248 } else {
3249 assert(Init->isDelegatingInitializer());
3250 // This must be the only initializer
3251 if (i != 0 || NumMemInits > 1) {
3252 Diag(MemInits[0]->getSourceLocation(),
3253 diag::err_delegating_initializer_alone)
3254 << MemInits[0]->getSourceRange();
3255 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003256 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003257 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003258 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003259 // Return immediately as the initializer is set.
3260 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003261 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003262 }
3263
Anders Carlssonea356fb2010-04-02 05:42:15 +00003264 if (HadError)
3265 return;
3266
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003267 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003268
Sean Huntcbb67482011-01-08 20:30:50 +00003269 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003270}
3271
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003272void
John McCallef027fe2010-03-16 21:39:52 +00003273Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3274 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003275 // Ignore dependent contexts. Also ignore unions, since their members never
3276 // have destructors implicitly called.
3277 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003278 return;
John McCall58e6f342010-03-16 05:22:47 +00003279
3280 // FIXME: all the access-control diagnostics are positioned on the
3281 // field/base declaration. That's probably good; that said, the
3282 // user might reasonably want to know why the destructor is being
3283 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003284
Anders Carlsson9f853df2009-11-17 04:44:12 +00003285 // Non-static data members.
3286 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3287 E = ClassDecl->field_end(); I != E; ++I) {
3288 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003289 if (Field->isInvalidDecl())
3290 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003291
3292 // Don't destroy incomplete or zero-length arrays.
3293 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3294 continue;
3295
Anders Carlsson9f853df2009-11-17 04:44:12 +00003296 QualType FieldType = Context.getBaseElementType(Field->getType());
3297
3298 const RecordType* RT = FieldType->getAs<RecordType>();
3299 if (!RT)
3300 continue;
3301
3302 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003303 if (FieldClassDecl->isInvalidDecl())
3304 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003305 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003306 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003307 // The destructor for an implicit anonymous union member is never invoked.
3308 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3309 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003310
Douglas Gregordb89f282010-07-01 22:47:18 +00003311 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003312 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003313 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003314 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003315 << Field->getDeclName()
3316 << FieldType);
3317
Eli Friedman5f2987c2012-02-02 03:46:19 +00003318 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003319 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003320 }
3321
John McCall58e6f342010-03-16 05:22:47 +00003322 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3323
Anders Carlsson9f853df2009-11-17 04:44:12 +00003324 // Bases.
3325 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3326 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003327 // Bases are always records in a well-formed non-dependent class.
3328 const RecordType *RT = Base->getType()->getAs<RecordType>();
3329
3330 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003331 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003332 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003333
John McCall58e6f342010-03-16 05:22:47 +00003334 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003335 // If our base class is invalid, we probably can't get its dtor anyway.
3336 if (BaseClassDecl->isInvalidDecl())
3337 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003338 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003339 continue;
John McCall58e6f342010-03-16 05:22:47 +00003340
Douglas Gregordb89f282010-07-01 22:47:18 +00003341 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003342 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003343
3344 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003345 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003346 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003347 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003348 << Base->getSourceRange(),
3349 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003350
Eli Friedman5f2987c2012-02-02 03:46:19 +00003351 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003352 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003353 }
3354
3355 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003356 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3357 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003358
3359 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003360 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003361
3362 // Ignore direct virtual bases.
3363 if (DirectVirtualBases.count(RT))
3364 continue;
3365
John McCall58e6f342010-03-16 05:22:47 +00003366 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003367 // If our base class is invalid, we probably can't get its dtor anyway.
3368 if (BaseClassDecl->isInvalidDecl())
3369 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003370 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003371 continue;
John McCall58e6f342010-03-16 05:22:47 +00003372
Douglas Gregordb89f282010-07-01 22:47:18 +00003373 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003374 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003375 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003376 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003377 << VBase->getType(),
3378 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003379
Eli Friedman5f2987c2012-02-02 03:46:19 +00003380 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003381 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003382 }
3383}
3384
John McCalld226f652010-08-21 09:40:31 +00003385void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003386 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003387 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Mike Stump1eb44332009-09-09 15:08:12 +00003389 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003390 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003391 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003392}
3393
Mike Stump1eb44332009-09-09 15:08:12 +00003394bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003395 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003396 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003397 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003398 else
John McCall94c3b562010-08-18 09:41:07 +00003399 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003400}
3401
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003402bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003403 const PartialDiagnostic &PD) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003404 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003405 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Anders Carlsson11f21a02009-03-23 19:10:31 +00003407 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003408 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Ted Kremenek6217b802009-07-29 21:53:49 +00003410 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003411 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003412 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003413 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003415 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003416 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003417 }
Mike Stump1eb44332009-09-09 15:08:12 +00003418
Ted Kremenek6217b802009-07-29 21:53:49 +00003419 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003420 if (!RT)
3421 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCall86ff3082010-02-04 22:26:26 +00003423 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003424
John McCall94c3b562010-08-18 09:41:07 +00003425 // We can't answer whether something is abstract until it has a
3426 // definition. If it's currently being defined, we'll walk back
3427 // over all the declarations when we have a full definition.
3428 const CXXRecordDecl *Def = RD->getDefinition();
3429 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003430 return false;
3431
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003432 if (!RD->isAbstract())
3433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003435 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003436 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003437
John McCall94c3b562010-08-18 09:41:07 +00003438 return true;
3439}
3440
3441void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3442 // Check if we've already emitted the list of pure virtual functions
3443 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003444 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003445 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003447 CXXFinalOverriderMap FinalOverriders;
3448 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003450 // Keep a set of seen pure methods so we won't diagnose the same method
3451 // more than once.
3452 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3453
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003454 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3455 MEnd = FinalOverriders.end();
3456 M != MEnd;
3457 ++M) {
3458 for (OverridingMethods::iterator SO = M->second.begin(),
3459 SOEnd = M->second.end();
3460 SO != SOEnd; ++SO) {
3461 // C++ [class.abstract]p4:
3462 // A class is abstract if it contains or inherits at least one
3463 // pure virtual function for which the final overrider is pure
3464 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003466 //
3467 if (SO->second.size() != 1)
3468 continue;
3469
3470 if (!SO->second.front().Method->isPure())
3471 continue;
3472
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003473 if (!SeenPureMethods.insert(SO->second.front().Method))
3474 continue;
3475
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003476 Diag(SO->second.front().Method->getLocation(),
3477 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003478 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003479 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003480 }
3481
3482 if (!PureVirtualClassDiagSet)
3483 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3484 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003485}
3486
Anders Carlsson8211eff2009-03-24 01:19:16 +00003487namespace {
John McCall94c3b562010-08-18 09:41:07 +00003488struct AbstractUsageInfo {
3489 Sema &S;
3490 CXXRecordDecl *Record;
3491 CanQualType AbstractType;
3492 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003493
John McCall94c3b562010-08-18 09:41:07 +00003494 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3495 : S(S), Record(Record),
3496 AbstractType(S.Context.getCanonicalType(
3497 S.Context.getTypeDeclType(Record))),
3498 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003499
John McCall94c3b562010-08-18 09:41:07 +00003500 void DiagnoseAbstractType() {
3501 if (Invalid) return;
3502 S.DiagnoseAbstractType(Record);
3503 Invalid = true;
3504 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003505
John McCall94c3b562010-08-18 09:41:07 +00003506 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3507};
3508
3509struct CheckAbstractUsage {
3510 AbstractUsageInfo &Info;
3511 const NamedDecl *Ctx;
3512
3513 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3514 : Info(Info), Ctx(Ctx) {}
3515
3516 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3517 switch (TL.getTypeLocClass()) {
3518#define ABSTRACT_TYPELOC(CLASS, PARENT)
3519#define TYPELOC(CLASS, PARENT) \
3520 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3521#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003522 }
John McCall94c3b562010-08-18 09:41:07 +00003523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
John McCall94c3b562010-08-18 09:41:07 +00003525 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3526 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3527 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003528 if (!TL.getArg(I))
3529 continue;
3530
John McCall94c3b562010-08-18 09:41:07 +00003531 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3532 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003533 }
John McCall94c3b562010-08-18 09:41:07 +00003534 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003535
John McCall94c3b562010-08-18 09:41:07 +00003536 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3537 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCall94c3b562010-08-18 09:41:07 +00003540 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3541 // Visit the type parameters from a permissive context.
3542 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3543 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3544 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3545 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3546 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3547 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003548 }
John McCall94c3b562010-08-18 09:41:07 +00003549 }
Mike Stump1eb44332009-09-09 15:08:12 +00003550
John McCall94c3b562010-08-18 09:41:07 +00003551 // Visit pointee types from a permissive context.
3552#define CheckPolymorphic(Type) \
3553 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3554 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3555 }
3556 CheckPolymorphic(PointerTypeLoc)
3557 CheckPolymorphic(ReferenceTypeLoc)
3558 CheckPolymorphic(MemberPointerTypeLoc)
3559 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003560 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003561
John McCall94c3b562010-08-18 09:41:07 +00003562 /// Handle all the types we haven't given a more specific
3563 /// implementation for above.
3564 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3565 // Every other kind of type that we haven't called out already
3566 // that has an inner type is either (1) sugar or (2) contains that
3567 // inner type in some way as a subobject.
3568 if (TypeLoc Next = TL.getNextTypeLoc())
3569 return Visit(Next, Sel);
3570
3571 // If there's no inner type and we're in a permissive context,
3572 // don't diagnose.
3573 if (Sel == Sema::AbstractNone) return;
3574
3575 // Check whether the type matches the abstract type.
3576 QualType T = TL.getType();
3577 if (T->isArrayType()) {
3578 Sel = Sema::AbstractArrayType;
3579 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003580 }
John McCall94c3b562010-08-18 09:41:07 +00003581 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3582 if (CT != Info.AbstractType) return;
3583
3584 // It matched; do some magic.
3585 if (Sel == Sema::AbstractArrayType) {
3586 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3587 << T << TL.getSourceRange();
3588 } else {
3589 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3590 << Sel << T << TL.getSourceRange();
3591 }
3592 Info.DiagnoseAbstractType();
3593 }
3594};
3595
3596void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3597 Sema::AbstractDiagSelID Sel) {
3598 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3599}
3600
3601}
3602
3603/// Check for invalid uses of an abstract type in a method declaration.
3604static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3605 CXXMethodDecl *MD) {
3606 // No need to do the check on definitions, which require that
3607 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003608 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003609 return;
3610
3611 // For safety's sake, just ignore it if we don't have type source
3612 // information. This should never happen for non-implicit methods,
3613 // but...
3614 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3615 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3616}
3617
3618/// Check for invalid uses of an abstract type within a class definition.
3619static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3620 CXXRecordDecl *RD) {
3621 for (CXXRecordDecl::decl_iterator
3622 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3623 Decl *D = *I;
3624 if (D->isImplicit()) continue;
3625
3626 // Methods and method templates.
3627 if (isa<CXXMethodDecl>(D)) {
3628 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3629 } else if (isa<FunctionTemplateDecl>(D)) {
3630 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3631 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3632
3633 // Fields and static variables.
3634 } else if (isa<FieldDecl>(D)) {
3635 FieldDecl *FD = cast<FieldDecl>(D);
3636 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3637 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3638 } else if (isa<VarDecl>(D)) {
3639 VarDecl *VD = cast<VarDecl>(D);
3640 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3641 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3642
3643 // Nested classes and class templates.
3644 } else if (isa<CXXRecordDecl>(D)) {
3645 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3646 } else if (isa<ClassTemplateDecl>(D)) {
3647 CheckAbstractClassUsage(Info,
3648 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3649 }
3650 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003651}
3652
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003653/// \brief Perform semantic checks on a class definition that has been
3654/// completing, introducing implicitly-declared members, checking for
3655/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003656void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003657 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003658 return;
3659
John McCall94c3b562010-08-18 09:41:07 +00003660 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3661 AbstractUsageInfo Info(*this, Record);
3662 CheckAbstractClassUsage(Info, Record);
3663 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003664
3665 // If this is not an aggregate type and has no user-declared constructor,
3666 // complain about any non-static data members of reference or const scalar
3667 // type, since they will never get initializers.
3668 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003669 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3670 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003671 bool Complained = false;
3672 for (RecordDecl::field_iterator F = Record->field_begin(),
3673 FEnd = Record->field_end();
3674 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003675 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003676 continue;
3677
Douglas Gregor325e5932010-04-15 00:00:53 +00003678 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003679 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003680 if (!Complained) {
3681 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3682 << Record->getTagKind() << Record;
3683 Complained = true;
3684 }
3685
3686 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3687 << F->getType()->isReferenceType()
3688 << F->getDeclName();
3689 }
3690 }
3691 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003692
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003693 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003694 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003695
3696 if (Record->getIdentifier()) {
3697 // C++ [class.mem]p13:
3698 // If T is the name of a class, then each of the following shall have a
3699 // name different from T:
3700 // - every member of every anonymous union that is a member of class T.
3701 //
3702 // C++ [class.mem]p14:
3703 // In addition, if class T has a user-declared constructor (12.1), every
3704 // non-static data member of class T shall have a name different from T.
3705 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003706 R.first != R.second; ++R.first) {
3707 NamedDecl *D = *R.first;
3708 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3709 isa<IndirectFieldDecl>(D)) {
3710 Diag(D->getLocation(), diag::err_member_name_of_class)
3711 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003712 break;
3713 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003714 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003715 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003716
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003717 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003718 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003719 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003720 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003721 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3722 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3723 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003724
3725 // See if a method overloads virtual methods in a base
3726 /// class without overriding any.
3727 if (!Record->isDependentType()) {
3728 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3729 MEnd = Record->method_end();
3730 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003731 if (!(*M)->isStatic())
3732 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003733 }
3734 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003735
Richard Smith9f569cc2011-10-01 02:31:28 +00003736 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3737 // function that is not a constructor declares that member function to be
3738 // const. [...] The class of which that function is a member shall be
3739 // a literal type.
3740 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003741 // If the class has virtual bases, any constexpr members will already have
3742 // been diagnosed by the checks performed on the member declaration, so
3743 // suppress this (less useful) diagnostic.
3744 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3745 !Record->isLiteral() && !Record->getNumVBases()) {
3746 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3747 MEnd = Record->method_end();
3748 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003749 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003750 switch (Record->getTemplateSpecializationKind()) {
3751 case TSK_ImplicitInstantiation:
3752 case TSK_ExplicitInstantiationDeclaration:
3753 case TSK_ExplicitInstantiationDefinition:
3754 // If a template instantiates to a non-literal type, but its members
3755 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003756 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003757 continue;
3758
3759 case TSK_Undeclared:
3760 case TSK_ExplicitSpecialization:
3761 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3762 PDiag(diag::err_constexpr_method_non_literal));
3763 break;
3764 }
3765
3766 // Only produce one error per class.
3767 break;
3768 }
3769 }
3770 }
3771
Sebastian Redlf677ea32011-02-05 19:23:19 +00003772 // Declare inherited constructors. We do this eagerly here because:
3773 // - The standard requires an eager diagnostic for conflicting inherited
3774 // constructors from different classes.
3775 // - The lazy declaration of the other implicit constructors is so as to not
3776 // waste space and performance on classes that are not meant to be
3777 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3778 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003779 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003780
Sean Hunteb88ae52011-05-23 21:07:59 +00003781 if (!Record->isDependentType())
3782 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003783}
3784
3785void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003786 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3787 ME = Record->method_end();
3788 MI != ME; ++MI) {
3789 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3790 switch (getSpecialMember(*MI)) {
3791 case CXXDefaultConstructor:
3792 CheckExplicitlyDefaultedDefaultConstructor(
3793 cast<CXXConstructorDecl>(*MI));
3794 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003795
Sean Huntcb45a0f2011-05-12 22:46:25 +00003796 case CXXDestructor:
3797 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3798 break;
3799
3800 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003801 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3802 break;
3803
Sean Huntcb45a0f2011-05-12 22:46:25 +00003804 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003805 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003806 break;
3807
Sean Hunt82713172011-05-25 23:16:36 +00003808 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003809 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003810 break;
3811
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003812 case CXXMoveAssignment:
3813 CheckExplicitlyDefaultedMoveAssignment(*MI);
3814 break;
3815
3816 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003817 llvm_unreachable("non-special member explicitly defaulted!");
3818 }
Sean Hunt001cad92011-05-10 00:49:42 +00003819 }
3820 }
3821
Sean Hunt001cad92011-05-10 00:49:42 +00003822}
3823
3824void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3825 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3826
3827 // Whether this was the first-declared instance of the constructor.
3828 // This affects whether we implicitly add an exception spec (and, eventually,
3829 // constexpr). It is also ill-formed to explicitly default a constructor such
3830 // that it would be deleted. (C++0x [decl.fct.def.default])
3831 bool First = CD == CD->getCanonicalDecl();
3832
Sean Hunt49634cf2011-05-13 06:10:58 +00003833 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003834 if (CD->getNumParams() != 0) {
3835 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3836 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003837 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003838 }
3839
3840 ImplicitExceptionSpecification Spec
3841 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3842 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003843 if (EPI.ExceptionSpecType == EST_Delayed) {
3844 // Exception specification depends on some deferred part of the class. We'll
3845 // try again when the class's definition has been fully processed.
3846 return;
3847 }
Sean Hunt001cad92011-05-10 00:49:42 +00003848 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3849 *ExceptionType = Context.getFunctionType(
3850 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3851
Richard Smith61802452011-12-22 02:22:31 +00003852 // C++11 [dcl.fct.def.default]p2:
3853 // An explicitly-defaulted function may be declared constexpr only if it
3854 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003855 // Do not apply this rule to templates, since core issue 1358 makes such
3856 // functions always instantiate to constexpr functions.
3857 if (CD->isConstexpr() &&
3858 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003859 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3860 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3861 << CXXDefaultConstructor;
3862 HadError = true;
3863 }
3864 }
3865 // and may have an explicit exception-specification only if it is compatible
3866 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003867 if (CtorType->hasExceptionSpec()) {
3868 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003869 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003870 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003871 PDiag(),
3872 ExceptionType, SourceLocation(),
3873 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003874 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003875 }
Richard Smith61802452011-12-22 02:22:31 +00003876 }
3877
3878 // If a function is explicitly defaulted on its first declaration,
3879 if (First) {
3880 // -- it is implicitly considered to be constexpr if the implicit
3881 // definition would be,
3882 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3883
3884 // -- it is implicitly considered to have the same
3885 // exception-specification as if it had been implicitly declared
3886 //
3887 // FIXME: a compatible, but different, explicit exception specification
3888 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003889 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithe653ba22012-02-26 00:31:33 +00003890
3891 // Such a function is also trivial if the implicitly-declared function
3892 // would have been.
3893 CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
Sean Hunt001cad92011-05-10 00:49:42 +00003894 }
Sean Huntca46d132011-05-12 03:51:48 +00003895
Sean Hunt49634cf2011-05-13 06:10:58 +00003896 if (HadError) {
3897 CD->setInvalidDecl();
3898 return;
3899 }
3900
Sean Hunte16da072011-10-10 06:18:57 +00003901 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003902 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003903 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003904 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003905 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003906 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003907 CD->setInvalidDecl();
3908 }
3909 }
3910}
3911
3912void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3913 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3914
3915 // Whether this was the first-declared instance of the constructor.
3916 bool First = CD == CD->getCanonicalDecl();
3917
3918 bool HadError = false;
3919 if (CD->getNumParams() != 1) {
3920 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3921 << CD->getSourceRange();
3922 HadError = true;
3923 }
3924
3925 ImplicitExceptionSpecification Spec(Context);
3926 bool Const;
3927 llvm::tie(Spec, Const) =
3928 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3929
3930 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3931 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3932 *ExceptionType = Context.getFunctionType(
3933 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3934
3935 // Check for parameter type matching.
3936 // This is a copy ctor so we know it's a cv-qualified reference to T.
3937 QualType ArgType = CtorType->getArgType(0);
3938 if (ArgType->getPointeeType().isVolatileQualified()) {
3939 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3940 HadError = true;
3941 }
3942 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3943 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3944 HadError = true;
3945 }
3946
Richard Smith61802452011-12-22 02:22:31 +00003947 // C++11 [dcl.fct.def.default]p2:
3948 // An explicitly-defaulted function may be declared constexpr only if it
3949 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003950 // Do not apply this rule to templates, since core issue 1358 makes such
3951 // functions always instantiate to constexpr functions.
3952 if (CD->isConstexpr() &&
3953 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003954 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3955 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3956 << CXXCopyConstructor;
3957 HadError = true;
3958 }
3959 }
3960 // and may have an explicit exception-specification only if it is compatible
3961 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003962 if (CtorType->hasExceptionSpec()) {
3963 if (CheckEquivalentExceptionSpec(
3964 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003965 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003966 PDiag(),
3967 ExceptionType, SourceLocation(),
3968 CtorType, CD->getLocation())) {
3969 HadError = true;
3970 }
Richard Smith61802452011-12-22 02:22:31 +00003971 }
3972
3973 // If a function is explicitly defaulted on its first declaration,
3974 if (First) {
3975 // -- it is implicitly considered to be constexpr if the implicit
3976 // definition would be,
3977 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3978
3979 // -- it is implicitly considered to have the same
3980 // exception-specification as if it had been implicitly declared, and
3981 //
3982 // FIXME: a compatible, but different, explicit exception specification
3983 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003984 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003985
3986 // -- [...] it shall have the same parameter type as if it had been
3987 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003988 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00003989
3990 // Such a function is also trivial if the implicitly-declared function
3991 // would have been.
3992 CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00003993 }
3994
3995 if (HadError) {
3996 CD->setInvalidDecl();
3997 return;
3998 }
3999
Sean Huntc32d6842011-10-11 04:55:36 +00004000 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004001 if (First) {
4002 CD->setDeletedAsWritten();
4003 } else {
4004 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004005 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004006 CD->setInvalidDecl();
4007 }
Sean Huntca46d132011-05-12 03:51:48 +00004008 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004009}
Sean Hunt001cad92011-05-10 00:49:42 +00004010
Sean Hunt2b188082011-05-14 05:23:28 +00004011void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4012 assert(MD->isExplicitlyDefaulted());
4013
4014 // Whether this was the first-declared instance of the operator
4015 bool First = MD == MD->getCanonicalDecl();
4016
4017 bool HadError = false;
4018 if (MD->getNumParams() != 1) {
4019 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4020 << MD->getSourceRange();
4021 HadError = true;
4022 }
4023
4024 QualType ReturnType =
4025 MD->getType()->getAs<FunctionType>()->getResultType();
4026 if (!ReturnType->isLValueReferenceType() ||
4027 !Context.hasSameType(
4028 Context.getCanonicalType(ReturnType->getPointeeType()),
4029 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4030 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4031 HadError = true;
4032 }
4033
4034 ImplicitExceptionSpecification Spec(Context);
4035 bool Const;
4036 llvm::tie(Spec, Const) =
4037 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4038
4039 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4040 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4041 *ExceptionType = Context.getFunctionType(
4042 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4043
Sean Hunt2b188082011-05-14 05:23:28 +00004044 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004045 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004046 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004047 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004048 } else {
4049 if (ArgType->getPointeeType().isVolatileQualified()) {
4050 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4051 HadError = true;
4052 }
4053 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4054 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4055 HadError = true;
4056 }
Sean Hunt2b188082011-05-14 05:23:28 +00004057 }
Sean Huntbe631222011-05-17 20:44:43 +00004058
Sean Hunt2b188082011-05-14 05:23:28 +00004059 if (OperType->getTypeQuals()) {
4060 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4061 HadError = true;
4062 }
4063
4064 if (OperType->hasExceptionSpec()) {
4065 if (CheckEquivalentExceptionSpec(
4066 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004067 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004068 PDiag(),
4069 ExceptionType, SourceLocation(),
4070 OperType, MD->getLocation())) {
4071 HadError = true;
4072 }
Richard Smith61802452011-12-22 02:22:31 +00004073 }
4074 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004075 // We set the declaration to have the computed exception spec here.
4076 // We duplicate the one parameter type.
4077 EPI.RefQualifier = OperType->getRefQualifier();
4078 EPI.ExtInfo = OperType->getExtInfo();
4079 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004080
4081 // Such a function is also trivial if the implicitly-declared function
4082 // would have been.
4083 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
Sean Hunt2b188082011-05-14 05:23:28 +00004084 }
4085
4086 if (HadError) {
4087 MD->setInvalidDecl();
4088 return;
4089 }
4090
Richard Smith7d5088a2012-02-18 02:02:13 +00004091 if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
Sean Hunt2b188082011-05-14 05:23:28 +00004092 if (First) {
4093 MD->setDeletedAsWritten();
4094 } else {
4095 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004096 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004097 MD->setInvalidDecl();
4098 }
4099 }
4100}
4101
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004102void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4103 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4104
4105 // Whether this was the first-declared instance of the constructor.
4106 bool First = CD == CD->getCanonicalDecl();
4107
4108 bool HadError = false;
4109 if (CD->getNumParams() != 1) {
4110 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4111 << CD->getSourceRange();
4112 HadError = true;
4113 }
4114
4115 ImplicitExceptionSpecification Spec(
4116 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4117
4118 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4119 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4120 *ExceptionType = Context.getFunctionType(
4121 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4122
4123 // Check for parameter type matching.
4124 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4125 QualType ArgType = CtorType->getArgType(0);
4126 if (ArgType->getPointeeType().isVolatileQualified()) {
4127 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4128 HadError = true;
4129 }
4130 if (ArgType->getPointeeType().isConstQualified()) {
4131 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4132 HadError = true;
4133 }
4134
Richard Smith61802452011-12-22 02:22:31 +00004135 // C++11 [dcl.fct.def.default]p2:
4136 // An explicitly-defaulted function may be declared constexpr only if it
4137 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004138 // Do not apply this rule to templates, since core issue 1358 makes such
4139 // functions always instantiate to constexpr functions.
4140 if (CD->isConstexpr() &&
4141 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004142 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4143 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4144 << CXXMoveConstructor;
4145 HadError = true;
4146 }
4147 }
4148 // and may have an explicit exception-specification only if it is compatible
4149 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004150 if (CtorType->hasExceptionSpec()) {
4151 if (CheckEquivalentExceptionSpec(
4152 PDiag(diag::err_incorrect_defaulted_exception_spec)
4153 << CXXMoveConstructor,
4154 PDiag(),
4155 ExceptionType, SourceLocation(),
4156 CtorType, CD->getLocation())) {
4157 HadError = true;
4158 }
Richard Smith61802452011-12-22 02:22:31 +00004159 }
4160
4161 // If a function is explicitly defaulted on its first declaration,
4162 if (First) {
4163 // -- it is implicitly considered to be constexpr if the implicit
4164 // definition would be,
4165 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4166
4167 // -- it is implicitly considered to have the same
4168 // exception-specification as if it had been implicitly declared, and
4169 //
4170 // FIXME: a compatible, but different, explicit exception specification
4171 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004172 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004173
4174 // -- [...] it shall have the same parameter type as if it had been
4175 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004176 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004177
4178 // Such a function is also trivial if the implicitly-declared function
4179 // would have been.
4180 CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004181 }
4182
4183 if (HadError) {
4184 CD->setInvalidDecl();
4185 return;
4186 }
4187
Sean Hunt769bb2d2011-10-11 06:43:29 +00004188 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004189 if (First) {
4190 CD->setDeletedAsWritten();
4191 } else {
4192 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4193 << CXXMoveConstructor;
4194 CD->setInvalidDecl();
4195 }
4196 }
4197}
4198
4199void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4200 assert(MD->isExplicitlyDefaulted());
4201
4202 // Whether this was the first-declared instance of the operator
4203 bool First = MD == MD->getCanonicalDecl();
4204
4205 bool HadError = false;
4206 if (MD->getNumParams() != 1) {
4207 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4208 << MD->getSourceRange();
4209 HadError = true;
4210 }
4211
4212 QualType ReturnType =
4213 MD->getType()->getAs<FunctionType>()->getResultType();
4214 if (!ReturnType->isLValueReferenceType() ||
4215 !Context.hasSameType(
4216 Context.getCanonicalType(ReturnType->getPointeeType()),
4217 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4218 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4219 HadError = true;
4220 }
4221
4222 ImplicitExceptionSpecification Spec(
4223 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4224
4225 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4226 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4227 *ExceptionType = Context.getFunctionType(
4228 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4229
4230 QualType ArgType = OperType->getArgType(0);
4231 if (!ArgType->isRValueReferenceType()) {
4232 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4233 HadError = true;
4234 } else {
4235 if (ArgType->getPointeeType().isVolatileQualified()) {
4236 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4237 HadError = true;
4238 }
4239 if (ArgType->getPointeeType().isConstQualified()) {
4240 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4241 HadError = true;
4242 }
4243 }
4244
4245 if (OperType->getTypeQuals()) {
4246 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4247 HadError = true;
4248 }
4249
4250 if (OperType->hasExceptionSpec()) {
4251 if (CheckEquivalentExceptionSpec(
4252 PDiag(diag::err_incorrect_defaulted_exception_spec)
4253 << CXXMoveAssignment,
4254 PDiag(),
4255 ExceptionType, SourceLocation(),
4256 OperType, MD->getLocation())) {
4257 HadError = true;
4258 }
Richard Smith61802452011-12-22 02:22:31 +00004259 }
4260 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004261 // We set the declaration to have the computed exception spec here.
4262 // We duplicate the one parameter type.
4263 EPI.RefQualifier = OperType->getRefQualifier();
4264 EPI.ExtInfo = OperType->getExtInfo();
4265 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004266
4267 // Such a function is also trivial if the implicitly-declared function
4268 // would have been.
4269 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004270 }
4271
4272 if (HadError) {
4273 MD->setInvalidDecl();
4274 return;
4275 }
4276
Richard Smith7d5088a2012-02-18 02:02:13 +00004277 if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004278 if (First) {
4279 MD->setDeletedAsWritten();
4280 } else {
4281 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4282 << CXXMoveAssignment;
4283 MD->setInvalidDecl();
4284 }
4285 }
4286}
4287
Sean Huntcb45a0f2011-05-12 22:46:25 +00004288void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4289 assert(DD->isExplicitlyDefaulted());
4290
4291 // Whether this was the first-declared instance of the destructor.
4292 bool First = DD == DD->getCanonicalDecl();
4293
4294 ImplicitExceptionSpecification Spec
4295 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4296 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4297 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4298 *ExceptionType = Context.getFunctionType(
4299 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4300
4301 if (DtorType->hasExceptionSpec()) {
4302 if (CheckEquivalentExceptionSpec(
4303 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004304 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004305 PDiag(),
4306 ExceptionType, SourceLocation(),
4307 DtorType, DD->getLocation())) {
4308 DD->setInvalidDecl();
4309 return;
4310 }
Richard Smith61802452011-12-22 02:22:31 +00004311 }
4312 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004313 // We set the declaration to have the computed exception spec here.
4314 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004315 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004316 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004317
4318 // Such a function is also trivial if the implicitly-declared function
4319 // would have been.
4320 DD->setTrivial(DD->getParent()->hasTrivialDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321 }
4322
Richard Smith7d5088a2012-02-18 02:02:13 +00004323 if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004324 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004325 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004326 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004327 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004328 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004329 DD->setInvalidDecl();
4330 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004331 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004332}
4333
Richard Smith7d5088a2012-02-18 02:02:13 +00004334namespace {
4335struct SpecialMemberDeletionInfo {
4336 Sema &S;
4337 CXXMethodDecl *MD;
4338 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004339 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004340
4341 // Properties of the special member, computed for convenience.
4342 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4343 SourceLocation Loc;
4344
4345 bool AllFieldsAreConst;
4346
4347 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004348 Sema::CXXSpecialMember CSM, bool Diagnose)
4349 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004350 IsConstructor(false), IsAssignment(false), IsMove(false),
4351 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4352 AllFieldsAreConst(true) {
4353 switch (CSM) {
4354 case Sema::CXXDefaultConstructor:
4355 case Sema::CXXCopyConstructor:
4356 IsConstructor = true;
4357 break;
4358 case Sema::CXXMoveConstructor:
4359 IsConstructor = true;
4360 IsMove = true;
4361 break;
4362 case Sema::CXXCopyAssignment:
4363 IsAssignment = true;
4364 break;
4365 case Sema::CXXMoveAssignment:
4366 IsAssignment = true;
4367 IsMove = true;
4368 break;
4369 case Sema::CXXDestructor:
4370 break;
4371 case Sema::CXXInvalid:
4372 llvm_unreachable("invalid special member kind");
4373 }
4374
4375 if (MD->getNumParams()) {
4376 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4377 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4378 }
4379 }
4380
4381 bool inUnion() const { return MD->getParent()->isUnion(); }
4382
4383 /// Look up the corresponding special member in the given class.
4384 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4385 unsigned TQ = MD->getTypeQualifiers();
4386 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4387 MD->getRefQualifier() == RQ_RValue,
4388 TQ & Qualifiers::Const,
4389 TQ & Qualifiers::Volatile);
4390 }
4391
Richard Smith6c4c36c2012-03-30 20:53:28 +00004392 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004393
Richard Smith6c4c36c2012-03-30 20:53:28 +00004394 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004395 bool shouldDeleteForField(FieldDecl *FD);
4396 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004397
4398 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4399 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4400 Sema::SpecialMemberOverloadResult *SMOR,
4401 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004402
4403 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004404};
4405}
4406
John McCall12d8d802012-04-09 20:53:23 +00004407/// Is the given special member inaccessible when used on the given
4408/// sub-object.
4409bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4410 CXXMethodDecl *target) {
4411 /// If we're operating on a base class, the object type is the
4412 /// type of this special member.
4413 QualType objectTy;
4414 AccessSpecifier access = target->getAccess();;
4415 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4416 objectTy = S.Context.getTypeDeclType(MD->getParent());
4417 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4418
4419 // If we're operating on a field, the object type is the type of the field.
4420 } else {
4421 objectTy = S.Context.getTypeDeclType(target->getParent());
4422 }
4423
4424 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4425}
4426
Richard Smith6c4c36c2012-03-30 20:53:28 +00004427/// Check whether we should delete a special member due to the implicit
4428/// definition containing a call to a special member of a subobject.
4429bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4430 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4431 bool IsDtorCallInCtor) {
4432 CXXMethodDecl *Decl = SMOR->getMethod();
4433 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4434
4435 int DiagKind = -1;
4436
4437 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4438 DiagKind = !Decl ? 0 : 1;
4439 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4440 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004441 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004442 DiagKind = 3;
4443 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4444 !Decl->isTrivial()) {
4445 // A member of a union must have a trivial corresponding special member.
4446 // As a weird special case, a destructor call from a union's constructor
4447 // must be accessible and non-deleted, but need not be trivial. Such a
4448 // destructor is never actually called, but is semantically checked as
4449 // if it were.
4450 DiagKind = 4;
4451 }
4452
4453 if (DiagKind == -1)
4454 return false;
4455
4456 if (Diagnose) {
4457 if (Field) {
4458 S.Diag(Field->getLocation(),
4459 diag::note_deleted_special_member_class_subobject)
4460 << CSM << MD->getParent() << /*IsField*/true
4461 << Field << DiagKind << IsDtorCallInCtor;
4462 } else {
4463 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4464 S.Diag(Base->getLocStart(),
4465 diag::note_deleted_special_member_class_subobject)
4466 << CSM << MD->getParent() << /*IsField*/false
4467 << Base->getType() << DiagKind << IsDtorCallInCtor;
4468 }
4469
4470 if (DiagKind == 1)
4471 S.NoteDeletedFunction(Decl);
4472 // FIXME: Explain inaccessibility if DiagKind == 3.
4473 }
4474
4475 return true;
4476}
4477
Richard Smith9a561d52012-02-26 09:11:52 +00004478/// Check whether we should delete a special member function due to having a
4479/// direct or virtual base class or static data member of class type M.
4480bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith6c4c36c2012-03-30 20:53:28 +00004481 CXXRecordDecl *Class, Subobject Subobj) {
4482 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004483
4484 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004485 // -- any direct or virtual base class, or non-static data member with no
4486 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004487 // either M has no default constructor or overload resolution as applied
4488 // to M's default constructor results in an ambiguity or in a function
4489 // that is deleted or inaccessible
4490 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4491 // -- a direct or virtual base class B that cannot be copied/moved because
4492 // overload resolution, as applied to B's corresponding special member,
4493 // results in an ambiguity or a function that is deleted or inaccessible
4494 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004495 // C++11 [class.dtor]p5:
4496 // -- any direct or virtual base class [...] has a type with a destructor
4497 // that is deleted or inaccessible
4498 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004499 Field && Field->hasInClassInitializer()) &&
4500 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4501 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004502
Richard Smith6c4c36c2012-03-30 20:53:28 +00004503 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4504 // -- any direct or virtual base class or non-static data member has a
4505 // type with a destructor that is deleted or inaccessible
4506 if (IsConstructor) {
4507 Sema::SpecialMemberOverloadResult *SMOR =
4508 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4509 false, false, false, false, false);
4510 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4511 return true;
4512 }
4513
Richard Smith9a561d52012-02-26 09:11:52 +00004514 return false;
4515}
4516
4517/// Check whether we should delete a special member function due to the class
4518/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004519bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004520 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4521 return shouldDeleteForClassSubobject(BaseClass, Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004522}
4523
4524/// Check whether we should delete a special member function due to the class
4525/// having a particular non-static data member.
4526bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4527 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4528 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4529
4530 if (CSM == Sema::CXXDefaultConstructor) {
4531 // For a default constructor, all references must be initialized in-class
4532 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004533 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4534 if (Diagnose)
4535 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4536 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004537 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004538 }
Richard Smith79363f52012-02-27 06:07:25 +00004539 // C++11 [class.ctor]p5: any non-variant non-static data member of
4540 // const-qualified type (or array thereof) with no
4541 // brace-or-equal-initializer does not have a user-provided default
4542 // constructor.
4543 if (!inUnion() && FieldType.isConstQualified() &&
4544 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004545 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4546 if (Diagnose)
4547 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4548 << MD->getParent() << FD << FieldType << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004549 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004550 }
4551
4552 if (inUnion() && !FieldType.isConstQualified())
4553 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004554 } else if (CSM == Sema::CXXCopyConstructor) {
4555 // For a copy constructor, data members must not be of rvalue reference
4556 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004557 if (FieldType->isRValueReferenceType()) {
4558 if (Diagnose)
4559 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4560 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004561 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004562 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004563 } else if (IsAssignment) {
4564 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004565 if (FieldType->isReferenceType()) {
4566 if (Diagnose)
4567 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4568 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004569 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004570 }
4571 if (!FieldRecord && FieldType.isConstQualified()) {
4572 // C++11 [class.copy]p23:
4573 // -- a non-static data member of const non-class type (or array thereof)
4574 if (Diagnose)
4575 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4576 << IsMove << MD->getParent() << FD << FieldType << /*Const*/1;
4577 return true;
4578 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004579 }
4580
4581 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004582 // Some additional restrictions exist on the variant members.
4583 if (!inUnion() && FieldRecord->isUnion() &&
4584 FieldRecord->isAnonymousStructOrUnion()) {
4585 bool AllVariantFieldsAreConst = true;
4586
Richard Smithdf8dc862012-03-29 19:00:10 +00004587 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004588 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4589 UE = FieldRecord->field_end();
4590 UI != UE; ++UI) {
4591 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004592
4593 if (!UnionFieldType.isConstQualified())
4594 AllVariantFieldsAreConst = false;
4595
Richard Smith9a561d52012-02-26 09:11:52 +00004596 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4597 if (UnionFieldRecord &&
4598 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4599 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004600 }
4601
4602 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004603 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004604 FieldRecord->field_begin() != FieldRecord->field_end()) {
4605 if (Diagnose)
4606 S.Diag(FieldRecord->getLocation(),
4607 diag::note_deleted_default_ctor_all_const)
4608 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004609 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004610 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004611
Richard Smithdf8dc862012-03-29 19:00:10 +00004612 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004613 // This is technically non-conformant, but sanity demands it.
4614 return false;
4615 }
4616
Richard Smithdf8dc862012-03-29 19:00:10 +00004617 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4618 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004619 }
4620
4621 return false;
4622}
4623
4624/// C++11 [class.ctor] p5:
4625/// A defaulted default constructor for a class X is defined as deleted if
4626/// X is a union and all of its variant members are of const-qualified type.
4627bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004628 // This is a silly definition, because it gives an empty union a deleted
4629 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004630 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4631 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4632 if (Diagnose)
4633 S.Diag(MD->getParent()->getLocation(),
4634 diag::note_deleted_default_ctor_all_const)
4635 << MD->getParent() << /*not anonymous union*/0;
4636 return true;
4637 }
4638 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004639}
4640
4641/// Determine whether a defaulted special member function should be defined as
4642/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4643/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004644bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4645 bool Diagnose) {
Sean Hunte16da072011-10-10 06:18:57 +00004646 assert(!MD->isInvalidDecl());
4647 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004648 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004649 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004650 return false;
4651
Richard Smith7d5088a2012-02-18 02:02:13 +00004652 // C++11 [expr.lambda.prim]p19:
4653 // The closure type associated with a lambda-expression has a
4654 // deleted (8.4.3) default constructor and a deleted copy
4655 // assignment operator.
4656 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004657 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4658 if (Diagnose)
4659 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004661 }
4662
Richard Smith5bdaac52012-04-02 20:59:25 +00004663 // For an anonymous struct or union, the copy and assignment special members
4664 // will never be used, so skip the check. For an anonymous union declared at
4665 // namespace scope, the constructor and destructor are used.
4666 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4667 RD->isAnonymousStructOrUnion())
4668 return false;
4669
Richard Smith6c4c36c2012-03-30 20:53:28 +00004670 // C++11 [class.copy]p7, p18:
4671 // If the class definition declares a move constructor or move assignment
4672 // operator, an implicitly declared copy constructor or copy assignment
4673 // operator is defined as deleted.
4674 if (MD->isImplicit() &&
4675 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4676 CXXMethodDecl *UserDeclaredMove = 0;
4677
4678 // In Microsoft mode, a user-declared move only causes the deletion of the
4679 // corresponding copy operation, not both copy operations.
4680 if (RD->hasUserDeclaredMoveConstructor() &&
4681 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4682 if (!Diagnose) return true;
4683 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004684 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004685 } else if (RD->hasUserDeclaredMoveAssignment() &&
4686 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4687 if (!Diagnose) return true;
4688 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004689 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004690 }
4691
4692 if (UserDeclaredMove) {
4693 Diag(UserDeclaredMove->getLocation(),
4694 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004695 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004696 << UserDeclaredMove->isMoveAssignmentOperator();
4697 return true;
4698 }
4699 }
Sean Hunte16da072011-10-10 06:18:57 +00004700
Richard Smith5bdaac52012-04-02 20:59:25 +00004701 // Do access control from the special member function
4702 ContextRAII MethodContext(*this, MD);
4703
Richard Smith9a561d52012-02-26 09:11:52 +00004704 // C++11 [class.dtor]p5:
4705 // -- for a virtual destructor, lookup of the non-array deallocation function
4706 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004707 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004708 FunctionDecl *OperatorDelete = 0;
4709 DeclarationName Name =
4710 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4711 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004712 OperatorDelete, false)) {
4713 if (Diagnose)
4714 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004715 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004716 }
Richard Smith9a561d52012-02-26 09:11:52 +00004717 }
4718
Richard Smith6c4c36c2012-03-30 20:53:28 +00004719 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004720
Sean Huntcdee3fe2011-05-11 22:34:38 +00004721 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004722 BE = RD->bases_end(); BI != BE; ++BI)
4723 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004724 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004725 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004726
4727 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004728 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004729 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004730 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004731
4732 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004733 FE = RD->field_end(); FI != FE; ++FI)
4734 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4735 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004736 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004737
Richard Smith7d5088a2012-02-18 02:02:13 +00004738 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004739 return true;
4740
4741 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004742}
4743
4744/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004745namespace {
4746 struct FindHiddenVirtualMethodData {
4747 Sema *S;
4748 CXXMethodDecl *Method;
4749 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004750 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004751 };
4752}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004753
4754/// \brief Member lookup function that determines whether a given C++
4755/// method overloads virtual methods in a base class without overriding any,
4756/// to be used with CXXRecordDecl::lookupInBases().
4757static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4758 CXXBasePath &Path,
4759 void *UserData) {
4760 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4761
4762 FindHiddenVirtualMethodData &Data
4763 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4764
4765 DeclarationName Name = Data.Method->getDeclName();
4766 assert(Name.getNameKind() == DeclarationName::Identifier);
4767
4768 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004769 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004770 for (Path.Decls = BaseRecord->lookup(Name);
4771 Path.Decls.first != Path.Decls.second;
4772 ++Path.Decls.first) {
4773 NamedDecl *D = *Path.Decls.first;
4774 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004775 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004776 foundSameNameMethod = true;
4777 // Interested only in hidden virtual methods.
4778 if (!MD->isVirtual())
4779 continue;
4780 // If the method we are checking overrides a method from its base
4781 // don't warn about the other overloaded methods.
4782 if (!Data.S->IsOverload(Data.Method, MD, false))
4783 return true;
4784 // Collect the overload only if its hidden.
4785 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4786 overloadedMethods.push_back(MD);
4787 }
4788 }
4789
4790 if (foundSameNameMethod)
4791 Data.OverloadedMethods.append(overloadedMethods.begin(),
4792 overloadedMethods.end());
4793 return foundSameNameMethod;
4794}
4795
4796/// \brief See if a method overloads virtual methods in a base class without
4797/// overriding any.
4798void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4799 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004800 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004801 return;
4802 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4803 return;
4804
4805 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4806 /*bool RecordPaths=*/false,
4807 /*bool DetectVirtual=*/false);
4808 FindHiddenVirtualMethodData Data;
4809 Data.Method = MD;
4810 Data.S = this;
4811
4812 // Keep the base methods that were overriden or introduced in the subclass
4813 // by 'using' in a set. A base method not in this set is hidden.
4814 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4815 res.first != res.second; ++res.first) {
4816 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4817 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4818 E = MD->end_overridden_methods();
4819 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004820 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004821 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4822 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004823 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004824 }
4825
4826 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4827 !Data.OverloadedMethods.empty()) {
4828 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4829 << MD << (Data.OverloadedMethods.size() > 1);
4830
4831 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4832 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4833 Diag(overloadedMD->getLocation(),
4834 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4835 }
4836 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004837}
4838
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004839void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004840 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004841 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004842 SourceLocation RBrac,
4843 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004844 if (!TagDecl)
4845 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Douglas Gregor42af25f2009-05-11 19:58:34 +00004847 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004848
David Blaikie77b6de02011-09-22 02:58:26 +00004849 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004850 // strict aliasing violation!
4851 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004852 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004853
Douglas Gregor23c94db2010-07-02 17:43:08 +00004854 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004855 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004856}
4857
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004858/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4859/// special functions, such as the default constructor, copy
4860/// constructor, or destructor, to the given C++ class (C++
4861/// [special]p1). This routine can only be executed just before the
4862/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004863void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004864 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004865 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004866
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004867 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004868 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004869
David Blaikie4e4d0842012-03-11 07:00:24 +00004870 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004871 ++ASTContext::NumImplicitMoveConstructors;
4872
Douglas Gregora376d102010-07-02 21:50:04 +00004873 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4874 ++ASTContext::NumImplicitCopyAssignmentOperators;
4875
4876 // If we have a dynamic class, then the copy assignment operator may be
4877 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4878 // it shows up in the right place in the vtable and that we diagnose
4879 // problems with the implicit exception specification.
4880 if (ClassDecl->isDynamicClass())
4881 DeclareImplicitCopyAssignment(ClassDecl);
4882 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004883
Richard Smith1c931be2012-04-02 18:40:40 +00004884 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004885 ++ASTContext::NumImplicitMoveAssignmentOperators;
4886
4887 // Likewise for the move assignment operator.
4888 if (ClassDecl->isDynamicClass())
4889 DeclareImplicitMoveAssignment(ClassDecl);
4890 }
4891
Douglas Gregor4923aa22010-07-02 20:37:36 +00004892 if (!ClassDecl->hasUserDeclaredDestructor()) {
4893 ++ASTContext::NumImplicitDestructors;
4894
4895 // If we have a dynamic class, then the destructor may be virtual, so we
4896 // have to declare the destructor immediately. This ensures that, e.g., it
4897 // shows up in the right place in the vtable and that we diagnose problems
4898 // with the implicit exception specification.
4899 if (ClassDecl->isDynamicClass())
4900 DeclareImplicitDestructor(ClassDecl);
4901 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004902}
4903
Francois Pichet8387e2a2011-04-22 22:18:13 +00004904void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4905 if (!D)
4906 return;
4907
4908 int NumParamList = D->getNumTemplateParameterLists();
4909 for (int i = 0; i < NumParamList; i++) {
4910 TemplateParameterList* Params = D->getTemplateParameterList(i);
4911 for (TemplateParameterList::iterator Param = Params->begin(),
4912 ParamEnd = Params->end();
4913 Param != ParamEnd; ++Param) {
4914 NamedDecl *Named = cast<NamedDecl>(*Param);
4915 if (Named->getDeclName()) {
4916 S->AddDecl(Named);
4917 IdResolver.AddDecl(Named);
4918 }
4919 }
4920 }
4921}
4922
John McCalld226f652010-08-21 09:40:31 +00004923void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004924 if (!D)
4925 return;
4926
4927 TemplateParameterList *Params = 0;
4928 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4929 Params = Template->getTemplateParameters();
4930 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4931 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4932 Params = PartialSpec->getTemplateParameters();
4933 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004934 return;
4935
Douglas Gregor6569d682009-05-27 23:11:45 +00004936 for (TemplateParameterList::iterator Param = Params->begin(),
4937 ParamEnd = Params->end();
4938 Param != ParamEnd; ++Param) {
4939 NamedDecl *Named = cast<NamedDecl>(*Param);
4940 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004941 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004942 IdResolver.AddDecl(Named);
4943 }
4944 }
4945}
4946
John McCalld226f652010-08-21 09:40:31 +00004947void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004948 if (!RecordD) return;
4949 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004950 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004951 PushDeclContext(S, Record);
4952}
4953
John McCalld226f652010-08-21 09:40:31 +00004954void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004955 if (!RecordD) return;
4956 PopDeclContext();
4957}
4958
Douglas Gregor72b505b2008-12-16 21:30:33 +00004959/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4960/// parsing a top-level (non-nested) C++ class, and we are now
4961/// parsing those parts of the given Method declaration that could
4962/// not be parsed earlier (C++ [class.mem]p2), such as default
4963/// arguments. This action should enter the scope of the given
4964/// Method declaration as if we had just parsed the qualified method
4965/// name. However, it should not bring the parameters into scope;
4966/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004967void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004968}
4969
4970/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4971/// C++ method declaration. We're (re-)introducing the given
4972/// function parameter into scope for use in parsing later parts of
4973/// the method declaration. For example, we could see an
4974/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004975void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004976 if (!ParamD)
4977 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004978
John McCalld226f652010-08-21 09:40:31 +00004979 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004980
4981 // If this parameter has an unparsed default argument, clear it out
4982 // to make way for the parsed default argument.
4983 if (Param->hasUnparsedDefaultArg())
4984 Param->setDefaultArg(0);
4985
John McCalld226f652010-08-21 09:40:31 +00004986 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004987 if (Param->getDeclName())
4988 IdResolver.AddDecl(Param);
4989}
4990
4991/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4992/// processing the delayed method declaration for Method. The method
4993/// declaration is now considered finished. There may be a separate
4994/// ActOnStartOfFunctionDef action later (not necessarily
4995/// immediately!) for this method, if it was also defined inside the
4996/// class body.
John McCalld226f652010-08-21 09:40:31 +00004997void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004998 if (!MethodD)
4999 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005001 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005002
John McCalld226f652010-08-21 09:40:31 +00005003 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005004
5005 // Now that we have our default arguments, check the constructor
5006 // again. It could produce additional diagnostics or affect whether
5007 // the class has implicitly-declared destructors, among other
5008 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005009 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5010 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005011
5012 // Check the default arguments, which we may have added.
5013 if (!Method->isInvalidDecl())
5014 CheckCXXDefaultArguments(Method);
5015}
5016
Douglas Gregor42a552f2008-11-05 20:51:48 +00005017/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005018/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005019/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005020/// emit diagnostics and set the invalid bit to true. In any case, the type
5021/// will be updated to reflect a well-formed type for the constructor and
5022/// returned.
5023QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005024 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005025 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005026
5027 // C++ [class.ctor]p3:
5028 // A constructor shall not be virtual (10.3) or static (9.4). A
5029 // constructor can be invoked for a const, volatile or const
5030 // volatile object. A constructor shall not be declared const,
5031 // volatile, or const volatile (9.3.2).
5032 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005033 if (!D.isInvalidType())
5034 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5035 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5036 << SourceRange(D.getIdentifierLoc());
5037 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005038 }
John McCalld931b082010-08-26 03:08:43 +00005039 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005040 if (!D.isInvalidType())
5041 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5042 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5043 << SourceRange(D.getIdentifierLoc());
5044 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005045 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005046 }
Mike Stump1eb44332009-09-09 15:08:12 +00005047
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005048 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005049 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005050 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005051 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5052 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005053 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005054 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5055 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005056 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005057 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5058 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005059 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005060 }
Mike Stump1eb44332009-09-09 15:08:12 +00005061
Douglas Gregorc938c162011-01-26 05:01:58 +00005062 // C++0x [class.ctor]p4:
5063 // A constructor shall not be declared with a ref-qualifier.
5064 if (FTI.hasRefQualifier()) {
5065 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5066 << FTI.RefQualifierIsLValueRef
5067 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5068 D.setInvalidType();
5069 }
5070
Douglas Gregor42a552f2008-11-05 20:51:48 +00005071 // Rebuild the function type "R" without any type qualifiers (in
5072 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005073 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005074 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005075 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5076 return R;
5077
5078 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5079 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005080 EPI.RefQualifier = RQ_None;
5081
Chris Lattner65401802009-04-25 08:28:21 +00005082 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005083 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005084}
5085
Douglas Gregor72b505b2008-12-16 21:30:33 +00005086/// CheckConstructor - Checks a fully-formed constructor for
5087/// well-formedness, issuing any diagnostics required. Returns true if
5088/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005089void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005090 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005091 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5092 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005093 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005094
5095 // C++ [class.copy]p3:
5096 // A declaration of a constructor for a class X is ill-formed if
5097 // its first parameter is of type (optionally cv-qualified) X and
5098 // either there are no other parameters or else all other
5099 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005100 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005101 ((Constructor->getNumParams() == 1) ||
5102 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005103 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5104 Constructor->getTemplateSpecializationKind()
5105 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005106 QualType ParamType = Constructor->getParamDecl(0)->getType();
5107 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5108 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005109 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005110 const char *ConstRef
5111 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5112 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005113 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005114 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005115
5116 // FIXME: Rather that making the constructor invalid, we should endeavor
5117 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005118 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005119 }
5120 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005121}
5122
John McCall15442822010-08-04 01:04:25 +00005123/// CheckDestructor - Checks a fully-formed destructor definition for
5124/// well-formedness, issuing any diagnostics required. Returns true
5125/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005126bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005127 CXXRecordDecl *RD = Destructor->getParent();
5128
5129 if (Destructor->isVirtual()) {
5130 SourceLocation Loc;
5131
5132 if (!Destructor->isImplicit())
5133 Loc = Destructor->getLocation();
5134 else
5135 Loc = RD->getLocation();
5136
5137 // If we have a virtual destructor, look up the deallocation function
5138 FunctionDecl *OperatorDelete = 0;
5139 DeclarationName Name =
5140 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005141 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005142 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005143
Eli Friedman5f2987c2012-02-02 03:46:19 +00005144 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005145
5146 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005147 }
Anders Carlsson37909802009-11-30 21:24:50 +00005148
5149 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005150}
5151
Mike Stump1eb44332009-09-09 15:08:12 +00005152static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005153FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5154 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5155 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005156 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005157}
5158
Douglas Gregor42a552f2008-11-05 20:51:48 +00005159/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5160/// the well-formednes of the destructor declarator @p D with type @p
5161/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005162/// emit diagnostics and set the declarator to invalid. Even if this happens,
5163/// will be updated to reflect a well-formed type for the destructor and
5164/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005165QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005166 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005167 // C++ [class.dtor]p1:
5168 // [...] A typedef-name that names a class is a class-name
5169 // (7.1.3); however, a typedef-name that names a class shall not
5170 // be used as the identifier in the declarator for a destructor
5171 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005172 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005173 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005174 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005175 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005176 else if (const TemplateSpecializationType *TST =
5177 DeclaratorType->getAs<TemplateSpecializationType>())
5178 if (TST->isTypeAlias())
5179 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5180 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005181
5182 // C++ [class.dtor]p2:
5183 // A destructor is used to destroy objects of its class type. A
5184 // destructor takes no parameters, and no return type can be
5185 // specified for it (not even void). The address of a destructor
5186 // shall not be taken. A destructor shall not be static. A
5187 // destructor can be invoked for a const, volatile or const
5188 // volatile object. A destructor shall not be declared const,
5189 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005190 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005191 if (!D.isInvalidType())
5192 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5193 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005194 << SourceRange(D.getIdentifierLoc())
5195 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5196
John McCalld931b082010-08-26 03:08:43 +00005197 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005198 }
Chris Lattner65401802009-04-25 08:28:21 +00005199 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005200 // Destructors don't have return types, but the parser will
5201 // happily parse something like:
5202 //
5203 // class X {
5204 // float ~X();
5205 // };
5206 //
5207 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005208 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5209 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5210 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005211 }
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005213 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005214 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005215 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005216 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5217 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005218 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005219 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5220 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005221 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005222 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5223 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005224 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005225 }
5226
Douglas Gregorc938c162011-01-26 05:01:58 +00005227 // C++0x [class.dtor]p2:
5228 // A destructor shall not be declared with a ref-qualifier.
5229 if (FTI.hasRefQualifier()) {
5230 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5231 << FTI.RefQualifierIsLValueRef
5232 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5233 D.setInvalidType();
5234 }
5235
Douglas Gregor42a552f2008-11-05 20:51:48 +00005236 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005237 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005238 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5239
5240 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005241 FTI.freeArgs();
5242 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005243 }
5244
Mike Stump1eb44332009-09-09 15:08:12 +00005245 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005246 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005247 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005248 D.setInvalidType();
5249 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005250
5251 // Rebuild the function type "R" without any type qualifiers or
5252 // parameters (in case any of the errors above fired) and with
5253 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005254 // types.
John McCalle23cf432010-12-14 08:05:40 +00005255 if (!D.isInvalidType())
5256 return R;
5257
Douglas Gregord92ec472010-07-01 05:10:53 +00005258 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005259 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5260 EPI.Variadic = false;
5261 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005262 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005263 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005264}
5265
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005266/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5267/// well-formednes of the conversion function declarator @p D with
5268/// type @p R. If there are any errors in the declarator, this routine
5269/// will emit diagnostics and return true. Otherwise, it will return
5270/// false. Either way, the type @p R will be updated to reflect a
5271/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005272void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005273 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005274 // C++ [class.conv.fct]p1:
5275 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005276 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005277 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005278 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005279 if (!D.isInvalidType())
5280 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5281 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5282 << SourceRange(D.getIdentifierLoc());
5283 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005284 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005285 }
John McCalla3f81372010-04-13 00:04:31 +00005286
5287 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5288
Chris Lattner6e475012009-04-25 08:35:12 +00005289 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005290 // Conversion functions don't have return types, but the parser will
5291 // happily parse something like:
5292 //
5293 // class X {
5294 // float operator bool();
5295 // };
5296 //
5297 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005298 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5299 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5300 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005301 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005302 }
5303
John McCalla3f81372010-04-13 00:04:31 +00005304 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5305
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005306 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005307 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005308 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5309
5310 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005311 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005312 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005313 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005314 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005315 D.setInvalidType();
5316 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005317
John McCalla3f81372010-04-13 00:04:31 +00005318 // Diagnose "&operator bool()" and other such nonsense. This
5319 // is actually a gcc extension which we don't support.
5320 if (Proto->getResultType() != ConvType) {
5321 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5322 << Proto->getResultType();
5323 D.setInvalidType();
5324 ConvType = Proto->getResultType();
5325 }
5326
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005327 // C++ [class.conv.fct]p4:
5328 // The conversion-type-id shall not represent a function type nor
5329 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005330 if (ConvType->isArrayType()) {
5331 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5332 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005333 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005334 } else if (ConvType->isFunctionType()) {
5335 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5336 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005337 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005338 }
5339
5340 // Rebuild the function type "R" without any parameters (in case any
5341 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005342 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005343 if (D.isInvalidType())
5344 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005345
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005346 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005347 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005348 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005349 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005350 diag::warn_cxx98_compat_explicit_conversion_functions :
5351 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005352 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005353}
5354
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005355/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5356/// the declaration of the given C++ conversion function. This routine
5357/// is responsible for recording the conversion function in the C++
5358/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005359Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005360 assert(Conversion && "Expected to receive a conversion function declaration");
5361
Douglas Gregor9d350972008-12-12 08:25:50 +00005362 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005363
5364 // Make sure we aren't redeclaring the conversion function.
5365 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005366
5367 // C++ [class.conv.fct]p1:
5368 // [...] A conversion function is never used to convert a
5369 // (possibly cv-qualified) object to the (possibly cv-qualified)
5370 // same object type (or a reference to it), to a (possibly
5371 // cv-qualified) base class of that type (or a reference to it),
5372 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005373 // FIXME: Suppress this warning if the conversion function ends up being a
5374 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005375 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005376 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005377 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005378 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005379 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5380 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005381 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005382 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005383 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5384 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005385 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005386 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005387 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005388 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005389 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005390 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005391 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005392 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005393 }
5394
Douglas Gregore80622f2010-09-29 04:25:11 +00005395 if (FunctionTemplateDecl *ConversionTemplate
5396 = Conversion->getDescribedFunctionTemplate())
5397 return ConversionTemplate;
5398
John McCalld226f652010-08-21 09:40:31 +00005399 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005400}
5401
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005402//===----------------------------------------------------------------------===//
5403// Namespace Handling
5404//===----------------------------------------------------------------------===//
5405
John McCallea318642010-08-26 09:15:37 +00005406
5407
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005408/// ActOnStartNamespaceDef - This is called at the start of a namespace
5409/// definition.
John McCalld226f652010-08-21 09:40:31 +00005410Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005411 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005412 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005413 SourceLocation IdentLoc,
5414 IdentifierInfo *II,
5415 SourceLocation LBrace,
5416 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005417 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5418 // For anonymous namespace, take the location of the left brace.
5419 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005420 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005421 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005422 bool IsStd = false;
5423 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005424 Scope *DeclRegionScope = NamespcScope->getParent();
5425
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005426 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005427 if (II) {
5428 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005429 // The identifier in an original-namespace-definition shall not
5430 // have been previously defined in the declarative region in
5431 // which the original-namespace-definition appears. The
5432 // identifier in an original-namespace-definition is the name of
5433 // the namespace. Subsequently in that declarative region, it is
5434 // treated as an original-namespace-name.
5435 //
5436 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005437 // look through using directives, just look for any ordinary names.
5438
5439 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005440 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5441 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005442 NamedDecl *PrevDecl = 0;
5443 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005444 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005445 R.first != R.second; ++R.first) {
5446 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5447 PrevDecl = *R.first;
5448 break;
5449 }
5450 }
5451
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005452 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5453
5454 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005455 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005456 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005457 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005458 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005459 // The user probably just forgot the 'inline', so suggest that it
5460 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005461 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005462 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5463 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005464 Diag(Loc, diag::err_inline_namespace_mismatch)
5465 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005466 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005467 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5468
5469 IsInline = PrevNS->isInline();
5470 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005471 } else if (PrevDecl) {
5472 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005473 Diag(Loc, diag::err_redefinition_different_kind)
5474 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005475 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005476 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005477 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005478 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005479 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005480 // This is the first "real" definition of the namespace "std", so update
5481 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005482 PrevNS = getStdNamespace();
5483 IsStd = true;
5484 AddToKnown = !IsInline;
5485 } else {
5486 // We've seen this namespace for the first time.
5487 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005488 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005489 } else {
John McCall9aeed322009-10-01 00:25:31 +00005490 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005491
5492 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005493 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005494 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005495 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005496 } else {
5497 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005498 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005499 }
5500
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005501 if (PrevNS && IsInline != PrevNS->isInline()) {
5502 // inline-ness must match
5503 Diag(Loc, diag::err_inline_namespace_mismatch)
5504 << IsInline;
5505 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005506
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005507 // Recover by ignoring the new namespace's inline status.
5508 IsInline = PrevNS->isInline();
5509 }
5510 }
5511
5512 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5513 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005514 if (IsInvalid)
5515 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005516
5517 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005518
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005519 // FIXME: Should we be merging attributes?
5520 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005521 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005522
5523 if (IsStd)
5524 StdNamespace = Namespc;
5525 if (AddToKnown)
5526 KnownNamespaces[Namespc] = false;
5527
5528 if (II) {
5529 PushOnScopeChains(Namespc, DeclRegionScope);
5530 } else {
5531 // Link the anonymous namespace into its parent.
5532 DeclContext *Parent = CurContext->getRedeclContext();
5533 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5534 TU->setAnonymousNamespace(Namespc);
5535 } else {
5536 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005537 }
John McCall9aeed322009-10-01 00:25:31 +00005538
Douglas Gregora4181472010-03-24 00:46:35 +00005539 CurContext->addDecl(Namespc);
5540
John McCall9aeed322009-10-01 00:25:31 +00005541 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5542 // behaves as if it were replaced by
5543 // namespace unique { /* empty body */ }
5544 // using namespace unique;
5545 // namespace unique { namespace-body }
5546 // where all occurrences of 'unique' in a translation unit are
5547 // replaced by the same identifier and this identifier differs
5548 // from all other identifiers in the entire program.
5549
5550 // We just create the namespace with an empty name and then add an
5551 // implicit using declaration, just like the standard suggests.
5552 //
5553 // CodeGen enforces the "universally unique" aspect by giving all
5554 // declarations semantically contained within an anonymous
5555 // namespace internal linkage.
5556
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005557 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005558 UsingDirectiveDecl* UD
5559 = UsingDirectiveDecl::Create(Context, CurContext,
5560 /* 'using' */ LBrace,
5561 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005562 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005563 /* identifier */ SourceLocation(),
5564 Namespc,
5565 /* Ancestor */ CurContext);
5566 UD->setImplicit();
5567 CurContext->addDecl(UD);
5568 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005569 }
5570
5571 // Although we could have an invalid decl (i.e. the namespace name is a
5572 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005573 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5574 // for the namespace has the declarations that showed up in that particular
5575 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005576 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005577 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005578}
5579
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005580/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5581/// is a namespace alias, returns the namespace it points to.
5582static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5583 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5584 return AD->getNamespace();
5585 return dyn_cast_or_null<NamespaceDecl>(D);
5586}
5587
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005588/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5589/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005590void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005591 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5592 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005593 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005594 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005595 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005596 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005597}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005598
John McCall384aff82010-08-25 07:42:41 +00005599CXXRecordDecl *Sema::getStdBadAlloc() const {
5600 return cast_or_null<CXXRecordDecl>(
5601 StdBadAlloc.get(Context.getExternalSource()));
5602}
5603
5604NamespaceDecl *Sema::getStdNamespace() const {
5605 return cast_or_null<NamespaceDecl>(
5606 StdNamespace.get(Context.getExternalSource()));
5607}
5608
Douglas Gregor66992202010-06-29 17:53:46 +00005609/// \brief Retrieve the special "std" namespace, which may require us to
5610/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005611NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005612 if (!StdNamespace) {
5613 // The "std" namespace has not yet been defined, so build one implicitly.
5614 StdNamespace = NamespaceDecl::Create(Context,
5615 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005616 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005617 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005618 &PP.getIdentifierTable().get("std"),
5619 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005620 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005621 }
5622
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005623 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005624}
5625
Sebastian Redl395e04d2012-01-17 22:49:33 +00005626bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005627 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005628 "Looking for std::initializer_list outside of C++.");
5629
5630 // We're looking for implicit instantiations of
5631 // template <typename E> class std::initializer_list.
5632
5633 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5634 return false;
5635
Sebastian Redl84760e32012-01-17 22:49:58 +00005636 ClassTemplateDecl *Template = 0;
5637 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005638
Sebastian Redl84760e32012-01-17 22:49:58 +00005639 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005640
Sebastian Redl84760e32012-01-17 22:49:58 +00005641 ClassTemplateSpecializationDecl *Specialization =
5642 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5643 if (!Specialization)
5644 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005645
Sebastian Redl84760e32012-01-17 22:49:58 +00005646 Template = Specialization->getSpecializedTemplate();
5647 Arguments = Specialization->getTemplateArgs().data();
5648 } else if (const TemplateSpecializationType *TST =
5649 Ty->getAs<TemplateSpecializationType>()) {
5650 Template = dyn_cast_or_null<ClassTemplateDecl>(
5651 TST->getTemplateName().getAsTemplateDecl());
5652 Arguments = TST->getArgs();
5653 }
5654 if (!Template)
5655 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005656
5657 if (!StdInitializerList) {
5658 // Haven't recognized std::initializer_list yet, maybe this is it.
5659 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5660 if (TemplateClass->getIdentifier() !=
5661 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005662 !getStdNamespace()->InEnclosingNamespaceSetOf(
5663 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005664 return false;
5665 // This is a template called std::initializer_list, but is it the right
5666 // template?
5667 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005668 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005669 return false;
5670 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5671 return false;
5672
5673 // It's the right template.
5674 StdInitializerList = Template;
5675 }
5676
5677 if (Template != StdInitializerList)
5678 return false;
5679
5680 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005681 if (Element)
5682 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005683 return true;
5684}
5685
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005686static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5687 NamespaceDecl *Std = S.getStdNamespace();
5688 if (!Std) {
5689 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5690 return 0;
5691 }
5692
5693 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5694 Loc, Sema::LookupOrdinaryName);
5695 if (!S.LookupQualifiedName(Result, Std)) {
5696 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5697 return 0;
5698 }
5699 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5700 if (!Template) {
5701 Result.suppressDiagnostics();
5702 // We found something weird. Complain about the first thing we found.
5703 NamedDecl *Found = *Result.begin();
5704 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5705 return 0;
5706 }
5707
5708 // We found some template called std::initializer_list. Now verify that it's
5709 // correct.
5710 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005711 if (Params->getMinRequiredArguments() != 1 ||
5712 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005713 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5714 return 0;
5715 }
5716
5717 return Template;
5718}
5719
5720QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5721 if (!StdInitializerList) {
5722 StdInitializerList = LookupStdInitializerList(*this, Loc);
5723 if (!StdInitializerList)
5724 return QualType();
5725 }
5726
5727 TemplateArgumentListInfo Args(Loc, Loc);
5728 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5729 Context.getTrivialTypeSourceInfo(Element,
5730 Loc)));
5731 return Context.getCanonicalType(
5732 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5733}
5734
Sebastian Redl98d36062012-01-17 22:50:14 +00005735bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5736 // C++ [dcl.init.list]p2:
5737 // A constructor is an initializer-list constructor if its first parameter
5738 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5739 // std::initializer_list<E> for some type E, and either there are no other
5740 // parameters or else all other parameters have default arguments.
5741 if (Ctor->getNumParams() < 1 ||
5742 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5743 return false;
5744
5745 QualType ArgType = Ctor->getParamDecl(0)->getType();
5746 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5747 ArgType = RT->getPointeeType().getUnqualifiedType();
5748
5749 return isStdInitializerList(ArgType, 0);
5750}
5751
Douglas Gregor9172aa62011-03-26 22:25:30 +00005752/// \brief Determine whether a using statement is in a context where it will be
5753/// apply in all contexts.
5754static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5755 switch (CurContext->getDeclKind()) {
5756 case Decl::TranslationUnit:
5757 return true;
5758 case Decl::LinkageSpec:
5759 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5760 default:
5761 return false;
5762 }
5763}
5764
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005765namespace {
5766
5767// Callback to only accept typo corrections that are namespaces.
5768class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5769 public:
5770 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5771 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5772 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5773 }
5774 return false;
5775 }
5776};
5777
5778}
5779
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005780static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5781 CXXScopeSpec &SS,
5782 SourceLocation IdentLoc,
5783 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005784 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005785 R.clear();
5786 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005787 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005788 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005789 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5790 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005791 if (DeclContext *DC = S.computeDeclContext(SS, false))
5792 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5793 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5794 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5795 else
5796 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5797 << Ident << CorrectedQuotedStr
5798 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005799
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005800 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5801 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005802
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005803 R.addDecl(Corrected.getCorrectionDecl());
5804 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005805 }
5806 return false;
5807}
5808
John McCalld226f652010-08-21 09:40:31 +00005809Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005810 SourceLocation UsingLoc,
5811 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005812 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005813 SourceLocation IdentLoc,
5814 IdentifierInfo *NamespcName,
5815 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005816 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5817 assert(NamespcName && "Invalid NamespcName.");
5818 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005819
5820 // This can only happen along a recovery path.
5821 while (S->getFlags() & Scope::TemplateParamScope)
5822 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005823 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005824
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005825 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005826 NestedNameSpecifier *Qualifier = 0;
5827 if (SS.isSet())
5828 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5829
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005830 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005831 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5832 LookupParsedName(R, S, &SS);
5833 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005834 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005835
Douglas Gregor66992202010-06-29 17:53:46 +00005836 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005837 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005838 // Allow "using namespace std;" or "using namespace ::std;" even if
5839 // "std" hasn't been defined yet, for GCC compatibility.
5840 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5841 NamespcName->isStr("std")) {
5842 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005843 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005844 R.resolveKind();
5845 }
5846 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005847 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005848 }
5849
John McCallf36e02d2009-10-09 21:13:30 +00005850 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005851 NamedDecl *Named = R.getFoundDecl();
5852 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5853 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005854 // C++ [namespace.udir]p1:
5855 // A using-directive specifies that the names in the nominated
5856 // namespace can be used in the scope in which the
5857 // using-directive appears after the using-directive. During
5858 // unqualified name lookup (3.4.1), the names appear as if they
5859 // were declared in the nearest enclosing namespace which
5860 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005861 // namespace. [Note: in this context, "contains" means "contains
5862 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005863
5864 // Find enclosing context containing both using-directive and
5865 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005866 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005867 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5868 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5869 CommonAncestor = CommonAncestor->getParent();
5870
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005871 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005872 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005873 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005874
Douglas Gregor9172aa62011-03-26 22:25:30 +00005875 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005876 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005877 Diag(IdentLoc, diag::warn_using_directive_in_header);
5878 }
5879
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005880 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005881 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005882 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005883 }
5884
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005885 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005886 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005887}
5888
5889void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005890 // If the scope has an associated entity and the using directive is at
5891 // namespace or translation unit scope, add the UsingDirectiveDecl into
5892 // its lookup structure so qualified name lookup can find it.
5893 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5894 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005895 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005896 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005897 // Otherwise, it is at block sope. The using-directives will affect lookup
5898 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005899 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005900}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005901
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005902
John McCalld226f652010-08-21 09:40:31 +00005903Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005904 AccessSpecifier AS,
5905 bool HasUsingKeyword,
5906 SourceLocation UsingLoc,
5907 CXXScopeSpec &SS,
5908 UnqualifiedId &Name,
5909 AttributeList *AttrList,
5910 bool IsTypeName,
5911 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005912 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005913
Douglas Gregor12c118a2009-11-04 16:30:06 +00005914 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005915 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005916 case UnqualifiedId::IK_Identifier:
5917 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005918 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005919 case UnqualifiedId::IK_ConversionFunctionId:
5920 break;
5921
5922 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005923 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005924 // C++0x inherited constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005925 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005926 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005927 diag::warn_cxx98_compat_using_decl_constructor :
5928 diag::err_using_decl_constructor)
5929 << SS.getRange();
5930
David Blaikie4e4d0842012-03-11 07:00:24 +00005931 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005932
John McCalld226f652010-08-21 09:40:31 +00005933 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005934
5935 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005936 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005937 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005938 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005939
5940 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005941 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005942 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005943 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005944 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005945
5946 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5947 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005948 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005949 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005950
John McCall60fa3cf2009-12-11 02:10:03 +00005951 // Warn about using declarations.
5952 // TODO: store that the declaration was written without 'using' and
5953 // talk about access decls instead of using decls in the
5954 // diagnostics.
5955 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005956 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005957
5958 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005959 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005960 }
5961
Douglas Gregor56c04582010-12-16 00:46:58 +00005962 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5963 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5964 return 0;
5965
John McCall9488ea12009-11-17 05:59:44 +00005966 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005967 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005968 /* IsInstantiation */ false,
5969 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005970 if (UD)
5971 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005972
John McCalld226f652010-08-21 09:40:31 +00005973 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005974}
5975
Douglas Gregor09acc982010-07-07 23:08:52 +00005976/// \brief Determine whether a using declaration considers the given
5977/// declarations as "equivalent", e.g., if they are redeclarations of
5978/// the same entity or are both typedefs of the same type.
5979static bool
5980IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5981 bool &SuppressRedeclaration) {
5982 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5983 SuppressRedeclaration = false;
5984 return true;
5985 }
5986
Richard Smith162e1c12011-04-15 14:24:37 +00005987 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5988 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005989 SuppressRedeclaration = true;
5990 return Context.hasSameType(TD1->getUnderlyingType(),
5991 TD2->getUnderlyingType());
5992 }
5993
5994 return false;
5995}
5996
5997
John McCall9f54ad42009-12-10 09:41:52 +00005998/// Determines whether to create a using shadow decl for a particular
5999/// decl, given the set of decls existing prior to this using lookup.
6000bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6001 const LookupResult &Previous) {
6002 // Diagnose finding a decl which is not from a base class of the
6003 // current class. We do this now because there are cases where this
6004 // function will silently decide not to build a shadow decl, which
6005 // will pre-empt further diagnostics.
6006 //
6007 // We don't need to do this in C++0x because we do the check once on
6008 // the qualifier.
6009 //
6010 // FIXME: diagnose the following if we care enough:
6011 // struct A { int foo; };
6012 // struct B : A { using A::foo; };
6013 // template <class T> struct C : A {};
6014 // template <class T> struct D : C<T> { using B::foo; } // <---
6015 // This is invalid (during instantiation) in C++03 because B::foo
6016 // resolves to the using decl in B, which is not a base class of D<T>.
6017 // We can't diagnose it immediately because C<T> is an unknown
6018 // specialization. The UsingShadowDecl in D<T> then points directly
6019 // to A::foo, which will look well-formed when we instantiate.
6020 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006021 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006022 DeclContext *OrigDC = Orig->getDeclContext();
6023
6024 // Handle enums and anonymous structs.
6025 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6026 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6027 while (OrigRec->isAnonymousStructOrUnion())
6028 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6029
6030 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6031 if (OrigDC == CurContext) {
6032 Diag(Using->getLocation(),
6033 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006034 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006035 Diag(Orig->getLocation(), diag::note_using_decl_target);
6036 return true;
6037 }
6038
Douglas Gregordc355712011-02-25 00:36:19 +00006039 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006040 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006041 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006042 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006043 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006044 Diag(Orig->getLocation(), diag::note_using_decl_target);
6045 return true;
6046 }
6047 }
6048
6049 if (Previous.empty()) return false;
6050
6051 NamedDecl *Target = Orig;
6052 if (isa<UsingShadowDecl>(Target))
6053 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6054
John McCalld7533ec2009-12-11 02:33:26 +00006055 // If the target happens to be one of the previous declarations, we
6056 // don't have a conflict.
6057 //
6058 // FIXME: but we might be increasing its access, in which case we
6059 // should redeclare it.
6060 NamedDecl *NonTag = 0, *Tag = 0;
6061 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6062 I != E; ++I) {
6063 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006064 bool Result;
6065 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6066 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006067
6068 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6069 }
6070
John McCall9f54ad42009-12-10 09:41:52 +00006071 if (Target->isFunctionOrFunctionTemplate()) {
6072 FunctionDecl *FD;
6073 if (isa<FunctionTemplateDecl>(Target))
6074 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6075 else
6076 FD = cast<FunctionDecl>(Target);
6077
6078 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006079 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006080 case Ovl_Overload:
6081 return false;
6082
6083 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006084 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006085 break;
6086
6087 // We found a decl with the exact signature.
6088 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006089 // If we're in a record, we want to hide the target, so we
6090 // return true (without a diagnostic) to tell the caller not to
6091 // build a shadow decl.
6092 if (CurContext->isRecord())
6093 return true;
6094
6095 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006096 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006097 break;
6098 }
6099
6100 Diag(Target->getLocation(), diag::note_using_decl_target);
6101 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6102 return true;
6103 }
6104
6105 // Target is not a function.
6106
John McCall9f54ad42009-12-10 09:41:52 +00006107 if (isa<TagDecl>(Target)) {
6108 // No conflict between a tag and a non-tag.
6109 if (!Tag) return false;
6110
John McCall41ce66f2009-12-10 19:51:03 +00006111 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006112 Diag(Target->getLocation(), diag::note_using_decl_target);
6113 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6114 return true;
6115 }
6116
6117 // No conflict between a tag and a non-tag.
6118 if (!NonTag) return false;
6119
John McCall41ce66f2009-12-10 19:51:03 +00006120 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006121 Diag(Target->getLocation(), diag::note_using_decl_target);
6122 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6123 return true;
6124}
6125
John McCall9488ea12009-11-17 05:59:44 +00006126/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006127UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006128 UsingDecl *UD,
6129 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006130
6131 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006132 NamedDecl *Target = Orig;
6133 if (isa<UsingShadowDecl>(Target)) {
6134 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6135 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006136 }
6137
6138 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006139 = UsingShadowDecl::Create(Context, CurContext,
6140 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006141 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006142
6143 Shadow->setAccess(UD->getAccess());
6144 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6145 Shadow->setInvalidDecl();
6146
John McCall9488ea12009-11-17 05:59:44 +00006147 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006148 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006149 else
John McCall604e7f12009-12-08 07:46:18 +00006150 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006151
John McCall604e7f12009-12-08 07:46:18 +00006152
John McCall9f54ad42009-12-10 09:41:52 +00006153 return Shadow;
6154}
John McCall604e7f12009-12-08 07:46:18 +00006155
John McCall9f54ad42009-12-10 09:41:52 +00006156/// Hides a using shadow declaration. This is required by the current
6157/// using-decl implementation when a resolvable using declaration in a
6158/// class is followed by a declaration which would hide or override
6159/// one or more of the using decl's targets; for example:
6160///
6161/// struct Base { void foo(int); };
6162/// struct Derived : Base {
6163/// using Base::foo;
6164/// void foo(int);
6165/// };
6166///
6167/// The governing language is C++03 [namespace.udecl]p12:
6168///
6169/// When a using-declaration brings names from a base class into a
6170/// derived class scope, member functions in the derived class
6171/// override and/or hide member functions with the same name and
6172/// parameter types in a base class (rather than conflicting).
6173///
6174/// There are two ways to implement this:
6175/// (1) optimistically create shadow decls when they're not hidden
6176/// by existing declarations, or
6177/// (2) don't create any shadow decls (or at least don't make them
6178/// visible) until we've fully parsed/instantiated the class.
6179/// The problem with (1) is that we might have to retroactively remove
6180/// a shadow decl, which requires several O(n) operations because the
6181/// decl structures are (very reasonably) not designed for removal.
6182/// (2) avoids this but is very fiddly and phase-dependent.
6183void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006184 if (Shadow->getDeclName().getNameKind() ==
6185 DeclarationName::CXXConversionFunctionName)
6186 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6187
John McCall9f54ad42009-12-10 09:41:52 +00006188 // Remove it from the DeclContext...
6189 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006190
John McCall9f54ad42009-12-10 09:41:52 +00006191 // ...and the scope, if applicable...
6192 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006193 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006194 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006195 }
6196
John McCall9f54ad42009-12-10 09:41:52 +00006197 // ...and the using decl.
6198 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6199
6200 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006201 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006202}
6203
John McCall7ba107a2009-11-18 02:36:19 +00006204/// Builds a using declaration.
6205///
6206/// \param IsInstantiation - Whether this call arises from an
6207/// instantiation of an unresolved using declaration. We treat
6208/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006209NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6210 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006211 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006212 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006213 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006214 bool IsInstantiation,
6215 bool IsTypeName,
6216 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006217 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006218 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006219 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006220
Anders Carlsson550b14b2009-08-28 05:49:21 +00006221 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006222
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006223 if (SS.isEmpty()) {
6224 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006225 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006226 }
Mike Stump1eb44332009-09-09 15:08:12 +00006227
John McCall9f54ad42009-12-10 09:41:52 +00006228 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006229 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006230 ForRedeclaration);
6231 Previous.setHideTags(false);
6232 if (S) {
6233 LookupName(Previous, S);
6234
6235 // It is really dumb that we have to do this.
6236 LookupResult::Filter F = Previous.makeFilter();
6237 while (F.hasNext()) {
6238 NamedDecl *D = F.next();
6239 if (!isDeclInScope(D, CurContext, S))
6240 F.erase();
6241 }
6242 F.done();
6243 } else {
6244 assert(IsInstantiation && "no scope in non-instantiation");
6245 assert(CurContext->isRecord() && "scope not record in instantiation");
6246 LookupQualifiedName(Previous, CurContext);
6247 }
6248
John McCall9f54ad42009-12-10 09:41:52 +00006249 // Check for invalid redeclarations.
6250 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6251 return 0;
6252
6253 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006254 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6255 return 0;
6256
John McCallaf8e6ed2009-11-12 03:15:40 +00006257 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006258 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006259 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006260 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006261 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006262 // FIXME: not all declaration name kinds are legal here
6263 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6264 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006265 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006266 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006267 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006268 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6269 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006270 }
John McCalled976492009-12-04 22:46:56 +00006271 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006272 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6273 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006274 }
John McCalled976492009-12-04 22:46:56 +00006275 D->setAccess(AS);
6276 CurContext->addDecl(D);
6277
6278 if (!LookupContext) return D;
6279 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006280
John McCall77bb1aa2010-05-01 00:40:08 +00006281 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006282 UD->setInvalidDecl();
6283 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006284 }
6285
Richard Smithc5a89a12012-04-02 01:30:27 +00006286 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006287 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006288 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006289 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006290 return UD;
6291 }
6292
6293 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006294
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006295 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006296
John McCall604e7f12009-12-08 07:46:18 +00006297 // Unlike most lookups, we don't always want to hide tag
6298 // declarations: tag names are visible through the using declaration
6299 // even if hidden by ordinary names, *except* in a dependent context
6300 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006301 if (!IsInstantiation)
6302 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006303
John McCallb9abd8722012-04-07 03:04:20 +00006304 // For the purposes of this lookup, we have a base object type
6305 // equal to that of the current context.
6306 if (CurContext->isRecord()) {
6307 R.setBaseObjectType(
6308 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6309 }
6310
John McCalla24dc2e2009-11-17 02:14:36 +00006311 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006312
John McCallf36e02d2009-10-09 21:13:30 +00006313 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006314 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006315 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006316 UD->setInvalidDecl();
6317 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006318 }
6319
John McCalled976492009-12-04 22:46:56 +00006320 if (R.isAmbiguous()) {
6321 UD->setInvalidDecl();
6322 return UD;
6323 }
Mike Stump1eb44332009-09-09 15:08:12 +00006324
John McCall7ba107a2009-11-18 02:36:19 +00006325 if (IsTypeName) {
6326 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006327 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006328 Diag(IdentLoc, diag::err_using_typename_non_type);
6329 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6330 Diag((*I)->getUnderlyingDecl()->getLocation(),
6331 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006332 UD->setInvalidDecl();
6333 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006334 }
6335 } else {
6336 // If we asked for a non-typename and we got a type, error out,
6337 // but only if this is an instantiation of an unresolved using
6338 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006339 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006340 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6341 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006342 UD->setInvalidDecl();
6343 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006344 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006345 }
6346
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006347 // C++0x N2914 [namespace.udecl]p6:
6348 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006349 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006350 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6351 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006352 UD->setInvalidDecl();
6353 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006354 }
Mike Stump1eb44332009-09-09 15:08:12 +00006355
John McCall9f54ad42009-12-10 09:41:52 +00006356 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6357 if (!CheckUsingShadowDecl(UD, *I, Previous))
6358 BuildUsingShadowDecl(S, UD, *I);
6359 }
John McCall9488ea12009-11-17 05:59:44 +00006360
6361 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006362}
6363
Sebastian Redlf677ea32011-02-05 19:23:19 +00006364/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006365bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6366 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006367
Douglas Gregordc355712011-02-25 00:36:19 +00006368 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006369 assert(SourceType &&
6370 "Using decl naming constructor doesn't have type in scope spec.");
6371 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6372
6373 // Check whether the named type is a direct base class.
6374 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6375 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6376 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6377 BaseIt != BaseE; ++BaseIt) {
6378 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6379 if (CanonicalSourceType == BaseType)
6380 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006381 if (BaseIt->getType()->isDependentType())
6382 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006383 }
6384
6385 if (BaseIt == BaseE) {
6386 // Did not find SourceType in the bases.
6387 Diag(UD->getUsingLocation(),
6388 diag::err_using_decl_constructor_not_in_direct_base)
6389 << UD->getNameInfo().getSourceRange()
6390 << QualType(SourceType, 0) << TargetClass;
6391 return true;
6392 }
6393
Richard Smithc5a89a12012-04-02 01:30:27 +00006394 if (!CurContext->isDependentContext())
6395 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006396
6397 return false;
6398}
6399
John McCall9f54ad42009-12-10 09:41:52 +00006400/// Checks that the given using declaration is not an invalid
6401/// redeclaration. Note that this is checking only for the using decl
6402/// itself, not for any ill-formedness among the UsingShadowDecls.
6403bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6404 bool isTypeName,
6405 const CXXScopeSpec &SS,
6406 SourceLocation NameLoc,
6407 const LookupResult &Prev) {
6408 // C++03 [namespace.udecl]p8:
6409 // C++0x [namespace.udecl]p10:
6410 // A using-declaration is a declaration and can therefore be used
6411 // repeatedly where (and only where) multiple declarations are
6412 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006413 //
John McCall8a726212010-11-29 18:01:58 +00006414 // That's in non-member contexts.
6415 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006416 return false;
6417
6418 NestedNameSpecifier *Qual
6419 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6420
6421 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6422 NamedDecl *D = *I;
6423
6424 bool DTypename;
6425 NestedNameSpecifier *DQual;
6426 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6427 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006428 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006429 } else if (UnresolvedUsingValueDecl *UD
6430 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6431 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006432 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006433 } else if (UnresolvedUsingTypenameDecl *UD
6434 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6435 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006436 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006437 } else continue;
6438
6439 // using decls differ if one says 'typename' and the other doesn't.
6440 // FIXME: non-dependent using decls?
6441 if (isTypeName != DTypename) continue;
6442
6443 // using decls differ if they name different scopes (but note that
6444 // template instantiation can cause this check to trigger when it
6445 // didn't before instantiation).
6446 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6447 Context.getCanonicalNestedNameSpecifier(DQual))
6448 continue;
6449
6450 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006451 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006452 return true;
6453 }
6454
6455 return false;
6456}
6457
John McCall604e7f12009-12-08 07:46:18 +00006458
John McCalled976492009-12-04 22:46:56 +00006459/// Checks that the given nested-name qualifier used in a using decl
6460/// in the current context is appropriately related to the current
6461/// scope. If an error is found, diagnoses it and returns true.
6462bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6463 const CXXScopeSpec &SS,
6464 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006465 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006466
John McCall604e7f12009-12-08 07:46:18 +00006467 if (!CurContext->isRecord()) {
6468 // C++03 [namespace.udecl]p3:
6469 // C++0x [namespace.udecl]p8:
6470 // A using-declaration for a class member shall be a member-declaration.
6471
6472 // If we weren't able to compute a valid scope, it must be a
6473 // dependent class scope.
6474 if (!NamedContext || NamedContext->isRecord()) {
6475 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6476 << SS.getRange();
6477 return true;
6478 }
6479
6480 // Otherwise, everything is known to be fine.
6481 return false;
6482 }
6483
6484 // The current scope is a record.
6485
6486 // If the named context is dependent, we can't decide much.
6487 if (!NamedContext) {
6488 // FIXME: in C++0x, we can diagnose if we can prove that the
6489 // nested-name-specifier does not refer to a base class, which is
6490 // still possible in some cases.
6491
6492 // Otherwise we have to conservatively report that things might be
6493 // okay.
6494 return false;
6495 }
6496
6497 if (!NamedContext->isRecord()) {
6498 // Ideally this would point at the last name in the specifier,
6499 // but we don't have that level of source info.
6500 Diag(SS.getRange().getBegin(),
6501 diag::err_using_decl_nested_name_specifier_is_not_class)
6502 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6503 return true;
6504 }
6505
Douglas Gregor6fb07292010-12-21 07:41:49 +00006506 if (!NamedContext->isDependentContext() &&
6507 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6508 return true;
6509
David Blaikie4e4d0842012-03-11 07:00:24 +00006510 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006511 // C++0x [namespace.udecl]p3:
6512 // In a using-declaration used as a member-declaration, the
6513 // nested-name-specifier shall name a base class of the class
6514 // being defined.
6515
6516 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6517 cast<CXXRecordDecl>(NamedContext))) {
6518 if (CurContext == NamedContext) {
6519 Diag(NameLoc,
6520 diag::err_using_decl_nested_name_specifier_is_current_class)
6521 << SS.getRange();
6522 return true;
6523 }
6524
6525 Diag(SS.getRange().getBegin(),
6526 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6527 << (NestedNameSpecifier*) SS.getScopeRep()
6528 << cast<CXXRecordDecl>(CurContext)
6529 << SS.getRange();
6530 return true;
6531 }
6532
6533 return false;
6534 }
6535
6536 // C++03 [namespace.udecl]p4:
6537 // A using-declaration used as a member-declaration shall refer
6538 // to a member of a base class of the class being defined [etc.].
6539
6540 // Salient point: SS doesn't have to name a base class as long as
6541 // lookup only finds members from base classes. Therefore we can
6542 // diagnose here only if we can prove that that can't happen,
6543 // i.e. if the class hierarchies provably don't intersect.
6544
6545 // TODO: it would be nice if "definitely valid" results were cached
6546 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6547 // need to be repeated.
6548
6549 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006550 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006551
6552 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6553 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6554 Data->Bases.insert(Base);
6555 return true;
6556 }
6557
6558 bool hasDependentBases(const CXXRecordDecl *Class) {
6559 return !Class->forallBases(collect, this);
6560 }
6561
6562 /// Returns true if the base is dependent or is one of the
6563 /// accumulated base classes.
6564 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6565 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6566 return !Data->Bases.count(Base);
6567 }
6568
6569 bool mightShareBases(const CXXRecordDecl *Class) {
6570 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6571 }
6572 };
6573
6574 UserData Data;
6575
6576 // Returns false if we find a dependent base.
6577 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6578 return false;
6579
6580 // Returns false if the class has a dependent base or if it or one
6581 // of its bases is present in the base set of the current context.
6582 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6583 return false;
6584
6585 Diag(SS.getRange().getBegin(),
6586 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6587 << (NestedNameSpecifier*) SS.getScopeRep()
6588 << cast<CXXRecordDecl>(CurContext)
6589 << SS.getRange();
6590
6591 return true;
John McCalled976492009-12-04 22:46:56 +00006592}
6593
Richard Smith162e1c12011-04-15 14:24:37 +00006594Decl *Sema::ActOnAliasDeclaration(Scope *S,
6595 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006596 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006597 SourceLocation UsingLoc,
6598 UnqualifiedId &Name,
6599 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006600 // Skip up to the relevant declaration scope.
6601 while (S->getFlags() & Scope::TemplateParamScope)
6602 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006603 assert((S->getFlags() & Scope::DeclScope) &&
6604 "got alias-declaration outside of declaration scope");
6605
6606 if (Type.isInvalid())
6607 return 0;
6608
6609 bool Invalid = false;
6610 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6611 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006612 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006613
6614 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6615 return 0;
6616
6617 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006618 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006619 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006620 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6621 TInfo->getTypeLoc().getBeginLoc());
6622 }
Richard Smith162e1c12011-04-15 14:24:37 +00006623
6624 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6625 LookupName(Previous, S);
6626
6627 // Warn about shadowing the name of a template parameter.
6628 if (Previous.isSingleResult() &&
6629 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006630 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006631 Previous.clear();
6632 }
6633
6634 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6635 "name in alias declaration must be an identifier");
6636 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6637 Name.StartLocation,
6638 Name.Identifier, TInfo);
6639
6640 NewTD->setAccess(AS);
6641
6642 if (Invalid)
6643 NewTD->setInvalidDecl();
6644
Richard Smith3e4c6c42011-05-05 21:57:07 +00006645 CheckTypedefForVariablyModifiedType(S, NewTD);
6646 Invalid |= NewTD->isInvalidDecl();
6647
Richard Smith162e1c12011-04-15 14:24:37 +00006648 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006649
6650 NamedDecl *NewND;
6651 if (TemplateParamLists.size()) {
6652 TypeAliasTemplateDecl *OldDecl = 0;
6653 TemplateParameterList *OldTemplateParams = 0;
6654
6655 if (TemplateParamLists.size() != 1) {
6656 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6657 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6658 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6659 }
6660 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6661
6662 // Only consider previous declarations in the same scope.
6663 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6664 /*ExplicitInstantiationOrSpecialization*/false);
6665 if (!Previous.empty()) {
6666 Redeclaration = true;
6667
6668 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6669 if (!OldDecl && !Invalid) {
6670 Diag(UsingLoc, diag::err_redefinition_different_kind)
6671 << Name.Identifier;
6672
6673 NamedDecl *OldD = Previous.getRepresentativeDecl();
6674 if (OldD->getLocation().isValid())
6675 Diag(OldD->getLocation(), diag::note_previous_definition);
6676
6677 Invalid = true;
6678 }
6679
6680 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6681 if (TemplateParameterListsAreEqual(TemplateParams,
6682 OldDecl->getTemplateParameters(),
6683 /*Complain=*/true,
6684 TPL_TemplateMatch))
6685 OldTemplateParams = OldDecl->getTemplateParameters();
6686 else
6687 Invalid = true;
6688
6689 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6690 if (!Invalid &&
6691 !Context.hasSameType(OldTD->getUnderlyingType(),
6692 NewTD->getUnderlyingType())) {
6693 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6694 // but we can't reasonably accept it.
6695 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6696 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6697 if (OldTD->getLocation().isValid())
6698 Diag(OldTD->getLocation(), diag::note_previous_definition);
6699 Invalid = true;
6700 }
6701 }
6702 }
6703
6704 // Merge any previous default template arguments into our parameters,
6705 // and check the parameter list.
6706 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6707 TPC_TypeAliasTemplate))
6708 return 0;
6709
6710 TypeAliasTemplateDecl *NewDecl =
6711 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6712 Name.Identifier, TemplateParams,
6713 NewTD);
6714
6715 NewDecl->setAccess(AS);
6716
6717 if (Invalid)
6718 NewDecl->setInvalidDecl();
6719 else if (OldDecl)
6720 NewDecl->setPreviousDeclaration(OldDecl);
6721
6722 NewND = NewDecl;
6723 } else {
6724 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6725 NewND = NewTD;
6726 }
Richard Smith162e1c12011-04-15 14:24:37 +00006727
6728 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006729 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006730
Richard Smith3e4c6c42011-05-05 21:57:07 +00006731 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006732}
6733
John McCalld226f652010-08-21 09:40:31 +00006734Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006735 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006736 SourceLocation AliasLoc,
6737 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006738 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006739 SourceLocation IdentLoc,
6740 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006741
Anders Carlsson81c85c42009-03-28 23:53:49 +00006742 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006743 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6744 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006745
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006746 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006747 NamedDecl *PrevDecl
6748 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6749 ForRedeclaration);
6750 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6751 PrevDecl = 0;
6752
6753 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006754 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006755 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006756 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006757 // FIXME: At some point, we'll want to create the (redundant)
6758 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006759 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006760 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006761 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006762 }
Mike Stump1eb44332009-09-09 15:08:12 +00006763
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006764 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6765 diag::err_redefinition_different_kind;
6766 Diag(AliasLoc, DiagID) << Alias;
6767 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006768 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006769 }
6770
John McCalla24dc2e2009-11-17 02:14:36 +00006771 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006772 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006773
John McCallf36e02d2009-10-09 21:13:30 +00006774 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006775 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006776 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006777 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006778 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006779 }
Mike Stump1eb44332009-09-09 15:08:12 +00006780
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006781 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006782 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006783 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006784 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006785
John McCall3dbd3d52010-02-16 06:53:13 +00006786 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006787 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006788}
6789
Douglas Gregor39957dc2010-05-01 15:04:51 +00006790namespace {
6791 /// \brief Scoped object used to handle the state changes required in Sema
6792 /// to implicitly define the body of a C++ member function;
6793 class ImplicitlyDefinedFunctionScope {
6794 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006795 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006796
6797 public:
6798 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006799 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006800 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006801 S.PushFunctionScope();
6802 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6803 }
6804
6805 ~ImplicitlyDefinedFunctionScope() {
6806 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006807 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006808 }
6809 };
6810}
6811
Sean Hunt001cad92011-05-10 00:49:42 +00006812Sema::ImplicitExceptionSpecification
6813Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006814 // C++ [except.spec]p14:
6815 // An implicitly declared special member function (Clause 12) shall have an
6816 // exception-specification. [...]
6817 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006818 if (ClassDecl->isInvalidDecl())
6819 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006820
Sebastian Redl60618fa2011-03-12 11:50:43 +00006821 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006822 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6823 BEnd = ClassDecl->bases_end();
6824 B != BEnd; ++B) {
6825 if (B->isVirtual()) // Handled below.
6826 continue;
6827
Douglas Gregor18274032010-07-03 00:47:00 +00006828 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6829 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006830 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6831 // If this is a deleted function, add it anyway. This might be conformant
6832 // with the standard. This might not. I'm not sure. It might not matter.
6833 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006834 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006835 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006836 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006837
6838 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006839 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6840 BEnd = ClassDecl->vbases_end();
6841 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006842 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6843 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006844 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6845 // If this is a deleted function, add it anyway. This might be conformant
6846 // with the standard. This might not. I'm not sure. It might not matter.
6847 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006848 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006849 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006850 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006851
6852 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006853 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6854 FEnd = ClassDecl->field_end();
6855 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006856 if (F->hasInClassInitializer()) {
6857 if (Expr *E = F->getInClassInitializer())
6858 ExceptSpec.CalledExpr(E);
6859 else if (!F->isInvalidDecl())
6860 ExceptSpec.SetDelayed();
6861 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006862 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006863 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6864 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6865 // If this is a deleted function, add it anyway. This might be conformant
6866 // with the standard. This might not. I'm not sure. It might not matter.
6867 // In particular, the problem is that this function never gets called. It
6868 // might just be ill-formed because this function attempts to refer to
6869 // a deleted function here.
6870 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006871 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006872 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006873 }
John McCalle23cf432010-12-14 08:05:40 +00006874
Sean Hunt001cad92011-05-10 00:49:42 +00006875 return ExceptSpec;
6876}
6877
6878CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6879 CXXRecordDecl *ClassDecl) {
6880 // C++ [class.ctor]p5:
6881 // A default constructor for a class X is a constructor of class X
6882 // that can be called without an argument. If there is no
6883 // user-declared constructor for class X, a default constructor is
6884 // implicitly declared. An implicitly-declared default constructor
6885 // is an inline public member of its class.
6886 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6887 "Should not build implicit default constructor!");
6888
6889 ImplicitExceptionSpecification Spec =
6890 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6891 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006892
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006893 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006894 CanQualType ClassType
6895 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006896 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006897 DeclarationName Name
6898 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006899 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006900 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6901 Context, ClassDecl, ClassLoc, NameInfo,
6902 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6903 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6904 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006905 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006906 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006907 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006908 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006909 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006910
6911 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006912 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6913
Douglas Gregor23c94db2010-07-02 17:43:08 +00006914 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006915 PushOnScopeChains(DefaultCon, S, false);
6916 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006917
Sean Hunte16da072011-10-10 06:18:57 +00006918 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006919 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006920
Douglas Gregor32df23e2010-07-01 22:02:46 +00006921 return DefaultCon;
6922}
6923
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006924void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6925 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006926 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006927 !Constructor->doesThisDeclarationHaveABody() &&
6928 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006929 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006931 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006932 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006933
Douglas Gregor39957dc2010-05-01 15:04:51 +00006934 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006935 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006936 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006937 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006938 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006939 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006940 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006941 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006942 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006943
6944 SourceLocation Loc = Constructor->getLocation();
6945 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6946
6947 Constructor->setUsed();
6948 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006949
6950 if (ASTMutationListener *L = getASTMutationListener()) {
6951 L->CompletedImplicitDefinition(Constructor);
6952 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006953}
6954
Richard Smith7a614d82011-06-11 17:19:42 +00006955/// Get any existing defaulted default constructor for the given class. Do not
6956/// implicitly define one if it does not exist.
6957static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6958 CXXRecordDecl *D) {
6959 ASTContext &Context = Self.Context;
6960 QualType ClassType = Context.getTypeDeclType(D);
6961 DeclarationName ConstructorName
6962 = Context.DeclarationNames.getCXXConstructorName(
6963 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6964
6965 DeclContext::lookup_const_iterator Con, ConEnd;
6966 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6967 Con != ConEnd; ++Con) {
6968 // A function template cannot be defaulted.
6969 if (isa<FunctionTemplateDecl>(*Con))
6970 continue;
6971
6972 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6973 if (Constructor->isDefaultConstructor())
6974 return Constructor->isDefaulted() ? Constructor : 0;
6975 }
6976 return 0;
6977}
6978
6979void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6980 if (!D) return;
6981 AdjustDeclIfTemplate(D);
6982
6983 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6984 CXXConstructorDecl *CtorDecl
6985 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6986
6987 if (!CtorDecl) return;
6988
6989 // Compute the exception specification for the default constructor.
6990 const FunctionProtoType *CtorTy =
6991 CtorDecl->getType()->castAs<FunctionProtoType>();
6992 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6993 ImplicitExceptionSpecification Spec =
6994 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6995 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6996 assert(EPI.ExceptionSpecType != EST_Delayed);
6997
6998 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6999 }
7000
7001 // If the default constructor is explicitly defaulted, checking the exception
7002 // specification is deferred until now.
7003 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7004 !ClassDecl->isDependentType())
7005 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7006}
7007
Sebastian Redlf677ea32011-02-05 19:23:19 +00007008void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7009 // We start with an initial pass over the base classes to collect those that
7010 // inherit constructors from. If there are none, we can forgo all further
7011 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007012 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007013 BasesVector BasesToInheritFrom;
7014 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7015 BaseE = ClassDecl->bases_end();
7016 BaseIt != BaseE; ++BaseIt) {
7017 if (BaseIt->getInheritConstructors()) {
7018 QualType Base = BaseIt->getType();
7019 if (Base->isDependentType()) {
7020 // If we inherit constructors from anything that is dependent, just
7021 // abort processing altogether. We'll get another chance for the
7022 // instantiations.
7023 return;
7024 }
7025 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7026 }
7027 }
7028 if (BasesToInheritFrom.empty())
7029 return;
7030
7031 // Now collect the constructors that we already have in the current class.
7032 // Those take precedence over inherited constructors.
7033 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7034 // unless there is a user-declared constructor with the same signature in
7035 // the class where the using-declaration appears.
7036 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7037 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7038 CtorE = ClassDecl->ctor_end();
7039 CtorIt != CtorE; ++CtorIt) {
7040 ExistingConstructors.insert(
7041 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7042 }
7043
Sebastian Redlf677ea32011-02-05 19:23:19 +00007044 DeclarationName CreatedCtorName =
7045 Context.DeclarationNames.getCXXConstructorName(
7046 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7047
7048 // Now comes the true work.
7049 // First, we keep a map from constructor types to the base that introduced
7050 // them. Needed for finding conflicting constructors. We also keep the
7051 // actually inserted declarations in there, for pretty diagnostics.
7052 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7053 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7054 ConstructorToSourceMap InheritedConstructors;
7055 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7056 BaseE = BasesToInheritFrom.end();
7057 BaseIt != BaseE; ++BaseIt) {
7058 const RecordType *Base = *BaseIt;
7059 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7060 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7061 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7062 CtorE = BaseDecl->ctor_end();
7063 CtorIt != CtorE; ++CtorIt) {
7064 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007065 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007066 DeclarationName Name =
7067 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007068 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7069 LookupQualifiedName(Result, CurContext);
7070 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007071 SourceLocation UsingLoc = UD ? UD->getLocation() :
7072 ClassDecl->getLocation();
7073
7074 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7075 // from the class X named in the using-declaration consists of actual
7076 // constructors and notional constructors that result from the
7077 // transformation of defaulted parameters as follows:
7078 // - all non-template default constructors of X, and
7079 // - for each non-template constructor of X that has at least one
7080 // parameter with a default argument, the set of constructors that
7081 // results from omitting any ellipsis parameter specification and
7082 // successively omitting parameters with a default argument from the
7083 // end of the parameter-type-list.
7084 CXXConstructorDecl *BaseCtor = *CtorIt;
7085 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7086 const FunctionProtoType *BaseCtorType =
7087 BaseCtor->getType()->getAs<FunctionProtoType>();
7088
7089 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7090 maxParams = BaseCtor->getNumParams();
7091 params <= maxParams; ++params) {
7092 // Skip default constructors. They're never inherited.
7093 if (params == 0)
7094 continue;
7095 // Skip copy and move constructors for the same reason.
7096 if (CanBeCopyOrMove && params == 1)
7097 continue;
7098
7099 // Build up a function type for this particular constructor.
7100 // FIXME: The working paper does not consider that the exception spec
7101 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007102 // source. This code doesn't yet, either. When it does, this code will
7103 // need to be delayed until after exception specifications and in-class
7104 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007105 const Type *NewCtorType;
7106 if (params == maxParams)
7107 NewCtorType = BaseCtorType;
7108 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007109 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007110 for (unsigned i = 0; i < params; ++i) {
7111 Args.push_back(BaseCtorType->getArgType(i));
7112 }
7113 FunctionProtoType::ExtProtoInfo ExtInfo =
7114 BaseCtorType->getExtProtoInfo();
7115 ExtInfo.Variadic = false;
7116 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7117 Args.data(), params, ExtInfo)
7118 .getTypePtr();
7119 }
7120 const Type *CanonicalNewCtorType =
7121 Context.getCanonicalType(NewCtorType);
7122
7123 // Now that we have the type, first check if the class already has a
7124 // constructor with this signature.
7125 if (ExistingConstructors.count(CanonicalNewCtorType))
7126 continue;
7127
7128 // Then we check if we have already declared an inherited constructor
7129 // with this signature.
7130 std::pair<ConstructorToSourceMap::iterator, bool> result =
7131 InheritedConstructors.insert(std::make_pair(
7132 CanonicalNewCtorType,
7133 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7134 if (!result.second) {
7135 // Already in the map. If it came from a different class, that's an
7136 // error. Not if it's from the same.
7137 CanQualType PreviousBase = result.first->second.first;
7138 if (CanonicalBase != PreviousBase) {
7139 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7140 const CXXConstructorDecl *PrevBaseCtor =
7141 PrevCtor->getInheritedConstructor();
7142 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7143
7144 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7145 Diag(BaseCtor->getLocation(),
7146 diag::note_using_decl_constructor_conflict_current_ctor);
7147 Diag(PrevBaseCtor->getLocation(),
7148 diag::note_using_decl_constructor_conflict_previous_ctor);
7149 Diag(PrevCtor->getLocation(),
7150 diag::note_using_decl_constructor_conflict_previous_using);
7151 }
7152 continue;
7153 }
7154
7155 // OK, we're there, now add the constructor.
7156 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007157 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007158 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7159 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007160 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7161 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007162 /*ImplicitlyDeclared=*/true,
7163 // FIXME: Due to a defect in the standard, we treat inherited
7164 // constructors as constexpr even if that makes them ill-formed.
7165 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007166 NewCtor->setAccess(BaseCtor->getAccess());
7167
7168 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007169 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007170 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007171 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7172 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007173 /*IdentifierInfo=*/0,
7174 BaseCtorType->getArgType(i),
7175 /*TInfo=*/0, SC_None,
7176 SC_None, /*DefaultArg=*/0));
7177 }
David Blaikie4278c652011-09-21 18:16:56 +00007178 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007179 NewCtor->setInheritedConstructor(BaseCtor);
7180
Sebastian Redlf677ea32011-02-05 19:23:19 +00007181 ClassDecl->addDecl(NewCtor);
7182 result.first->second.second = NewCtor;
7183 }
7184 }
7185 }
7186}
7187
Sean Huntcb45a0f2011-05-12 22:46:25 +00007188Sema::ImplicitExceptionSpecification
7189Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007190 // C++ [except.spec]p14:
7191 // An implicitly declared special member function (Clause 12) shall have
7192 // an exception-specification.
7193 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007194 if (ClassDecl->isInvalidDecl())
7195 return ExceptSpec;
7196
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007197 // Direct base-class destructors.
7198 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7199 BEnd = ClassDecl->bases_end();
7200 B != BEnd; ++B) {
7201 if (B->isVirtual()) // Handled below.
7202 continue;
7203
7204 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7205 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007206 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007207 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007208
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007209 // Virtual base-class destructors.
7210 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7211 BEnd = ClassDecl->vbases_end();
7212 B != BEnd; ++B) {
7213 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7214 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007215 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007216 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007217
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007218 // Field destructors.
7219 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7220 FEnd = ClassDecl->field_end();
7221 F != FEnd; ++F) {
7222 if (const RecordType *RecordTy
7223 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7224 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007225 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007226 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007227
Sean Huntcb45a0f2011-05-12 22:46:25 +00007228 return ExceptSpec;
7229}
7230
7231CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7232 // C++ [class.dtor]p2:
7233 // If a class has no user-declared destructor, a destructor is
7234 // declared implicitly. An implicitly-declared destructor is an
7235 // inline public member of its class.
7236
7237 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007238 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007239 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7240
Douglas Gregor4923aa22010-07-02 20:37:36 +00007241 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007242 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007243
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007244 CanQualType ClassType
7245 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007246 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007247 DeclarationName Name
7248 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007249 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007250 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007251 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7252 /*isInline=*/true,
7253 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007254 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007255 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007256 Destructor->setImplicit();
7257 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007258
7259 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007260 ++ASTContext::NumImplicitDestructorsDeclared;
7261
7262 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007263 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007264 PushOnScopeChains(Destructor, S, false);
7265 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007266
7267 // This could be uniqued if it ever proves significant.
7268 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007269
Richard Smith9a561d52012-02-26 09:11:52 +00007270 AddOverriddenMethods(ClassDecl, Destructor);
7271
Richard Smith7d5088a2012-02-18 02:02:13 +00007272 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007273 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007274
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007275 return Destructor;
7276}
7277
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007278void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007279 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007280 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007281 !Destructor->doesThisDeclarationHaveABody() &&
7282 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007283 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007284 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007285 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007286
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007287 if (Destructor->isInvalidDecl())
7288 return;
7289
Douglas Gregor39957dc2010-05-01 15:04:51 +00007290 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007291
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007292 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007293 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7294 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007295
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007296 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007297 Diag(CurrentLocation, diag::note_member_synthesized_at)
7298 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7299
7300 Destructor->setInvalidDecl();
7301 return;
7302 }
7303
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007304 SourceLocation Loc = Destructor->getLocation();
7305 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007306 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007307 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007308 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007309
7310 if (ASTMutationListener *L = getASTMutationListener()) {
7311 L->CompletedImplicitDefinition(Destructor);
7312 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007313}
7314
Sebastian Redl0ee33912011-05-19 05:13:44 +00007315void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7316 CXXDestructorDecl *destructor) {
7317 // C++11 [class.dtor]p3:
7318 // A declaration of a destructor that does not have an exception-
7319 // specification is implicitly considered to have the same exception-
7320 // specification as an implicit declaration.
7321 const FunctionProtoType *dtorType = destructor->getType()->
7322 getAs<FunctionProtoType>();
7323 if (dtorType->hasExceptionSpec())
7324 return;
7325
7326 ImplicitExceptionSpecification exceptSpec =
7327 ComputeDefaultedDtorExceptionSpec(classDecl);
7328
Chandler Carruth3f224b22011-09-20 04:55:26 +00007329 // Replace the destructor's type, building off the existing one. Fortunately,
7330 // the only thing of interest in the destructor type is its extended info.
7331 // The return and arguments are fixed.
7332 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007333 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7334 epi.NumExceptions = exceptSpec.size();
7335 epi.Exceptions = exceptSpec.data();
7336 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7337
7338 destructor->setType(ty);
7339
7340 // FIXME: If the destructor has a body that could throw, and the newly created
7341 // spec doesn't allow exceptions, we should emit a warning, because this
7342 // change in behavior can break conforming C++03 programs at runtime.
7343 // However, we don't have a body yet, so it needs to be done somewhere else.
7344}
7345
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007346/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007347/// \c To.
7348///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007349/// This routine is used to copy/move the members of a class with an
7350/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007351/// copied are arrays, this routine builds for loops to copy them.
7352///
7353/// \param S The Sema object used for type-checking.
7354///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007355/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007356///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007357/// \param T The type of the expressions being copied/moved. Both expressions
7358/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007359///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007360/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007361///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007362/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007363///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007364/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007365/// Otherwise, it's a non-static member subobject.
7366///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007367/// \param Copying Whether we're copying or moving.
7368///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007369/// \param Depth Internal parameter recording the depth of the recursion.
7370///
7371/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007372static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007373BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007374 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007375 bool CopyingBaseSubobject, bool Copying,
7376 unsigned Depth = 0) {
7377 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007378 // Each subobject is assigned in the manner appropriate to its type:
7379 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007380 // - if the subobject is of class type, as if by a call to operator= with
7381 // the subobject as the object expression and the corresponding
7382 // subobject of x as a single function argument (as if by explicit
7383 // qualification; that is, ignoring any possible virtual overriding
7384 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007385 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7386 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7387
7388 // Look for operator=.
7389 DeclarationName Name
7390 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7391 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7392 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7393
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007394 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007395 LookupResult::Filter F = OpLookup.makeFilter();
7396 while (F.hasNext()) {
7397 NamedDecl *D = F.next();
7398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007399 if (Method->isCopyAssignmentOperator() ||
7400 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007401 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007402
Douglas Gregor06a9f362010-05-01 20:49:11 +00007403 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007404 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007405 F.done();
7406
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007407 // Suppress the protected check (C++ [class.protected]) for each of the
7408 // assignment operators we found. This strange dance is required when
7409 // we're assigning via a base classes's copy-assignment operator. To
7410 // ensure that we're getting the right base class subobject (without
7411 // ambiguities), we need to cast "this" to that subobject type; to
7412 // ensure that we don't go through the virtual call mechanism, we need
7413 // to qualify the operator= name with the base class (see below). However,
7414 // this means that if the base class has a protected copy assignment
7415 // operator, the protected member access check will fail. So, we
7416 // rewrite "protected" access to "public" access in this case, since we
7417 // know by construction that we're calling from a derived class.
7418 if (CopyingBaseSubobject) {
7419 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7420 L != LEnd; ++L) {
7421 if (L.getAccess() == AS_protected)
7422 L.setAccess(AS_public);
7423 }
7424 }
7425
Douglas Gregor06a9f362010-05-01 20:49:11 +00007426 // Create the nested-name-specifier that will be used to qualify the
7427 // reference to operator=; this is required to suppress the virtual
7428 // call mechanism.
7429 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007430 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007431 SS.MakeTrivial(S.Context,
7432 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007433 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007434 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007435
7436 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007437 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007438 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007439 /*TemplateKWLoc=*/SourceLocation(),
7440 /*FirstQualifierInScope=*/0,
7441 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007442 /*TemplateArgs=*/0,
7443 /*SuppressQualifierCheck=*/true);
7444 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007445 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007446
7447 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007448
John McCall60d7b3a2010-08-24 06:29:42 +00007449 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007450 OpEqualRef.takeAs<Expr>(),
7451 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007452 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007453 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007454
7455 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007456 }
John McCallb0207482010-03-16 06:11:48 +00007457
Douglas Gregor06a9f362010-05-01 20:49:11 +00007458 // - if the subobject is of scalar type, the built-in assignment
7459 // operator is used.
7460 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7461 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007462 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007463 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007464 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007465
7466 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007467 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007468
7469 // - if the subobject is an array, each element is assigned, in the
7470 // manner appropriate to the element type;
7471
7472 // Construct a loop over the array bounds, e.g.,
7473 //
7474 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7475 //
7476 // that will copy each of the array elements.
7477 QualType SizeType = S.Context.getSizeType();
7478
7479 // Create the iteration variable.
7480 IdentifierInfo *IterationVarName = 0;
7481 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007482 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007483 llvm::raw_svector_ostream OS(Str);
7484 OS << "__i" << Depth;
7485 IterationVarName = &S.Context.Idents.get(OS.str());
7486 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007487 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007488 IterationVarName, SizeType,
7489 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007490 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007491
7492 // Initialize the iteration variable to zero.
7493 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007494 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007495
7496 // Create a reference to the iteration variable; we'll use this several
7497 // times throughout.
7498 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007499 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007500 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007501 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7502 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7503
Douglas Gregor06a9f362010-05-01 20:49:11 +00007504 // Create the DeclStmt that holds the iteration variable.
7505 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7506
7507 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007508 llvm::APInt Upper
7509 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007510 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007511 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007512 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7513 BO_NE, S.Context.BoolTy,
7514 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007515
7516 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007517 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007518 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7519 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007520
7521 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007522 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007523 IterationVarRefRVal,
7524 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007525 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007526 IterationVarRefRVal,
7527 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007528 if (!Copying) // Cast to rvalue
7529 From = CastForMoving(S, From);
7530
7531 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007532 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7533 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007534 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007535 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007536 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007537
7538 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007539 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007540 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007541 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007542 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007543}
7544
Sean Hunt30de05c2011-05-14 05:23:20 +00007545std::pair<Sema::ImplicitExceptionSpecification, bool>
7546Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7547 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007548 if (ClassDecl->isInvalidDecl())
7549 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7550
Douglas Gregord3c35902010-07-01 16:36:15 +00007551 // C++ [class.copy]p10:
7552 // If the class definition does not explicitly declare a copy
7553 // assignment operator, one is declared implicitly.
7554 // The implicitly-defined copy assignment operator for a class X
7555 // will have the form
7556 //
7557 // X& X::operator=(const X&)
7558 //
7559 // if
7560 bool HasConstCopyAssignment = true;
7561
7562 // -- each direct base class B of X has a copy assignment operator
7563 // whose parameter is of type const B&, const volatile B& or B,
7564 // and
7565 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7566 BaseEnd = ClassDecl->bases_end();
7567 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007568 // We'll handle this below
7569 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7570 continue;
7571
Douglas Gregord3c35902010-07-01 16:36:15 +00007572 assert(!Base->getType()->isDependentType() &&
7573 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007574 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7575 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7576 &HasConstCopyAssignment);
7577 }
7578
Richard Smithebaf0e62011-10-18 20:49:44 +00007579 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007580 if (LangOpts.CPlusPlus0x) {
7581 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7582 BaseEnd = ClassDecl->vbases_end();
7583 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7584 assert(!Base->getType()->isDependentType() &&
7585 "Cannot generate implicit members for class with dependent bases.");
7586 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7587 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7588 &HasConstCopyAssignment);
7589 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007590 }
7591
7592 // -- for all the nonstatic data members of X that are of a class
7593 // type M (or array thereof), each such class type has a copy
7594 // assignment operator whose parameter is of type const M&,
7595 // const volatile M& or M.
7596 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7597 FieldEnd = ClassDecl->field_end();
7598 HasConstCopyAssignment && Field != FieldEnd;
7599 ++Field) {
7600 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007601 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7602 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7603 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007604 }
7605 }
7606
7607 // Otherwise, the implicitly declared copy assignment operator will
7608 // have the form
7609 //
7610 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007611
Douglas Gregorb87786f2010-07-01 17:48:08 +00007612 // C++ [except.spec]p14:
7613 // An implicitly declared special member function (Clause 12) shall have an
7614 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007615
7616 // It is unspecified whether or not an implicit copy assignment operator
7617 // attempts to deduplicate calls to assignment operators of virtual bases are
7618 // made. As such, this exception specification is effectively unspecified.
7619 // Based on a similar decision made for constness in C++0x, we're erring on
7620 // the side of assuming such calls to be made regardless of whether they
7621 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007622 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007623 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007624 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7625 BaseEnd = ClassDecl->bases_end();
7626 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007627 if (Base->isVirtual())
7628 continue;
7629
Douglas Gregora376d102010-07-02 21:50:04 +00007630 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007631 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007632 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7633 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007634 ExceptSpec.CalledDecl(CopyAssign);
7635 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007636
7637 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7638 BaseEnd = ClassDecl->vbases_end();
7639 Base != BaseEnd; ++Base) {
7640 CXXRecordDecl *BaseClassDecl
7641 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7642 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7643 ArgQuals, false, 0))
7644 ExceptSpec.CalledDecl(CopyAssign);
7645 }
7646
Douglas Gregorb87786f2010-07-01 17:48:08 +00007647 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7648 FieldEnd = ClassDecl->field_end();
7649 Field != FieldEnd;
7650 ++Field) {
7651 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007652 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7653 if (CXXMethodDecl *CopyAssign =
7654 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7655 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007656 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007657 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007658
Sean Hunt30de05c2011-05-14 05:23:20 +00007659 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7660}
7661
7662CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7663 // Note: The following rules are largely analoguous to the copy
7664 // constructor rules. Note that virtual bases are not taken into account
7665 // for determining the argument type of the operator. Note also that
7666 // operators taking an object instead of a reference are allowed.
7667
7668 ImplicitExceptionSpecification Spec(Context);
7669 bool Const;
7670 llvm::tie(Spec, Const) =
7671 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7672
7673 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7674 QualType RetType = Context.getLValueReferenceType(ArgType);
7675 if (Const)
7676 ArgType = ArgType.withConst();
7677 ArgType = Context.getLValueReferenceType(ArgType);
7678
Douglas Gregord3c35902010-07-01 16:36:15 +00007679 // An implicitly-declared copy assignment operator is an inline public
7680 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007681 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007682 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007683 SourceLocation ClassLoc = ClassDecl->getLocation();
7684 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007685 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007686 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007687 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007688 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007689 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007690 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007691 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007692 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007693 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007694 CopyAssignment->setImplicit();
7695 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007696
7697 // Add the parameter to the operator.
7698 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007699 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007700 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007701 SC_None,
7702 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007703 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007704
Douglas Gregora376d102010-07-02 21:50:04 +00007705 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007706 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007707
Douglas Gregor23c94db2010-07-02 17:43:08 +00007708 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007709 PushOnScopeChains(CopyAssignment, S, false);
7710 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007711
Nico Weberafcc96a2012-01-23 03:19:29 +00007712 // C++0x [class.copy]p19:
7713 // .... If the class definition does not explicitly declare a copy
7714 // assignment operator, there is no user-declared move constructor, and
7715 // there is no user-declared move assignment operator, a copy assignment
7716 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007717 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007718 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007719
Douglas Gregord3c35902010-07-01 16:36:15 +00007720 AddOverriddenMethods(ClassDecl, CopyAssignment);
7721 return CopyAssignment;
7722}
7723
Douglas Gregor06a9f362010-05-01 20:49:11 +00007724void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7725 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007726 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007727 CopyAssignOperator->isOverloadedOperator() &&
7728 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007729 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7730 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007731 "DefineImplicitCopyAssignment called for wrong function");
7732
7733 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7734
7735 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7736 CopyAssignOperator->setInvalidDecl();
7737 return;
7738 }
7739
7740 CopyAssignOperator->setUsed();
7741
7742 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007743 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007744
7745 // C++0x [class.copy]p30:
7746 // The implicitly-defined or explicitly-defaulted copy assignment operator
7747 // for a non-union class X performs memberwise copy assignment of its
7748 // subobjects. The direct base classes of X are assigned first, in the
7749 // order of their declaration in the base-specifier-list, and then the
7750 // immediate non-static data members of X are assigned, in the order in
7751 // which they were declared in the class definition.
7752
7753 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007754 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007755
7756 // The parameter for the "other" object, which we are copying from.
7757 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7758 Qualifiers OtherQuals = Other->getType().getQualifiers();
7759 QualType OtherRefType = Other->getType();
7760 if (const LValueReferenceType *OtherRef
7761 = OtherRefType->getAs<LValueReferenceType>()) {
7762 OtherRefType = OtherRef->getPointeeType();
7763 OtherQuals = OtherRefType.getQualifiers();
7764 }
7765
7766 // Our location for everything implicitly-generated.
7767 SourceLocation Loc = CopyAssignOperator->getLocation();
7768
7769 // Construct a reference to the "other" object. We'll be using this
7770 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007771 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007772 assert(OtherRef && "Reference to parameter cannot fail!");
7773
7774 // Construct the "this" pointer. We'll be using this throughout the generated
7775 // ASTs.
7776 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7777 assert(This && "Reference to this cannot fail!");
7778
7779 // Assign base classes.
7780 bool Invalid = false;
7781 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7782 E = ClassDecl->bases_end(); Base != E; ++Base) {
7783 // Form the assignment:
7784 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7785 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007786 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007787 Invalid = true;
7788 continue;
7789 }
7790
John McCallf871d0c2010-08-07 06:22:56 +00007791 CXXCastPath BasePath;
7792 BasePath.push_back(Base);
7793
Douglas Gregor06a9f362010-05-01 20:49:11 +00007794 // Construct the "from" expression, which is an implicit cast to the
7795 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007796 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007797 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7798 CK_UncheckedDerivedToBase,
7799 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007800
7801 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007802 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007803
7804 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007805 To = ImpCastExprToType(To.take(),
7806 Context.getCVRQualifiedType(BaseType,
7807 CopyAssignOperator->getTypeQualifiers()),
7808 CK_UncheckedDerivedToBase,
7809 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007810
7811 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007812 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007813 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007814 /*CopyingBaseSubobject=*/true,
7815 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007816 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007817 Diag(CurrentLocation, diag::note_member_synthesized_at)
7818 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7819 CopyAssignOperator->setInvalidDecl();
7820 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007821 }
7822
7823 // Success! Record the copy.
7824 Statements.push_back(Copy.takeAs<Expr>());
7825 }
7826
7827 // \brief Reference to the __builtin_memcpy function.
7828 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007829 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007830 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007831
7832 // Assign non-static members.
7833 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7834 FieldEnd = ClassDecl->field_end();
7835 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007836 if (Field->isUnnamedBitfield())
7837 continue;
7838
Douglas Gregor06a9f362010-05-01 20:49:11 +00007839 // Check for members of reference type; we can't copy those.
7840 if (Field->getType()->isReferenceType()) {
7841 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7842 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7843 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007844 Diag(CurrentLocation, diag::note_member_synthesized_at)
7845 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007846 Invalid = true;
7847 continue;
7848 }
7849
7850 // Check for members of const-qualified, non-class type.
7851 QualType BaseType = Context.getBaseElementType(Field->getType());
7852 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7853 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7854 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7855 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007856 Diag(CurrentLocation, diag::note_member_synthesized_at)
7857 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007858 Invalid = true;
7859 continue;
7860 }
John McCallb77115d2011-06-17 00:18:42 +00007861
7862 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007863 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7864 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007865
7866 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007867 if (FieldType->isIncompleteArrayType()) {
7868 assert(ClassDecl->hasFlexibleArrayMember() &&
7869 "Incomplete array type is not valid");
7870 continue;
7871 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007872
7873 // Build references to the field in the object we're copying from and to.
7874 CXXScopeSpec SS; // Intentionally empty
7875 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7876 LookupMemberName);
7877 MemberLookup.addDecl(*Field);
7878 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007879 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007880 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007881 SS, SourceLocation(), 0,
7882 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007883 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007884 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007885 SS, SourceLocation(), 0,
7886 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007887 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7888 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7889
7890 // If the field should be copied with __builtin_memcpy rather than via
7891 // explicit assignments, do so. This optimization only applies for arrays
7892 // of scalars and arrays of class type with trivial copy-assignment
7893 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007894 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007895 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007896 // Compute the size of the memory buffer to be copied.
7897 QualType SizeType = Context.getSizeType();
7898 llvm::APInt Size(Context.getTypeSize(SizeType),
7899 Context.getTypeSizeInChars(BaseType).getQuantity());
7900 for (const ConstantArrayType *Array
7901 = Context.getAsConstantArrayType(FieldType);
7902 Array;
7903 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007904 llvm::APInt ArraySize
7905 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007906 Size *= ArraySize;
7907 }
7908
7909 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007910 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7911 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007912
7913 bool NeedsCollectableMemCpy =
7914 (BaseType->isRecordType() &&
7915 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7916
7917 if (NeedsCollectableMemCpy) {
7918 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007919 // Create a reference to the __builtin_objc_memmove_collectable function.
7920 LookupResult R(*this,
7921 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007922 Loc, LookupOrdinaryName);
7923 LookupName(R, TUScope, true);
7924
7925 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7926 if (!CollectableMemCpy) {
7927 // Something went horribly wrong earlier, and we will have
7928 // complained about it.
7929 Invalid = true;
7930 continue;
7931 }
7932
7933 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7934 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007935 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007936 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7937 }
7938 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007939 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007940 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007941 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7942 LookupOrdinaryName);
7943 LookupName(R, TUScope, true);
7944
7945 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7946 if (!BuiltinMemCpy) {
7947 // Something went horribly wrong earlier, and we will have complained
7948 // about it.
7949 Invalid = true;
7950 continue;
7951 }
7952
7953 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7954 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007955 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007956 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7957 }
7958
John McCallca0408f2010-08-23 06:44:23 +00007959 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007960 CallArgs.push_back(To.takeAs<Expr>());
7961 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007962 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007963 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007964 if (NeedsCollectableMemCpy)
7965 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007966 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007967 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007968 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007969 else
7970 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007971 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007972 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007973 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007974
Douglas Gregor06a9f362010-05-01 20:49:11 +00007975 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7976 Statements.push_back(Call.takeAs<Expr>());
7977 continue;
7978 }
7979
7980 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007981 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007982 To.get(), From.get(),
7983 /*CopyingBaseSubobject=*/false,
7984 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007985 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007986 Diag(CurrentLocation, diag::note_member_synthesized_at)
7987 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7988 CopyAssignOperator->setInvalidDecl();
7989 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990 }
7991
7992 // Success! Record the copy.
7993 Statements.push_back(Copy.takeAs<Stmt>());
7994 }
7995
7996 if (!Invalid) {
7997 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007998 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007999
John McCall60d7b3a2010-08-24 06:29:42 +00008000 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008001 if (Return.isInvalid())
8002 Invalid = true;
8003 else {
8004 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008005
8006 if (Trap.hasErrorOccurred()) {
8007 Diag(CurrentLocation, diag::note_member_synthesized_at)
8008 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8009 Invalid = true;
8010 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011 }
8012 }
8013
8014 if (Invalid) {
8015 CopyAssignOperator->setInvalidDecl();
8016 return;
8017 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008018
8019 StmtResult Body;
8020 {
8021 CompoundScopeRAII CompoundScope(*this);
8022 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8023 /*isStmtExpr=*/false);
8024 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8025 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008026 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008027
8028 if (ASTMutationListener *L = getASTMutationListener()) {
8029 L->CompletedImplicitDefinition(CopyAssignOperator);
8030 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008031}
8032
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008033Sema::ImplicitExceptionSpecification
8034Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8035 ImplicitExceptionSpecification ExceptSpec(Context);
8036
8037 if (ClassDecl->isInvalidDecl())
8038 return ExceptSpec;
8039
8040 // C++0x [except.spec]p14:
8041 // An implicitly declared special member function (Clause 12) shall have an
8042 // exception-specification. [...]
8043
8044 // It is unspecified whether or not an implicit move assignment operator
8045 // attempts to deduplicate calls to assignment operators of virtual bases are
8046 // made. As such, this exception specification is effectively unspecified.
8047 // Based on a similar decision made for constness in C++0x, we're erring on
8048 // the side of assuming such calls to be made regardless of whether they
8049 // actually happen.
8050 // Note that a move constructor is not implicitly declared when there are
8051 // virtual bases, but it can still be user-declared and explicitly defaulted.
8052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8053 BaseEnd = ClassDecl->bases_end();
8054 Base != BaseEnd; ++Base) {
8055 if (Base->isVirtual())
8056 continue;
8057
8058 CXXRecordDecl *BaseClassDecl
8059 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8060 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8061 false, 0))
8062 ExceptSpec.CalledDecl(MoveAssign);
8063 }
8064
8065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8066 BaseEnd = ClassDecl->vbases_end();
8067 Base != BaseEnd; ++Base) {
8068 CXXRecordDecl *BaseClassDecl
8069 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8070 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8071 false, 0))
8072 ExceptSpec.CalledDecl(MoveAssign);
8073 }
8074
8075 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8076 FieldEnd = ClassDecl->field_end();
8077 Field != FieldEnd;
8078 ++Field) {
8079 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8080 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8081 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8082 false, 0))
8083 ExceptSpec.CalledDecl(MoveAssign);
8084 }
8085 }
8086
8087 return ExceptSpec;
8088}
8089
Richard Smith1c931be2012-04-02 18:40:40 +00008090/// Determine whether the class type has any direct or indirect virtual base
8091/// classes which have a non-trivial move assignment operator.
8092static bool
8093hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8094 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8095 BaseEnd = ClassDecl->vbases_end();
8096 Base != BaseEnd; ++Base) {
8097 CXXRecordDecl *BaseClass =
8098 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8099
8100 // Try to declare the move assignment. If it would be deleted, then the
8101 // class does not have a non-trivial move assignment.
8102 if (BaseClass->needsImplicitMoveAssignment())
8103 S.DeclareImplicitMoveAssignment(BaseClass);
8104
8105 // If the class has both a trivial move assignment and a non-trivial move
8106 // assignment, hasTrivialMoveAssignment() is false.
8107 if (BaseClass->hasDeclaredMoveAssignment() &&
8108 !BaseClass->hasTrivialMoveAssignment())
8109 return true;
8110 }
8111
8112 return false;
8113}
8114
8115/// Determine whether the given type either has a move constructor or is
8116/// trivially copyable.
8117static bool
8118hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8119 Type = S.Context.getBaseElementType(Type);
8120
8121 // FIXME: Technically, non-trivially-copyable non-class types, such as
8122 // reference types, are supposed to return false here, but that appears
8123 // to be a standard defect.
8124 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8125 if (!ClassDecl)
8126 return true;
8127
8128 if (Type.isTriviallyCopyableType(S.Context))
8129 return true;
8130
8131 if (IsConstructor) {
8132 if (ClassDecl->needsImplicitMoveConstructor())
8133 S.DeclareImplicitMoveConstructor(ClassDecl);
8134 return ClassDecl->hasDeclaredMoveConstructor();
8135 }
8136
8137 if (ClassDecl->needsImplicitMoveAssignment())
8138 S.DeclareImplicitMoveAssignment(ClassDecl);
8139 return ClassDecl->hasDeclaredMoveAssignment();
8140}
8141
8142/// Determine whether all non-static data members and direct or virtual bases
8143/// of class \p ClassDecl have either a move operation, or are trivially
8144/// copyable.
8145static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8146 bool IsConstructor) {
8147 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8148 BaseEnd = ClassDecl->bases_end();
8149 Base != BaseEnd; ++Base) {
8150 if (Base->isVirtual())
8151 continue;
8152
8153 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8154 return false;
8155 }
8156
8157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8158 BaseEnd = ClassDecl->vbases_end();
8159 Base != BaseEnd; ++Base) {
8160 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8161 return false;
8162 }
8163
8164 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8165 FieldEnd = ClassDecl->field_end();
8166 Field != FieldEnd; ++Field) {
8167 if (!hasMoveOrIsTriviallyCopyable(S, (*Field)->getType(), IsConstructor))
8168 return false;
8169 }
8170
8171 return true;
8172}
8173
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008174CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008175 // C++11 [class.copy]p20:
8176 // If the definition of a class X does not explicitly declare a move
8177 // assignment operator, one will be implicitly declared as defaulted
8178 // if and only if:
8179 //
8180 // - [first 4 bullets]
8181 assert(ClassDecl->needsImplicitMoveAssignment());
8182
8183 // [Checked after we build the declaration]
8184 // - the move assignment operator would not be implicitly defined as
8185 // deleted,
8186
8187 // [DR1402]:
8188 // - X has no direct or indirect virtual base class with a non-trivial
8189 // move assignment operator, and
8190 // - each of X's non-static data members and direct or virtual base classes
8191 // has a type that either has a move assignment operator or is trivially
8192 // copyable.
8193 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8194 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8195 ClassDecl->setFailedImplicitMoveAssignment();
8196 return 0;
8197 }
8198
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008199 // Note: The following rules are largely analoguous to the move
8200 // constructor rules.
8201
8202 ImplicitExceptionSpecification Spec(
8203 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8204
8205 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8206 QualType RetType = Context.getLValueReferenceType(ArgType);
8207 ArgType = Context.getRValueReferenceType(ArgType);
8208
8209 // An implicitly-declared move assignment operator is an inline public
8210 // member of its class.
8211 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8212 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8213 SourceLocation ClassLoc = ClassDecl->getLocation();
8214 DeclarationNameInfo NameInfo(Name, ClassLoc);
8215 CXXMethodDecl *MoveAssignment
8216 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8217 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8218 /*TInfo=*/0, /*isStatic=*/false,
8219 /*StorageClassAsWritten=*/SC_None,
8220 /*isInline=*/true,
8221 /*isConstexpr=*/false,
8222 SourceLocation());
8223 MoveAssignment->setAccess(AS_public);
8224 MoveAssignment->setDefaulted();
8225 MoveAssignment->setImplicit();
8226 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8227
8228 // Add the parameter to the operator.
8229 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8230 ClassLoc, ClassLoc, /*Id=*/0,
8231 ArgType, /*TInfo=*/0,
8232 SC_None,
8233 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008234 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008235
8236 // Note that we have added this copy-assignment operator.
8237 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8238
8239 // C++0x [class.copy]p9:
8240 // If the definition of a class X does not explicitly declare a move
8241 // assignment operator, one will be implicitly declared as defaulted if and
8242 // only if:
8243 // [...]
8244 // - the move assignment operator would not be implicitly defined as
8245 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008246 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008247 // Cache this result so that we don't try to generate this over and over
8248 // on every lookup, leaking memory and wasting time.
8249 ClassDecl->setFailedImplicitMoveAssignment();
8250 return 0;
8251 }
8252
8253 if (Scope *S = getScopeForContext(ClassDecl))
8254 PushOnScopeChains(MoveAssignment, S, false);
8255 ClassDecl->addDecl(MoveAssignment);
8256
8257 AddOverriddenMethods(ClassDecl, MoveAssignment);
8258 return MoveAssignment;
8259}
8260
8261void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8262 CXXMethodDecl *MoveAssignOperator) {
8263 assert((MoveAssignOperator->isDefaulted() &&
8264 MoveAssignOperator->isOverloadedOperator() &&
8265 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008266 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8267 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008268 "DefineImplicitMoveAssignment called for wrong function");
8269
8270 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8271
8272 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8273 MoveAssignOperator->setInvalidDecl();
8274 return;
8275 }
8276
8277 MoveAssignOperator->setUsed();
8278
8279 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8280 DiagnosticErrorTrap Trap(Diags);
8281
8282 // C++0x [class.copy]p28:
8283 // The implicitly-defined or move assignment operator for a non-union class
8284 // X performs memberwise move assignment of its subobjects. The direct base
8285 // classes of X are assigned first, in the order of their declaration in the
8286 // base-specifier-list, and then the immediate non-static data members of X
8287 // are assigned, in the order in which they were declared in the class
8288 // definition.
8289
8290 // The statements that form the synthesized function body.
8291 ASTOwningVector<Stmt*> Statements(*this);
8292
8293 // The parameter for the "other" object, which we are move from.
8294 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8295 QualType OtherRefType = Other->getType()->
8296 getAs<RValueReferenceType>()->getPointeeType();
8297 assert(OtherRefType.getQualifiers() == 0 &&
8298 "Bad argument type of defaulted move assignment");
8299
8300 // Our location for everything implicitly-generated.
8301 SourceLocation Loc = MoveAssignOperator->getLocation();
8302
8303 // Construct a reference to the "other" object. We'll be using this
8304 // throughout the generated ASTs.
8305 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8306 assert(OtherRef && "Reference to parameter cannot fail!");
8307 // Cast to rvalue.
8308 OtherRef = CastForMoving(*this, OtherRef);
8309
8310 // Construct the "this" pointer. We'll be using this throughout the generated
8311 // ASTs.
8312 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8313 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008314
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008315 // Assign base classes.
8316 bool Invalid = false;
8317 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8318 E = ClassDecl->bases_end(); Base != E; ++Base) {
8319 // Form the assignment:
8320 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8321 QualType BaseType = Base->getType().getUnqualifiedType();
8322 if (!BaseType->isRecordType()) {
8323 Invalid = true;
8324 continue;
8325 }
8326
8327 CXXCastPath BasePath;
8328 BasePath.push_back(Base);
8329
8330 // Construct the "from" expression, which is an implicit cast to the
8331 // appropriately-qualified base type.
8332 Expr *From = OtherRef;
8333 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008334 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008335
8336 // Dereference "this".
8337 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8338
8339 // Implicitly cast "this" to the appropriately-qualified base type.
8340 To = ImpCastExprToType(To.take(),
8341 Context.getCVRQualifiedType(BaseType,
8342 MoveAssignOperator->getTypeQualifiers()),
8343 CK_UncheckedDerivedToBase,
8344 VK_LValue, &BasePath);
8345
8346 // Build the move.
8347 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8348 To.get(), From,
8349 /*CopyingBaseSubobject=*/true,
8350 /*Copying=*/false);
8351 if (Move.isInvalid()) {
8352 Diag(CurrentLocation, diag::note_member_synthesized_at)
8353 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8354 MoveAssignOperator->setInvalidDecl();
8355 return;
8356 }
8357
8358 // Success! Record the move.
8359 Statements.push_back(Move.takeAs<Expr>());
8360 }
8361
8362 // \brief Reference to the __builtin_memcpy function.
8363 Expr *BuiltinMemCpyRef = 0;
8364 // \brief Reference to the __builtin_objc_memmove_collectable function.
8365 Expr *CollectableMemCpyRef = 0;
8366
8367 // Assign non-static members.
8368 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8369 FieldEnd = ClassDecl->field_end();
8370 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008371 if (Field->isUnnamedBitfield())
8372 continue;
8373
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008374 // Check for members of reference type; we can't move those.
8375 if (Field->getType()->isReferenceType()) {
8376 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8377 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8378 Diag(Field->getLocation(), diag::note_declared_at);
8379 Diag(CurrentLocation, diag::note_member_synthesized_at)
8380 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8381 Invalid = true;
8382 continue;
8383 }
8384
8385 // Check for members of const-qualified, non-class type.
8386 QualType BaseType = Context.getBaseElementType(Field->getType());
8387 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8388 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8389 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8390 Diag(Field->getLocation(), diag::note_declared_at);
8391 Diag(CurrentLocation, diag::note_member_synthesized_at)
8392 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8393 Invalid = true;
8394 continue;
8395 }
8396
8397 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008398 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8399 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008400
8401 QualType FieldType = Field->getType().getNonReferenceType();
8402 if (FieldType->isIncompleteArrayType()) {
8403 assert(ClassDecl->hasFlexibleArrayMember() &&
8404 "Incomplete array type is not valid");
8405 continue;
8406 }
8407
8408 // Build references to the field in the object we're copying from and to.
8409 CXXScopeSpec SS; // Intentionally empty
8410 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8411 LookupMemberName);
8412 MemberLookup.addDecl(*Field);
8413 MemberLookup.resolveKind();
8414 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8415 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008416 SS, SourceLocation(), 0,
8417 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008418 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8419 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008420 SS, SourceLocation(), 0,
8421 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008422 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8423 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8424
8425 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8426 "Member reference with rvalue base must be rvalue except for reference "
8427 "members, which aren't allowed for move assignment.");
8428
8429 // If the field should be copied with __builtin_memcpy rather than via
8430 // explicit assignments, do so. This optimization only applies for arrays
8431 // of scalars and arrays of class type with trivial move-assignment
8432 // operators.
8433 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8434 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8435 // Compute the size of the memory buffer to be copied.
8436 QualType SizeType = Context.getSizeType();
8437 llvm::APInt Size(Context.getTypeSize(SizeType),
8438 Context.getTypeSizeInChars(BaseType).getQuantity());
8439 for (const ConstantArrayType *Array
8440 = Context.getAsConstantArrayType(FieldType);
8441 Array;
8442 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8443 llvm::APInt ArraySize
8444 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8445 Size *= ArraySize;
8446 }
8447
Douglas Gregor45d3d712011-09-01 02:09:07 +00008448 // Take the address of the field references for "from" and "to". We
8449 // directly construct UnaryOperators here because semantic analysis
8450 // does not permit us to take the address of an xvalue.
8451 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8452 Context.getPointerType(From.get()->getType()),
8453 VK_RValue, OK_Ordinary, Loc);
8454 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8455 Context.getPointerType(To.get()->getType()),
8456 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008457
8458 bool NeedsCollectableMemCpy =
8459 (BaseType->isRecordType() &&
8460 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8461
8462 if (NeedsCollectableMemCpy) {
8463 if (!CollectableMemCpyRef) {
8464 // Create a reference to the __builtin_objc_memmove_collectable function.
8465 LookupResult R(*this,
8466 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8467 Loc, LookupOrdinaryName);
8468 LookupName(R, TUScope, true);
8469
8470 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8471 if (!CollectableMemCpy) {
8472 // Something went horribly wrong earlier, and we will have
8473 // complained about it.
8474 Invalid = true;
8475 continue;
8476 }
8477
8478 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8479 CollectableMemCpy->getType(),
8480 VK_LValue, Loc, 0).take();
8481 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8482 }
8483 }
8484 // Create a reference to the __builtin_memcpy builtin function.
8485 else if (!BuiltinMemCpyRef) {
8486 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8487 LookupOrdinaryName);
8488 LookupName(R, TUScope, true);
8489
8490 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8491 if (!BuiltinMemCpy) {
8492 // Something went horribly wrong earlier, and we will have complained
8493 // about it.
8494 Invalid = true;
8495 continue;
8496 }
8497
8498 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8499 BuiltinMemCpy->getType(),
8500 VK_LValue, Loc, 0).take();
8501 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8502 }
8503
8504 ASTOwningVector<Expr*> CallArgs(*this);
8505 CallArgs.push_back(To.takeAs<Expr>());
8506 CallArgs.push_back(From.takeAs<Expr>());
8507 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8508 ExprResult Call = ExprError();
8509 if (NeedsCollectableMemCpy)
8510 Call = ActOnCallExpr(/*Scope=*/0,
8511 CollectableMemCpyRef,
8512 Loc, move_arg(CallArgs),
8513 Loc);
8514 else
8515 Call = ActOnCallExpr(/*Scope=*/0,
8516 BuiltinMemCpyRef,
8517 Loc, move_arg(CallArgs),
8518 Loc);
8519
8520 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8521 Statements.push_back(Call.takeAs<Expr>());
8522 continue;
8523 }
8524
8525 // Build the move of this field.
8526 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8527 To.get(), From.get(),
8528 /*CopyingBaseSubobject=*/false,
8529 /*Copying=*/false);
8530 if (Move.isInvalid()) {
8531 Diag(CurrentLocation, diag::note_member_synthesized_at)
8532 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8533 MoveAssignOperator->setInvalidDecl();
8534 return;
8535 }
8536
8537 // Success! Record the copy.
8538 Statements.push_back(Move.takeAs<Stmt>());
8539 }
8540
8541 if (!Invalid) {
8542 // Add a "return *this;"
8543 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8544
8545 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8546 if (Return.isInvalid())
8547 Invalid = true;
8548 else {
8549 Statements.push_back(Return.takeAs<Stmt>());
8550
8551 if (Trap.hasErrorOccurred()) {
8552 Diag(CurrentLocation, diag::note_member_synthesized_at)
8553 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8554 Invalid = true;
8555 }
8556 }
8557 }
8558
8559 if (Invalid) {
8560 MoveAssignOperator->setInvalidDecl();
8561 return;
8562 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008563
8564 StmtResult Body;
8565 {
8566 CompoundScopeRAII CompoundScope(*this);
8567 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8568 /*isStmtExpr=*/false);
8569 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8570 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008571 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8572
8573 if (ASTMutationListener *L = getASTMutationListener()) {
8574 L->CompletedImplicitDefinition(MoveAssignOperator);
8575 }
8576}
8577
Sean Hunt49634cf2011-05-13 06:10:58 +00008578std::pair<Sema::ImplicitExceptionSpecification, bool>
8579Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008580 if (ClassDecl->isInvalidDecl())
8581 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8582
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008583 // C++ [class.copy]p5:
8584 // The implicitly-declared copy constructor for a class X will
8585 // have the form
8586 //
8587 // X::X(const X&)
8588 //
8589 // if
Sean Huntc530d172011-06-10 04:44:37 +00008590 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008591 bool HasConstCopyConstructor = true;
8592
8593 // -- each direct or virtual base class B of X has a copy
8594 // constructor whose first parameter is of type const B& or
8595 // const volatile B&, and
8596 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8597 BaseEnd = ClassDecl->bases_end();
8598 HasConstCopyConstructor && Base != BaseEnd;
8599 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008600 // Virtual bases are handled below.
8601 if (Base->isVirtual())
8602 continue;
8603
Douglas Gregor22584312010-07-02 23:41:54 +00008604 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008605 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008606 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8607 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008608 }
8609
8610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8611 BaseEnd = ClassDecl->vbases_end();
8612 HasConstCopyConstructor && Base != BaseEnd;
8613 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008614 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008615 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008616 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8617 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008618 }
8619
8620 // -- for all the nonstatic data members of X that are of a
8621 // class type M (or array thereof), each such class type
8622 // has a copy constructor whose first parameter is of type
8623 // const M& or const volatile M&.
8624 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8625 FieldEnd = ClassDecl->field_end();
8626 HasConstCopyConstructor && Field != FieldEnd;
8627 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008628 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008629 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008630 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8631 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008632 }
8633 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008634 // Otherwise, the implicitly declared copy constructor will have
8635 // the form
8636 //
8637 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008638
Douglas Gregor0d405db2010-07-01 20:59:04 +00008639 // C++ [except.spec]p14:
8640 // An implicitly declared special member function (Clause 12) shall have an
8641 // exception-specification. [...]
8642 ImplicitExceptionSpecification ExceptSpec(Context);
8643 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8644 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8645 BaseEnd = ClassDecl->bases_end();
8646 Base != BaseEnd;
8647 ++Base) {
8648 // Virtual bases are handled below.
8649 if (Base->isVirtual())
8650 continue;
8651
Douglas Gregor22584312010-07-02 23:41:54 +00008652 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008653 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008654 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008655 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008656 ExceptSpec.CalledDecl(CopyConstructor);
8657 }
8658 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8659 BaseEnd = ClassDecl->vbases_end();
8660 Base != BaseEnd;
8661 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008662 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008663 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008664 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008665 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008666 ExceptSpec.CalledDecl(CopyConstructor);
8667 }
8668 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8669 FieldEnd = ClassDecl->field_end();
8670 Field != FieldEnd;
8671 ++Field) {
8672 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008673 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8674 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008675 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008676 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008677 }
8678 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008679
Sean Hunt49634cf2011-05-13 06:10:58 +00008680 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8681}
8682
8683CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8684 CXXRecordDecl *ClassDecl) {
8685 // C++ [class.copy]p4:
8686 // If the class definition does not explicitly declare a copy
8687 // constructor, one is declared implicitly.
8688
8689 ImplicitExceptionSpecification Spec(Context);
8690 bool Const;
8691 llvm::tie(Spec, Const) =
8692 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8693
8694 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8695 QualType ArgType = ClassType;
8696 if (Const)
8697 ArgType = ArgType.withConst();
8698 ArgType = Context.getLValueReferenceType(ArgType);
8699
8700 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8701
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008702 DeclarationName Name
8703 = Context.DeclarationNames.getCXXConstructorName(
8704 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008705 SourceLocation ClassLoc = ClassDecl->getLocation();
8706 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008707
8708 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008709 // member of its class.
8710 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8711 Context, ClassDecl, ClassLoc, NameInfo,
8712 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8713 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8714 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008715 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008716 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008717 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008718 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008719
Douglas Gregor22584312010-07-02 23:41:54 +00008720 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008721 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8722
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008723 // Add the parameter to the constructor.
8724 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008725 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008726 /*IdentifierInfo=*/0,
8727 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008728 SC_None,
8729 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008730 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008731
Douglas Gregor23c94db2010-07-02 17:43:08 +00008732 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008733 PushOnScopeChains(CopyConstructor, S, false);
8734 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008735
Nico Weberafcc96a2012-01-23 03:19:29 +00008736 // C++11 [class.copy]p8:
8737 // ... If the class definition does not explicitly declare a copy
8738 // constructor, there is no user-declared move constructor, and there is no
8739 // user-declared move assignment operator, a copy constructor is implicitly
8740 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008741 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008742 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008743
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008744 return CopyConstructor;
8745}
8746
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008747void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008748 CXXConstructorDecl *CopyConstructor) {
8749 assert((CopyConstructor->isDefaulted() &&
8750 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008751 !CopyConstructor->doesThisDeclarationHaveABody() &&
8752 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008753 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008754
Anders Carlsson63010a72010-04-23 16:24:12 +00008755 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008756 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008757
Douglas Gregor39957dc2010-05-01 15:04:51 +00008758 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008759 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008760
Sean Huntcbb67482011-01-08 20:30:50 +00008761 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008762 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008763 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008764 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008765 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008766 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008767 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008768 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8769 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008770 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008771 /*isStmtExpr=*/false)
8772 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008773 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008774 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008775
8776 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008777 if (ASTMutationListener *L = getASTMutationListener()) {
8778 L->CompletedImplicitDefinition(CopyConstructor);
8779 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008780}
8781
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008782Sema::ImplicitExceptionSpecification
8783Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8784 // C++ [except.spec]p14:
8785 // An implicitly declared special member function (Clause 12) shall have an
8786 // exception-specification. [...]
8787 ImplicitExceptionSpecification ExceptSpec(Context);
8788 if (ClassDecl->isInvalidDecl())
8789 return ExceptSpec;
8790
8791 // Direct base-class constructors.
8792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8793 BEnd = ClassDecl->bases_end();
8794 B != BEnd; ++B) {
8795 if (B->isVirtual()) // Handled below.
8796 continue;
8797
8798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8800 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8801 // If this is a deleted function, add it anyway. This might be conformant
8802 // with the standard. This might not. I'm not sure. It might not matter.
8803 if (Constructor)
8804 ExceptSpec.CalledDecl(Constructor);
8805 }
8806 }
8807
8808 // Virtual base-class constructors.
8809 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8810 BEnd = ClassDecl->vbases_end();
8811 B != BEnd; ++B) {
8812 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8813 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8814 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8815 // If this is a deleted function, add it anyway. This might be conformant
8816 // with the standard. This might not. I'm not sure. It might not matter.
8817 if (Constructor)
8818 ExceptSpec.CalledDecl(Constructor);
8819 }
8820 }
8821
8822 // Field constructors.
8823 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8824 FEnd = ClassDecl->field_end();
8825 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008826 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008827 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8828 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8829 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8830 // If this is a deleted function, add it anyway. This might be conformant
8831 // with the standard. This might not. I'm not sure. It might not matter.
8832 // In particular, the problem is that this function never gets called. It
8833 // might just be ill-formed because this function attempts to refer to
8834 // a deleted function here.
8835 if (Constructor)
8836 ExceptSpec.CalledDecl(Constructor);
8837 }
8838 }
8839
8840 return ExceptSpec;
8841}
8842
8843CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8844 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008845 // C++11 [class.copy]p9:
8846 // If the definition of a class X does not explicitly declare a move
8847 // constructor, one will be implicitly declared as defaulted if and only if:
8848 //
8849 // - [first 4 bullets]
8850 assert(ClassDecl->needsImplicitMoveConstructor());
8851
8852 // [Checked after we build the declaration]
8853 // - the move assignment operator would not be implicitly defined as
8854 // deleted,
8855
8856 // [DR1402]:
8857 // - each of X's non-static data members and direct or virtual base classes
8858 // has a type that either has a move constructor or is trivially copyable.
8859 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8860 ClassDecl->setFailedImplicitMoveConstructor();
8861 return 0;
8862 }
8863
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008864 ImplicitExceptionSpecification Spec(
8865 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8866
8867 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8868 QualType ArgType = Context.getRValueReferenceType(ClassType);
8869
8870 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8871
8872 DeclarationName Name
8873 = Context.DeclarationNames.getCXXConstructorName(
8874 Context.getCanonicalType(ClassType));
8875 SourceLocation ClassLoc = ClassDecl->getLocation();
8876 DeclarationNameInfo NameInfo(Name, ClassLoc);
8877
8878 // C++0x [class.copy]p11:
8879 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008880 // member of its class.
8881 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8882 Context, ClassDecl, ClassLoc, NameInfo,
8883 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8884 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8885 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008886 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008887 MoveConstructor->setAccess(AS_public);
8888 MoveConstructor->setDefaulted();
8889 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008890
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008891 // Add the parameter to the constructor.
8892 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8893 ClassLoc, ClassLoc,
8894 /*IdentifierInfo=*/0,
8895 ArgType, /*TInfo=*/0,
8896 SC_None,
8897 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008898 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008899
8900 // C++0x [class.copy]p9:
8901 // If the definition of a class X does not explicitly declare a move
8902 // constructor, one will be implicitly declared as defaulted if and only if:
8903 // [...]
8904 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008905 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008906 // Cache this result so that we don't try to generate this over and over
8907 // on every lookup, leaking memory and wasting time.
8908 ClassDecl->setFailedImplicitMoveConstructor();
8909 return 0;
8910 }
8911
8912 // Note that we have declared this constructor.
8913 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8914
8915 if (Scope *S = getScopeForContext(ClassDecl))
8916 PushOnScopeChains(MoveConstructor, S, false);
8917 ClassDecl->addDecl(MoveConstructor);
8918
8919 return MoveConstructor;
8920}
8921
8922void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8923 CXXConstructorDecl *MoveConstructor) {
8924 assert((MoveConstructor->isDefaulted() &&
8925 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008926 !MoveConstructor->doesThisDeclarationHaveABody() &&
8927 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008928 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8929
8930 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8931 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8932
8933 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8934 DiagnosticErrorTrap Trap(Diags);
8935
8936 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8937 Trap.hasErrorOccurred()) {
8938 Diag(CurrentLocation, diag::note_member_synthesized_at)
8939 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8940 MoveConstructor->setInvalidDecl();
8941 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008942 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008943 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8944 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008945 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008946 /*isStmtExpr=*/false)
8947 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008948 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008949 }
8950
8951 MoveConstructor->setUsed();
8952
8953 if (ASTMutationListener *L = getASTMutationListener()) {
8954 L->CompletedImplicitDefinition(MoveConstructor);
8955 }
8956}
8957
Douglas Gregore4e68d42012-02-15 19:33:52 +00008958bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8959 return FD->isDeleted() &&
8960 (FD->isDefaulted() || FD->isImplicit()) &&
8961 isa<CXXMethodDecl>(FD);
8962}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008963
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008964/// \brief Mark the call operator of the given lambda closure type as "used".
8965static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8966 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008967 = cast<CXXMethodDecl>(
8968 *Lambda->lookup(
8969 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008970 CallOperator->setReferenced();
8971 CallOperator->setUsed();
8972}
8973
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008974void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8975 SourceLocation CurrentLocation,
8976 CXXConversionDecl *Conv)
8977{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008978 CXXRecordDecl *Lambda = Conv->getParent();
8979
8980 // Make sure that the lambda call operator is marked used.
8981 markLambdaCallOperatorUsed(*this, Lambda);
8982
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008983 Conv->setUsed();
8984
8985 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8986 DiagnosticErrorTrap Trap(Diags);
8987
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008988 // Return the address of the __invoke function.
8989 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8990 CXXMethodDecl *Invoke
8991 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8992 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8993 VK_LValue, Conv->getLocation()).take();
8994 assert(FunctionRef && "Can't refer to __invoke function?");
8995 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8996 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8997 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008998 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008999
9000 // Fill in the __invoke function with a dummy implementation. IR generation
9001 // will fill in the actual details.
9002 Invoke->setUsed();
9003 Invoke->setReferenced();
9004 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
9005 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009006
9007 if (ASTMutationListener *L = getASTMutationListener()) {
9008 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009009 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009010 }
9011}
9012
9013void Sema::DefineImplicitLambdaToBlockPointerConversion(
9014 SourceLocation CurrentLocation,
9015 CXXConversionDecl *Conv)
9016{
9017 Conv->setUsed();
9018
9019 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9020 DiagnosticErrorTrap Trap(Diags);
9021
Douglas Gregorac1303e2012-02-22 05:02:47 +00009022 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009023 Expr *This = ActOnCXXThis(CurrentLocation).take();
9024 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009025
Eli Friedman23f02672012-03-01 04:01:32 +00009026 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9027 Conv->getLocation(),
9028 Conv, DerefThis);
9029
9030 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9031 // behavior. Note that only the general conversion function does this
9032 // (since it's unusable otherwise); in the case where we inline the
9033 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009034 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009035 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9036 CK_CopyAndAutoreleaseBlockObject,
9037 BuildBlock.get(), 0, VK_RValue);
9038
9039 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009040 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009041 Conv->setInvalidDecl();
9042 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009043 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009044
Douglas Gregorac1303e2012-02-22 05:02:47 +00009045 // Create the return statement that returns the block from the conversion
9046 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009047 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009048 if (Return.isInvalid()) {
9049 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9050 Conv->setInvalidDecl();
9051 return;
9052 }
9053
9054 // Set the body of the conversion function.
9055 Stmt *ReturnS = Return.take();
9056 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9057 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009058 Conv->getLocation()));
9059
Douglas Gregorac1303e2012-02-22 05:02:47 +00009060 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009061 if (ASTMutationListener *L = getASTMutationListener()) {
9062 L->CompletedImplicitDefinition(Conv);
9063 }
9064}
9065
Douglas Gregorf52757d2012-03-10 06:53:13 +00009066/// \brief Determine whether the given list arguments contains exactly one
9067/// "real" (non-default) argument.
9068static bool hasOneRealArgument(MultiExprArg Args) {
9069 switch (Args.size()) {
9070 case 0:
9071 return false;
9072
9073 default:
9074 if (!Args.get()[1]->isDefaultArgument())
9075 return false;
9076
9077 // fall through
9078 case 1:
9079 return !Args.get()[0]->isDefaultArgument();
9080 }
9081
9082 return false;
9083}
9084
John McCall60d7b3a2010-08-24 06:29:42 +00009085ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009086Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009087 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009088 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009089 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009090 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009091 unsigned ConstructKind,
9092 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009093 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009094
Douglas Gregor2f599792010-04-02 18:24:57 +00009095 // C++0x [class.copy]p34:
9096 // When certain criteria are met, an implementation is allowed to
9097 // omit the copy/move construction of a class object, even if the
9098 // copy/move constructor and/or destructor for the object have
9099 // side effects. [...]
9100 // - when a temporary class object that has not been bound to a
9101 // reference (12.2) would be copied/moved to a class object
9102 // with the same cv-unqualified type, the copy/move operation
9103 // can be omitted by constructing the temporary object
9104 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009105 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009106 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009107 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009108 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009109 }
Mike Stump1eb44332009-09-09 15:08:12 +00009110
9111 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009112 Elidable, move(ExprArgs), HadMultipleCandidates,
9113 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009114}
9115
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009116/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9117/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009118ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009119Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9120 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009121 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009122 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009123 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009124 unsigned ConstructKind,
9125 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009126 unsigned NumExprs = ExprArgs.size();
9127 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009128
Nick Lewycky909a70d2011-03-25 01:44:32 +00009129 for (specific_attr_iterator<NonNullAttr>
9130 i = Constructor->specific_attr_begin<NonNullAttr>(),
9131 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9132 const NonNullAttr *NonNull = *i;
9133 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9134 }
9135
Eli Friedman5f2987c2012-02-02 03:46:19 +00009136 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009137 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009138 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009139 HadMultipleCandidates, /*FIXME*/false,
9140 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009141 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9142 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009143}
9144
Mike Stump1eb44332009-09-09 15:08:12 +00009145bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009146 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009147 MultiExprArg Exprs,
9148 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009149 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009150 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009151 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009152 move(Exprs), HadMultipleCandidates, false,
9153 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009154 if (TempResult.isInvalid())
9155 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009156
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009157 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009158 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009159 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009160 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009161 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009162
Anders Carlssonfe2de492009-08-25 05:18:00 +00009163 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009164}
9165
John McCall68c6c9a2010-02-02 09:10:11 +00009166void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009167 if (VD->isInvalidDecl()) return;
9168
John McCall68c6c9a2010-02-02 09:10:11 +00009169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009170 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009171 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009172 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009173
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009174 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009175 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009176 CheckDestructorAccess(VD->getLocation(), Destructor,
9177 PDiag(diag::err_access_dtor_var)
9178 << VD->getDeclName()
9179 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009180 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009181
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009182 if (!VD->hasGlobalStorage()) return;
9183
9184 // Emit warning for non-trivial dtor in global scope (a real global,
9185 // class-static, function-static).
9186 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9187
9188 // TODO: this should be re-enabled for static locals by !CXAAtExit
9189 if (!VD->isStaticLocal())
9190 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009191}
9192
Douglas Gregor39da0b82009-09-09 23:08:42 +00009193/// \brief Given a constructor and the set of arguments provided for the
9194/// constructor, convert the arguments and add any required default arguments
9195/// to form a proper call to this constructor.
9196///
9197/// \returns true if an error occurred, false otherwise.
9198bool
9199Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9200 MultiExprArg ArgsPtr,
9201 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009202 ASTOwningVector<Expr*> &ConvertedArgs,
9203 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009204 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9205 unsigned NumArgs = ArgsPtr.size();
9206 Expr **Args = (Expr **)ArgsPtr.get();
9207
9208 const FunctionProtoType *Proto
9209 = Constructor->getType()->getAs<FunctionProtoType>();
9210 assert(Proto && "Constructor without a prototype?");
9211 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009212
9213 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009214 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009215 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009216 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009217 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009218
9219 VariadicCallType CallType =
9220 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009221 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009222 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9223 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009224 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009225 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009226
9227 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9228
9229 // FIXME: Missing call to CheckFunctionCall or equivalent
9230
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009231 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009232}
9233
Anders Carlsson20d45d22009-12-12 00:32:00 +00009234static inline bool
9235CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9236 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009237 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009238 if (isa<NamespaceDecl>(DC)) {
9239 return SemaRef.Diag(FnDecl->getLocation(),
9240 diag::err_operator_new_delete_declared_in_namespace)
9241 << FnDecl->getDeclName();
9242 }
9243
9244 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009245 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009246 return SemaRef.Diag(FnDecl->getLocation(),
9247 diag::err_operator_new_delete_declared_static)
9248 << FnDecl->getDeclName();
9249 }
9250
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009251 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009252}
9253
Anders Carlsson156c78e2009-12-13 17:53:43 +00009254static inline bool
9255CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9256 CanQualType ExpectedResultType,
9257 CanQualType ExpectedFirstParamType,
9258 unsigned DependentParamTypeDiag,
9259 unsigned InvalidParamTypeDiag) {
9260 QualType ResultType =
9261 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9262
9263 // Check that the result type is not dependent.
9264 if (ResultType->isDependentType())
9265 return SemaRef.Diag(FnDecl->getLocation(),
9266 diag::err_operator_new_delete_dependent_result_type)
9267 << FnDecl->getDeclName() << ExpectedResultType;
9268
9269 // Check that the result type is what we expect.
9270 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9271 return SemaRef.Diag(FnDecl->getLocation(),
9272 diag::err_operator_new_delete_invalid_result_type)
9273 << FnDecl->getDeclName() << ExpectedResultType;
9274
9275 // A function template must have at least 2 parameters.
9276 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9277 return SemaRef.Diag(FnDecl->getLocation(),
9278 diag::err_operator_new_delete_template_too_few_parameters)
9279 << FnDecl->getDeclName();
9280
9281 // The function decl must have at least 1 parameter.
9282 if (FnDecl->getNumParams() == 0)
9283 return SemaRef.Diag(FnDecl->getLocation(),
9284 diag::err_operator_new_delete_too_few_parameters)
9285 << FnDecl->getDeclName();
9286
9287 // Check the the first parameter type is not dependent.
9288 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9289 if (FirstParamType->isDependentType())
9290 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9291 << FnDecl->getDeclName() << ExpectedFirstParamType;
9292
9293 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009294 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009295 ExpectedFirstParamType)
9296 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9297 << FnDecl->getDeclName() << ExpectedFirstParamType;
9298
9299 return false;
9300}
9301
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009302static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009303CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009304 // C++ [basic.stc.dynamic.allocation]p1:
9305 // A program is ill-formed if an allocation function is declared in a
9306 // namespace scope other than global scope or declared static in global
9307 // scope.
9308 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9309 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009310
9311 CanQualType SizeTy =
9312 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9313
9314 // C++ [basic.stc.dynamic.allocation]p1:
9315 // The return type shall be void*. The first parameter shall have type
9316 // std::size_t.
9317 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9318 SizeTy,
9319 diag::err_operator_new_dependent_param_type,
9320 diag::err_operator_new_param_type))
9321 return true;
9322
9323 // C++ [basic.stc.dynamic.allocation]p1:
9324 // The first parameter shall not have an associated default argument.
9325 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009326 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009327 diag::err_operator_new_default_arg)
9328 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9329
9330 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009331}
9332
9333static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009334CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9335 // C++ [basic.stc.dynamic.deallocation]p1:
9336 // A program is ill-formed if deallocation functions are declared in a
9337 // namespace scope other than global scope or declared static in global
9338 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009339 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9340 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009341
9342 // C++ [basic.stc.dynamic.deallocation]p2:
9343 // Each deallocation function shall return void and its first parameter
9344 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009345 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9346 SemaRef.Context.VoidPtrTy,
9347 diag::err_operator_delete_dependent_param_type,
9348 diag::err_operator_delete_param_type))
9349 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009350
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009351 return false;
9352}
9353
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009354/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9355/// of this overloaded operator is well-formed. If so, returns false;
9356/// otherwise, emits appropriate diagnostics and returns true.
9357bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009358 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009359 "Expected an overloaded operator declaration");
9360
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009361 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9362
Mike Stump1eb44332009-09-09 15:08:12 +00009363 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009364 // The allocation and deallocation functions, operator new,
9365 // operator new[], operator delete and operator delete[], are
9366 // described completely in 3.7.3. The attributes and restrictions
9367 // found in the rest of this subclause do not apply to them unless
9368 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009369 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009370 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009371
Anders Carlssona3ccda52009-12-12 00:26:23 +00009372 if (Op == OO_New || Op == OO_Array_New)
9373 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009374
9375 // C++ [over.oper]p6:
9376 // An operator function shall either be a non-static member
9377 // function or be a non-member function and have at least one
9378 // parameter whose type is a class, a reference to a class, an
9379 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009380 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9381 if (MethodDecl->isStatic())
9382 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009383 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009384 } else {
9385 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009386 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9387 ParamEnd = FnDecl->param_end();
9388 Param != ParamEnd; ++Param) {
9389 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009390 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9391 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009392 ClassOrEnumParam = true;
9393 break;
9394 }
9395 }
9396
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009397 if (!ClassOrEnumParam)
9398 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009399 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009400 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009401 }
9402
9403 // C++ [over.oper]p8:
9404 // An operator function cannot have default arguments (8.3.6),
9405 // except where explicitly stated below.
9406 //
Mike Stump1eb44332009-09-09 15:08:12 +00009407 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009408 // (C++ [over.call]p1).
9409 if (Op != OO_Call) {
9410 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9411 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009412 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009413 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009414 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009415 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009416 }
9417 }
9418
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009419 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9420 { false, false, false }
9421#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9422 , { Unary, Binary, MemberOnly }
9423#include "clang/Basic/OperatorKinds.def"
9424 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009425
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009426 bool CanBeUnaryOperator = OperatorUses[Op][0];
9427 bool CanBeBinaryOperator = OperatorUses[Op][1];
9428 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009429
9430 // C++ [over.oper]p8:
9431 // [...] Operator functions cannot have more or fewer parameters
9432 // than the number required for the corresponding operator, as
9433 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009434 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009435 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009436 if (Op != OO_Call &&
9437 ((NumParams == 1 && !CanBeUnaryOperator) ||
9438 (NumParams == 2 && !CanBeBinaryOperator) ||
9439 (NumParams < 1) || (NumParams > 2))) {
9440 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009441 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009442 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009443 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009444 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009445 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009446 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009447 assert(CanBeBinaryOperator &&
9448 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009449 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009450 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009451
Chris Lattner416e46f2008-11-21 07:57:12 +00009452 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009453 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009454 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009455
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009456 // Overloaded operators other than operator() cannot be variadic.
9457 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009458 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009459 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009460 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009461 }
9462
9463 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009464 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9465 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009466 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009467 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009468 }
9469
9470 // C++ [over.inc]p1:
9471 // The user-defined function called operator++ implements the
9472 // prefix and postfix ++ operator. If this function is a member
9473 // function with no parameters, or a non-member function with one
9474 // parameter of class or enumeration type, it defines the prefix
9475 // increment operator ++ for objects of that type. If the function
9476 // is a member function with one parameter (which shall be of type
9477 // int) or a non-member function with two parameters (the second
9478 // of which shall be of type int), it defines the postfix
9479 // increment operator ++ for objects of that type.
9480 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9481 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9482 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009483 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009484 ParamIsInt = BT->getKind() == BuiltinType::Int;
9485
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009486 if (!ParamIsInt)
9487 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009488 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009489 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009490 }
9491
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009492 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009493}
Chris Lattner5a003a42008-12-17 07:09:26 +00009494
Sean Hunta6c058d2010-01-13 09:01:02 +00009495/// CheckLiteralOperatorDeclaration - Check whether the declaration
9496/// of this literal operator function is well-formed. If so, returns
9497/// false; otherwise, emits appropriate diagnostics and returns true.
9498bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009499 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009500 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9501 << FnDecl->getDeclName();
9502 return true;
9503 }
9504
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009505 if (FnDecl->isExternC()) {
9506 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9507 return true;
9508 }
9509
Sean Hunta6c058d2010-01-13 09:01:02 +00009510 bool Valid = false;
9511
Richard Smith36f5cfe2012-03-09 08:00:36 +00009512 // This might be the definition of a literal operator template.
9513 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9514 // This might be a specialization of a literal operator template.
9515 if (!TpDecl)
9516 TpDecl = FnDecl->getPrimaryTemplate();
9517
Sean Hunt216c2782010-04-07 23:11:06 +00009518 // template <char...> type operator "" name() is the only valid template
9519 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009520 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009521 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009522 // Must have only one template parameter
9523 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9524 if (Params->size() == 1) {
9525 NonTypeTemplateParmDecl *PmDecl =
9526 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009527
Sean Hunt216c2782010-04-07 23:11:06 +00009528 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009529 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9530 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9531 Valid = true;
9532 }
9533 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009534 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009535 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009536 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9537
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009538 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009539
Sean Hunt30019c02010-04-07 22:57:35 +00009540 // unsigned long long int, long double, and any character type are allowed
9541 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009542 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9543 Context.hasSameType(T, Context.LongDoubleTy) ||
9544 Context.hasSameType(T, Context.CharTy) ||
9545 Context.hasSameType(T, Context.WCharTy) ||
9546 Context.hasSameType(T, Context.Char16Ty) ||
9547 Context.hasSameType(T, Context.Char32Ty)) {
9548 if (++Param == FnDecl->param_end())
9549 Valid = true;
9550 goto FinishedParams;
9551 }
9552
Sean Hunt30019c02010-04-07 22:57:35 +00009553 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009554 const PointerType *PT = T->getAs<PointerType>();
9555 if (!PT)
9556 goto FinishedParams;
9557 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009558 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009559 goto FinishedParams;
9560 T = T.getUnqualifiedType();
9561
9562 // Move on to the second parameter;
9563 ++Param;
9564
9565 // If there is no second parameter, the first must be a const char *
9566 if (Param == FnDecl->param_end()) {
9567 if (Context.hasSameType(T, Context.CharTy))
9568 Valid = true;
9569 goto FinishedParams;
9570 }
9571
9572 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9573 // are allowed as the first parameter to a two-parameter function
9574 if (!(Context.hasSameType(T, Context.CharTy) ||
9575 Context.hasSameType(T, Context.WCharTy) ||
9576 Context.hasSameType(T, Context.Char16Ty) ||
9577 Context.hasSameType(T, Context.Char32Ty)))
9578 goto FinishedParams;
9579
9580 // The second and final parameter must be an std::size_t
9581 T = (*Param)->getType().getUnqualifiedType();
9582 if (Context.hasSameType(T, Context.getSizeType()) &&
9583 ++Param == FnDecl->param_end())
9584 Valid = true;
9585 }
9586
9587 // FIXME: This diagnostic is absolutely terrible.
9588FinishedParams:
9589 if (!Valid) {
9590 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9591 << FnDecl->getDeclName();
9592 return true;
9593 }
9594
Richard Smitha9e88b22012-03-09 08:16:22 +00009595 // A parameter-declaration-clause containing a default argument is not
9596 // equivalent to any of the permitted forms.
9597 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9598 ParamEnd = FnDecl->param_end();
9599 Param != ParamEnd; ++Param) {
9600 if ((*Param)->hasDefaultArg()) {
9601 Diag((*Param)->getDefaultArgRange().getBegin(),
9602 diag::err_literal_operator_default_argument)
9603 << (*Param)->getDefaultArgRange();
9604 break;
9605 }
9606 }
9607
Richard Smith2fb4ae32012-03-08 02:39:21 +00009608 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009609 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9610 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009611 // C++11 [usrlit.suffix]p1:
9612 // Literal suffix identifiers that do not start with an underscore
9613 // are reserved for future standardization.
9614 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009615 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009616
Sean Hunta6c058d2010-01-13 09:01:02 +00009617 return false;
9618}
9619
Douglas Gregor074149e2009-01-05 19:45:36 +00009620/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9621/// linkage specification, including the language and (if present)
9622/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9623/// the location of the language string literal, which is provided
9624/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9625/// the '{' brace. Otherwise, this linkage specification does not
9626/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009627Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9628 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009629 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009630 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009631 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009632 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009633 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009634 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009635 Language = LinkageSpecDecl::lang_cxx;
9636 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009637 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009638 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009639 }
Mike Stump1eb44332009-09-09 15:08:12 +00009640
Chris Lattnercc98eac2008-12-17 07:13:27 +00009641 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009642
Douglas Gregor074149e2009-01-05 19:45:36 +00009643 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009644 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009645 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009646 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009647 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009648}
9649
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009650/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009651/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9652/// valid, it's the position of the closing '}' brace in a linkage
9653/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009654Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009655 Decl *LinkageSpec,
9656 SourceLocation RBraceLoc) {
9657 if (LinkageSpec) {
9658 if (RBraceLoc.isValid()) {
9659 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9660 LSDecl->setRBraceLoc(RBraceLoc);
9661 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009662 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009663 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009664 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009665}
9666
Douglas Gregord308e622009-05-18 20:51:54 +00009667/// \brief Perform semantic analysis for the variable declaration that
9668/// occurs within a C++ catch clause, returning the newly-created
9669/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009670VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009671 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009672 SourceLocation StartLoc,
9673 SourceLocation Loc,
9674 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009675 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009676 QualType ExDeclType = TInfo->getType();
9677
Sebastian Redl4b07b292008-12-22 19:15:10 +00009678 // Arrays and functions decay.
9679 if (ExDeclType->isArrayType())
9680 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9681 else if (ExDeclType->isFunctionType())
9682 ExDeclType = Context.getPointerType(ExDeclType);
9683
9684 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9685 // The exception-declaration shall not denote a pointer or reference to an
9686 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009687 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009688 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009689 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009690 Invalid = true;
9691 }
Douglas Gregord308e622009-05-18 20:51:54 +00009692
Sebastian Redl4b07b292008-12-22 19:15:10 +00009693 QualType BaseType = ExDeclType;
9694 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009695 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009696 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009697 BaseType = Ptr->getPointeeType();
9698 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009699 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009700 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009701 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009702 BaseType = Ref->getPointeeType();
9703 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009704 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009705 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009706 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009707 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009708 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009709
Mike Stump1eb44332009-09-09 15:08:12 +00009710 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009711 RequireNonAbstractType(Loc, ExDeclType,
9712 diag::err_abstract_type_in_decl,
9713 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009714 Invalid = true;
9715
John McCall5a180392010-07-24 00:37:23 +00009716 // Only the non-fragile NeXT runtime currently supports C++ catches
9717 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009718 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009719 QualType T = ExDeclType;
9720 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9721 T = RT->getPointeeType();
9722
9723 if (T->isObjCObjectType()) {
9724 Diag(Loc, diag::err_objc_object_catch);
9725 Invalid = true;
9726 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009727 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009728 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009729 }
9730 }
9731
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009732 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9733 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009734 ExDecl->setExceptionVariable(true);
9735
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009736 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009738 Invalid = true;
9739
Douglas Gregorc41b8782011-07-06 18:14:43 +00009740 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009741 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009742 // C++ [except.handle]p16:
9743 // The object declared in an exception-declaration or, if the
9744 // exception-declaration does not specify a name, a temporary (12.2) is
9745 // copy-initialized (8.5) from the exception object. [...]
9746 // The object is destroyed when the handler exits, after the destruction
9747 // of any automatic objects initialized within the handler.
9748 //
9749 // We just pretend to initialize the object with itself, then make sure
9750 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009751 QualType initType = ExDeclType;
9752
9753 InitializedEntity entity =
9754 InitializedEntity::InitializeVariable(ExDecl);
9755 InitializationKind initKind =
9756 InitializationKind::CreateCopy(Loc, SourceLocation());
9757
9758 Expr *opaqueValue =
9759 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9760 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9761 ExprResult result = sequence.Perform(*this, entity, initKind,
9762 MultiExprArg(&opaqueValue, 1));
9763 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009764 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009765 else {
9766 // If the constructor used was non-trivial, set this as the
9767 // "initializer".
9768 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9769 if (!construct->getConstructor()->isTrivial()) {
9770 Expr *init = MaybeCreateExprWithCleanups(construct);
9771 ExDecl->setInit(init);
9772 }
9773
9774 // And make sure it's destructable.
9775 FinalizeVarWithDestructor(ExDecl, recordType);
9776 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009777 }
9778 }
9779
Douglas Gregord308e622009-05-18 20:51:54 +00009780 if (Invalid)
9781 ExDecl->setInvalidDecl();
9782
9783 return ExDecl;
9784}
9785
9786/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9787/// handler.
John McCalld226f652010-08-21 09:40:31 +00009788Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009789 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009790 bool Invalid = D.isInvalidType();
9791
9792 // Check for unexpanded parameter packs.
9793 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9794 UPPC_ExceptionType)) {
9795 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9796 D.getIdentifierLoc());
9797 Invalid = true;
9798 }
9799
Sebastian Redl4b07b292008-12-22 19:15:10 +00009800 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009801 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009802 LookupOrdinaryName,
9803 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009804 // The scope should be freshly made just for us. There is just no way
9805 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009806 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009807 if (PrevDecl->isTemplateParameter()) {
9808 // Maybe we will complain about the shadowed template parameter.
9809 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009810 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009811 }
9812 }
9813
Chris Lattnereaaebc72009-04-25 08:06:05 +00009814 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009815 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9816 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009817 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009818 }
9819
Douglas Gregor83cb9422010-09-09 17:09:21 +00009820 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009821 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009822 D.getIdentifierLoc(),
9823 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009824 if (Invalid)
9825 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009826
Sebastian Redl4b07b292008-12-22 19:15:10 +00009827 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009828 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009829 PushOnScopeChains(ExDecl, S);
9830 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009831 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009832
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009833 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009834 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009835}
Anders Carlssonfb311762009-03-14 00:25:26 +00009836
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009837Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009838 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009839 Expr *AssertMessageExpr_,
9840 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009841 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009842
Anders Carlssonc3082412009-03-14 00:33:21 +00009843 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009844 // In a static_assert-declaration, the constant-expression shall be a
9845 // constant expression that can be contextually converted to bool.
9846 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9847 if (Converted.isInvalid())
9848 return 0;
9849
Richard Smithdaaefc52011-12-14 23:32:26 +00009850 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009851 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9852 PDiag(diag::err_static_assert_expression_is_not_constant),
9853 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009854 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009855
Richard Smith0cc323c2012-03-05 23:20:05 +00009856 if (!Cond) {
9857 llvm::SmallString<256> MsgBuffer;
9858 llvm::raw_svector_ostream Msg(MsgBuffer);
9859 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009860 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009861 << Msg.str() << AssertExpr->getSourceRange();
9862 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009863 }
Mike Stump1eb44332009-09-09 15:08:12 +00009864
Douglas Gregor399ad972010-12-15 23:55:21 +00009865 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9866 return 0;
9867
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009868 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9869 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009870
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009871 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009872 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009873}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009874
Douglas Gregor1d869352010-04-07 16:53:43 +00009875/// \brief Perform semantic analysis of the given friend type declaration.
9876///
9877/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009878FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9879 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009880 TypeSourceInfo *TSInfo) {
9881 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9882
9883 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009884 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009885
Richard Smith6b130222011-10-18 21:39:00 +00009886 // C++03 [class.friend]p2:
9887 // An elaborated-type-specifier shall be used in a friend declaration
9888 // for a class.*
9889 //
9890 // * The class-key of the elaborated-type-specifier is required.
9891 if (!ActiveTemplateInstantiations.empty()) {
9892 // Do not complain about the form of friend template types during
9893 // template instantiation; we will already have complained when the
9894 // template was declared.
9895 } else if (!T->isElaboratedTypeSpecifier()) {
9896 // If we evaluated the type to a record type, suggest putting
9897 // a tag in front.
9898 if (const RecordType *RT = T->getAs<RecordType>()) {
9899 RecordDecl *RD = RT->getDecl();
9900
9901 std::string InsertionText = std::string(" ") + RD->getKindName();
9902
9903 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009904 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009905 diag::warn_cxx98_compat_unelaborated_friend_type :
9906 diag::ext_unelaborated_friend_type)
9907 << (unsigned) RD->getTagKind()
9908 << T
9909 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9910 InsertionText);
9911 } else {
9912 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009913 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009914 diag::warn_cxx98_compat_nonclass_type_friend :
9915 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009916 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009917 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009918 }
Richard Smith6b130222011-10-18 21:39:00 +00009919 } else if (T->getAs<EnumType>()) {
9920 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009921 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009922 diag::warn_cxx98_compat_enum_friend :
9923 diag::ext_enum_friend)
9924 << T
9925 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009926 }
9927
Douglas Gregor06245bf2010-04-07 17:57:12 +00009928 // C++0x [class.friend]p3:
9929 // If the type specifier in a friend declaration designates a (possibly
9930 // cv-qualified) class type, that class is declared as a friend; otherwise,
9931 // the friend declaration is ignored.
9932
9933 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9934 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009935
Abramo Bagnara0216df82011-10-29 20:52:52 +00009936 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009937}
9938
John McCall9a34edb2010-10-19 01:40:49 +00009939/// Handle a friend tag declaration where the scope specifier was
9940/// templated.
9941Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9942 unsigned TagSpec, SourceLocation TagLoc,
9943 CXXScopeSpec &SS,
9944 IdentifierInfo *Name, SourceLocation NameLoc,
9945 AttributeList *Attr,
9946 MultiTemplateParamsArg TempParamLists) {
9947 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9948
9949 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009950 bool Invalid = false;
9951
9952 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009953 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009954 TempParamLists.get(),
9955 TempParamLists.size(),
9956 /*friend*/ true,
9957 isExplicitSpecialization,
9958 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009959 if (TemplateParams->size() > 0) {
9960 // This is a declaration of a class template.
9961 if (Invalid)
9962 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009963
Eric Christopher4110e132011-07-21 05:34:24 +00009964 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9965 SS, Name, NameLoc, Attr,
9966 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009967 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009968 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009969 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009970 } else {
9971 // The "template<>" header is extraneous.
9972 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9973 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9974 isExplicitSpecialization = true;
9975 }
9976 }
9977
9978 if (Invalid) return 0;
9979
John McCall9a34edb2010-10-19 01:40:49 +00009980 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009981 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009982 if (TempParamLists.get()[I]->size()) {
9983 isAllExplicitSpecializations = false;
9984 break;
9985 }
9986 }
9987
9988 // FIXME: don't ignore attributes.
9989
9990 // If it's explicit specializations all the way down, just forget
9991 // about the template header and build an appropriate non-templated
9992 // friend. TODO: for source fidelity, remember the headers.
9993 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009994 if (SS.isEmpty()) {
9995 bool Owned = false;
9996 bool IsDependent = false;
9997 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9998 Attr, AS_public,
9999 /*ModulePrivateLoc=*/SourceLocation(),
10000 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010001 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010002 /*ScopedEnumUsesClassTag=*/false,
10003 /*UnderlyingType=*/TypeResult());
10004 }
10005
Douglas Gregor2494dd02011-03-01 01:34:45 +000010006 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010007 ElaboratedTypeKeyword Keyword
10008 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010009 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010010 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010011 if (T.isNull())
10012 return 0;
10013
10014 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10015 if (isa<DependentNameType>(T)) {
10016 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010017 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010018 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010019 TL.setNameLoc(NameLoc);
10020 } else {
10021 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010022 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010023 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010024 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10025 }
10026
10027 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10028 TSI, FriendLoc);
10029 Friend->setAccess(AS_public);
10030 CurContext->addDecl(Friend);
10031 return Friend;
10032 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010033
10034 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10035
10036
John McCall9a34edb2010-10-19 01:40:49 +000010037
10038 // Handle the case of a templated-scope friend class. e.g.
10039 // template <class T> class A<T>::B;
10040 // FIXME: we don't support these right now.
10041 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10042 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10043 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10044 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010045 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010046 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010047 TL.setNameLoc(NameLoc);
10048
10049 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10050 TSI, FriendLoc);
10051 Friend->setAccess(AS_public);
10052 Friend->setUnsupportedFriend(true);
10053 CurContext->addDecl(Friend);
10054 return Friend;
10055}
10056
10057
John McCalldd4a3b02009-09-16 22:47:08 +000010058/// Handle a friend type declaration. This works in tandem with
10059/// ActOnTag.
10060///
10061/// Notes on friend class templates:
10062///
10063/// We generally treat friend class declarations as if they were
10064/// declaring a class. So, for example, the elaborated type specifier
10065/// in a friend declaration is required to obey the restrictions of a
10066/// class-head (i.e. no typedefs in the scope chain), template
10067/// parameters are required to match up with simple template-ids, &c.
10068/// However, unlike when declaring a template specialization, it's
10069/// okay to refer to a template specialization without an empty
10070/// template parameter declaration, e.g.
10071/// friend class A<T>::B<unsigned>;
10072/// We permit this as a special case; if there are any template
10073/// parameters present at all, require proper matching, i.e.
10074/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010075Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010076 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010077 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010078
10079 assert(DS.isFriendSpecified());
10080 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10081
John McCalldd4a3b02009-09-16 22:47:08 +000010082 // Try to convert the decl specifier to a type. This works for
10083 // friend templates because ActOnTag never produces a ClassTemplateDecl
10084 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010085 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010086 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10087 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010088 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010089 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010090
Douglas Gregor6ccab972010-12-16 01:14:37 +000010091 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10092 return 0;
10093
John McCalldd4a3b02009-09-16 22:47:08 +000010094 // This is definitely an error in C++98. It's probably meant to
10095 // be forbidden in C++0x, too, but the specification is just
10096 // poorly written.
10097 //
10098 // The problem is with declarations like the following:
10099 // template <T> friend A<T>::foo;
10100 // where deciding whether a class C is a friend or not now hinges
10101 // on whether there exists an instantiation of A that causes
10102 // 'foo' to equal C. There are restrictions on class-heads
10103 // (which we declare (by fiat) elaborated friend declarations to
10104 // be) that makes this tractable.
10105 //
10106 // FIXME: handle "template <> friend class A<T>;", which
10107 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010108 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010109 Diag(Loc, diag::err_tagless_friend_type_template)
10110 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010111 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010112 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010113
John McCall02cace72009-08-28 07:59:38 +000010114 // C++98 [class.friend]p1: A friend of a class is a function
10115 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010116 // This is fixed in DR77, which just barely didn't make the C++03
10117 // deadline. It's also a very silly restriction that seriously
10118 // affects inner classes and which nobody else seems to implement;
10119 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010120 //
10121 // But note that we could warn about it: it's always useless to
10122 // friend one of your own members (it's not, however, worthless to
10123 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010124
John McCalldd4a3b02009-09-16 22:47:08 +000010125 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010126 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010127 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010128 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010129 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010130 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010131 DS.getFriendSpecLoc());
10132 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010133 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010134
10135 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010136 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010137
John McCalldd4a3b02009-09-16 22:47:08 +000010138 D->setAccess(AS_public);
10139 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010140
John McCalld226f652010-08-21 09:40:31 +000010141 return D;
John McCall02cace72009-08-28 07:59:38 +000010142}
10143
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010144Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010145 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010146 const DeclSpec &DS = D.getDeclSpec();
10147
10148 assert(DS.isFriendSpecified());
10149 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10150
10151 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010152 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010153
10154 // C++ [class.friend]p1
10155 // A friend of a class is a function or class....
10156 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010157 // It *doesn't* see through dependent types, which is correct
10158 // according to [temp.arg.type]p3:
10159 // If a declaration acquires a function type through a
10160 // type dependent on a template-parameter and this causes
10161 // a declaration that does not use the syntactic form of a
10162 // function declarator to have a function type, the program
10163 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010164 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010165 Diag(Loc, diag::err_unexpected_friend);
10166
10167 // It might be worthwhile to try to recover by creating an
10168 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010169 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010170 }
10171
10172 // C++ [namespace.memdef]p3
10173 // - If a friend declaration in a non-local class first declares a
10174 // class or function, the friend class or function is a member
10175 // of the innermost enclosing namespace.
10176 // - The name of the friend is not found by simple name lookup
10177 // until a matching declaration is provided in that namespace
10178 // scope (either before or after the class declaration granting
10179 // friendship).
10180 // - If a friend function is called, its name may be found by the
10181 // name lookup that considers functions from namespaces and
10182 // classes associated with the types of the function arguments.
10183 // - When looking for a prior declaration of a class or a function
10184 // declared as a friend, scopes outside the innermost enclosing
10185 // namespace scope are not considered.
10186
John McCall337ec3d2010-10-12 23:13:28 +000010187 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010188 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10189 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010190 assert(Name);
10191
Douglas Gregor6ccab972010-12-16 01:14:37 +000010192 // Check for unexpanded parameter packs.
10193 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10194 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10195 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10196 return 0;
10197
John McCall67d1a672009-08-06 02:15:43 +000010198 // The context we found the declaration in, or in which we should
10199 // create the declaration.
10200 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010201 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010202 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010203 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010204
John McCall337ec3d2010-10-12 23:13:28 +000010205 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010206
John McCall337ec3d2010-10-12 23:13:28 +000010207 // There are four cases here.
10208 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010209 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010210 // there as appropriate.
10211 // Recover from invalid scope qualifiers as if they just weren't there.
10212 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010213 // C++0x [namespace.memdef]p3:
10214 // If the name in a friend declaration is neither qualified nor
10215 // a template-id and the declaration is a function or an
10216 // elaborated-type-specifier, the lookup to determine whether
10217 // the entity has been previously declared shall not consider
10218 // any scopes outside the innermost enclosing namespace.
10219 // C++0x [class.friend]p11:
10220 // If a friend declaration appears in a local class and the name
10221 // specified is an unqualified name, a prior declaration is
10222 // looked up without considering scopes that are outside the
10223 // innermost enclosing non-class scope. For a friend function
10224 // declaration, if there is no prior declaration, the program is
10225 // ill-formed.
10226 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010227 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010228
John McCall29ae6e52010-10-13 05:45:15 +000010229 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010230 DC = CurContext;
10231 while (true) {
10232 // Skip class contexts. If someone can cite chapter and verse
10233 // for this behavior, that would be nice --- it's what GCC and
10234 // EDG do, and it seems like a reasonable intent, but the spec
10235 // really only says that checks for unqualified existing
10236 // declarations should stop at the nearest enclosing namespace,
10237 // not that they should only consider the nearest enclosing
10238 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010239 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010240 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010241
John McCall68263142009-11-18 22:49:29 +000010242 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010243
10244 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010245 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010246 break;
John McCall29ae6e52010-10-13 05:45:15 +000010247
John McCall8a407372010-10-14 22:22:28 +000010248 if (isTemplateId) {
10249 if (isa<TranslationUnitDecl>(DC)) break;
10250 } else {
10251 if (DC->isFileContext()) break;
10252 }
John McCall67d1a672009-08-06 02:15:43 +000010253 DC = DC->getParent();
10254 }
10255
10256 // C++ [class.friend]p1: A friend of a class is a function or
10257 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010258 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010259 // Most C++ 98 compilers do seem to give an error here, so
10260 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010261 if (!Previous.empty() && DC->Equals(CurContext))
10262 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010263 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010264 diag::warn_cxx98_compat_friend_is_member :
10265 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010266
John McCall380aaa42010-10-13 06:22:15 +000010267 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010268
Douglas Gregor883af832011-10-10 01:11:59 +000010269 // C++ [class.friend]p6:
10270 // A function can be defined in a friend declaration of a class if and
10271 // only if the class is a non-local class (9.8), the function name is
10272 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010273 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010274 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10275 }
10276
John McCall337ec3d2010-10-12 23:13:28 +000010277 // - There's a non-dependent scope specifier, in which case we
10278 // compute it and do a previous lookup there for a function
10279 // or function template.
10280 } else if (!SS.getScopeRep()->isDependent()) {
10281 DC = computeDeclContext(SS);
10282 if (!DC) return 0;
10283
10284 if (RequireCompleteDeclContext(SS, DC)) return 0;
10285
10286 LookupQualifiedName(Previous, DC);
10287
10288 // Ignore things found implicitly in the wrong scope.
10289 // TODO: better diagnostics for this case. Suggesting the right
10290 // qualified scope would be nice...
10291 LookupResult::Filter F = Previous.makeFilter();
10292 while (F.hasNext()) {
10293 NamedDecl *D = F.next();
10294 if (!DC->InEnclosingNamespaceSetOf(
10295 D->getDeclContext()->getRedeclContext()))
10296 F.erase();
10297 }
10298 F.done();
10299
10300 if (Previous.empty()) {
10301 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010302 Diag(Loc, diag::err_qualified_friend_not_found)
10303 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010304 return 0;
10305 }
10306
10307 // C++ [class.friend]p1: A friend of a class is a function or
10308 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010309 if (DC->Equals(CurContext))
10310 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010311 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010312 diag::warn_cxx98_compat_friend_is_member :
10313 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010314
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010315 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010316 // C++ [class.friend]p6:
10317 // A function can be defined in a friend declaration of a class if and
10318 // only if the class is a non-local class (9.8), the function name is
10319 // unqualified, and the function has namespace scope.
10320 SemaDiagnosticBuilder DB
10321 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10322
10323 DB << SS.getScopeRep();
10324 if (DC->isFileContext())
10325 DB << FixItHint::CreateRemoval(SS.getRange());
10326 SS.clear();
10327 }
John McCall337ec3d2010-10-12 23:13:28 +000010328
10329 // - There's a scope specifier that does not match any template
10330 // parameter lists, in which case we use some arbitrary context,
10331 // create a method or method template, and wait for instantiation.
10332 // - There's a scope specifier that does match some template
10333 // parameter lists, which we don't handle right now.
10334 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010335 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010336 // C++ [class.friend]p6:
10337 // A function can be defined in a friend declaration of a class if and
10338 // only if the class is a non-local class (9.8), the function name is
10339 // unqualified, and the function has namespace scope.
10340 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10341 << SS.getScopeRep();
10342 }
10343
John McCall337ec3d2010-10-12 23:13:28 +000010344 DC = CurContext;
10345 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010346 }
Douglas Gregor883af832011-10-10 01:11:59 +000010347
John McCall29ae6e52010-10-13 05:45:15 +000010348 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010349 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010350 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10351 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10352 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010353 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010354 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10355 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010356 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010357 }
John McCall67d1a672009-08-06 02:15:43 +000010358 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010359
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010360 // FIXME: This is an egregious hack to cope with cases where the scope stack
10361 // does not contain the declaration context, i.e., in an out-of-line
10362 // definition of a class.
10363 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10364 if (!DCScope) {
10365 FakeDCScope.setEntity(DC);
10366 DCScope = &FakeDCScope;
10367 }
10368
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010369 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010370 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10371 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010372 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010373
Douglas Gregor182ddf02009-09-28 00:08:27 +000010374 assert(ND->getDeclContext() == DC);
10375 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010376
John McCallab88d972009-08-31 22:39:49 +000010377 // Add the function declaration to the appropriate lookup tables,
10378 // adjusting the redeclarations list as necessary. We don't
10379 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010380 //
John McCallab88d972009-08-31 22:39:49 +000010381 // Also update the scope-based lookup if the target context's
10382 // lookup context is in lexical scope.
10383 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010384 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010385 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010386 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010387 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010388 }
John McCall02cace72009-08-28 07:59:38 +000010389
10390 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010391 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010392 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010393 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010394 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010395
John McCall337ec3d2010-10-12 23:13:28 +000010396 if (ND->isInvalidDecl())
10397 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010398 else {
10399 FunctionDecl *FD;
10400 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10401 FD = FTD->getTemplatedDecl();
10402 else
10403 FD = cast<FunctionDecl>(ND);
10404
10405 // Mark templated-scope function declarations as unsupported.
10406 if (FD->getNumTemplateParameterLists())
10407 FrD->setUnsupportedFriend(true);
10408 }
John McCall337ec3d2010-10-12 23:13:28 +000010409
John McCalld226f652010-08-21 09:40:31 +000010410 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010411}
10412
John McCalld226f652010-08-21 09:40:31 +000010413void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10414 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010415
Sebastian Redl50de12f2009-03-24 22:27:57 +000010416 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10417 if (!Fn) {
10418 Diag(DelLoc, diag::err_deleted_non_function);
10419 return;
10420 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010421 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010422 Diag(DelLoc, diag::err_deleted_decl_not_first);
10423 Diag(Prev->getLocation(), diag::note_previous_declaration);
10424 // If the declaration wasn't the first, we delete the function anyway for
10425 // recovery.
10426 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010427 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010428
10429 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10430 if (!MD)
10431 return;
10432
10433 // A deleted special member function is trivial if the corresponding
10434 // implicitly-declared function would have been.
10435 switch (getSpecialMember(MD)) {
10436 case CXXInvalid:
10437 break;
10438 case CXXDefaultConstructor:
10439 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10440 break;
10441 case CXXCopyConstructor:
10442 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10443 break;
10444 case CXXMoveConstructor:
10445 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10446 break;
10447 case CXXCopyAssignment:
10448 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10449 break;
10450 case CXXMoveAssignment:
10451 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10452 break;
10453 case CXXDestructor:
10454 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10455 break;
10456 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010457}
Sebastian Redl13e88542009-04-27 21:33:24 +000010458
Sean Hunte4246a62011-05-12 06:15:49 +000010459void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10461
10462 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010463 if (MD->getParent()->isDependentType()) {
10464 MD->setDefaulted();
10465 MD->setExplicitlyDefaulted();
10466 return;
10467 }
10468
Sean Hunte4246a62011-05-12 06:15:49 +000010469 CXXSpecialMember Member = getSpecialMember(MD);
10470 if (Member == CXXInvalid) {
10471 Diag(DefaultLoc, diag::err_default_special_members);
10472 return;
10473 }
10474
10475 MD->setDefaulted();
10476 MD->setExplicitlyDefaulted();
10477
Sean Huntcd10dec2011-05-23 23:14:04 +000010478 // If this definition appears within the record, do the checking when
10479 // the record is complete.
10480 const FunctionDecl *Primary = MD;
10481 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10482 // Find the uninstantiated declaration that actually had the '= default'
10483 // on it.
10484 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10485
10486 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010487 return;
10488
10489 switch (Member) {
10490 case CXXDefaultConstructor: {
10491 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10492 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010493 if (!CD->isInvalidDecl())
10494 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10495 break;
10496 }
10497
10498 case CXXCopyConstructor: {
10499 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10500 CheckExplicitlyDefaultedCopyConstructor(CD);
10501 if (!CD->isInvalidDecl())
10502 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010503 break;
10504 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010505
Sean Hunt2b188082011-05-14 05:23:28 +000010506 case CXXCopyAssignment: {
10507 CheckExplicitlyDefaultedCopyAssignment(MD);
10508 if (!MD->isInvalidDecl())
10509 DefineImplicitCopyAssignment(DefaultLoc, MD);
10510 break;
10511 }
10512
Sean Huntcb45a0f2011-05-12 22:46:25 +000010513 case CXXDestructor: {
10514 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10515 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010516 if (!DD->isInvalidDecl())
10517 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010518 break;
10519 }
10520
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010521 case CXXMoveConstructor: {
10522 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10523 CheckExplicitlyDefaultedMoveConstructor(CD);
10524 if (!CD->isInvalidDecl())
10525 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010526 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010527 }
Sean Hunt82713172011-05-25 23:16:36 +000010528
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010529 case CXXMoveAssignment: {
10530 CheckExplicitlyDefaultedMoveAssignment(MD);
10531 if (!MD->isInvalidDecl())
10532 DefineImplicitMoveAssignment(DefaultLoc, MD);
10533 break;
10534 }
10535
10536 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010537 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010538 }
10539 } else {
10540 Diag(DefaultLoc, diag::err_default_special_members);
10541 }
10542}
10543
Sebastian Redl13e88542009-04-27 21:33:24 +000010544static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010545 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010546 Stmt *SubStmt = *CI;
10547 if (!SubStmt)
10548 continue;
10549 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010550 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010551 diag::err_return_in_constructor_handler);
10552 if (!isa<Expr>(SubStmt))
10553 SearchForReturnInStmt(Self, SubStmt);
10554 }
10555}
10556
10557void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10558 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10559 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10560 SearchForReturnInStmt(*this, Handler);
10561 }
10562}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010563
Mike Stump1eb44332009-09-09 15:08:12 +000010564bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010565 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010566 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10567 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010568
Chandler Carruth73857792010-02-15 11:53:20 +000010569 if (Context.hasSameType(NewTy, OldTy) ||
10570 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010571 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010572
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010573 // Check if the return types are covariant
10574 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010575
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010576 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010577 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10578 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010579 NewClassTy = NewPT->getPointeeType();
10580 OldClassTy = OldPT->getPointeeType();
10581 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010582 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10583 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10584 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10585 NewClassTy = NewRT->getPointeeType();
10586 OldClassTy = OldRT->getPointeeType();
10587 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010588 }
10589 }
Mike Stump1eb44332009-09-09 15:08:12 +000010590
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010591 // The return types aren't either both pointers or references to a class type.
10592 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010593 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010594 diag::err_different_return_type_for_overriding_virtual_function)
10595 << New->getDeclName() << NewTy << OldTy;
10596 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010597
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010598 return true;
10599 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010600
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010601 // C++ [class.virtual]p6:
10602 // If the return type of D::f differs from the return type of B::f, the
10603 // class type in the return type of D::f shall be complete at the point of
10604 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010605 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10606 if (!RT->isBeingDefined() &&
10607 RequireCompleteType(New->getLocation(), NewClassTy,
10608 PDiag(diag::err_covariant_return_incomplete)
10609 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010610 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010611 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010612
Douglas Gregora4923eb2009-11-16 21:35:15 +000010613 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010614 // Check if the new class derives from the old class.
10615 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10616 Diag(New->getLocation(),
10617 diag::err_covariant_return_not_derived)
10618 << New->getDeclName() << NewTy << OldTy;
10619 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10620 return true;
10621 }
Mike Stump1eb44332009-09-09 15:08:12 +000010622
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010623 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010624 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010625 diag::err_covariant_return_inaccessible_base,
10626 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10627 // FIXME: Should this point to the return type?
10628 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010629 // FIXME: this note won't trigger for delayed access control
10630 // diagnostics, and it's impossible to get an undelayed error
10631 // here from access control during the original parse because
10632 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010633 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10634 return true;
10635 }
10636 }
Mike Stump1eb44332009-09-09 15:08:12 +000010637
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010638 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010639 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010640 Diag(New->getLocation(),
10641 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010642 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10644 return true;
10645 };
Mike Stump1eb44332009-09-09 15:08:12 +000010646
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010647
10648 // The new class type must have the same or less qualifiers as the old type.
10649 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10650 Diag(New->getLocation(),
10651 diag::err_covariant_return_type_class_type_more_qualified)
10652 << New->getDeclName() << NewTy << OldTy;
10653 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10654 return true;
10655 };
Mike Stump1eb44332009-09-09 15:08:12 +000010656
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010657 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010658}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010659
Douglas Gregor4ba31362009-12-01 17:24:26 +000010660/// \brief Mark the given method pure.
10661///
10662/// \param Method the method to be marked pure.
10663///
10664/// \param InitRange the source range that covers the "0" initializer.
10665bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010666 SourceLocation EndLoc = InitRange.getEnd();
10667 if (EndLoc.isValid())
10668 Method->setRangeEnd(EndLoc);
10669
Douglas Gregor4ba31362009-12-01 17:24:26 +000010670 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10671 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010672 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010673 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010674
10675 if (!Method->isInvalidDecl())
10676 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10677 << Method->getDeclName() << InitRange;
10678 return true;
10679}
10680
Douglas Gregor552e2992012-02-21 02:22:07 +000010681/// \brief Determine whether the given declaration is a static data member.
10682static bool isStaticDataMember(Decl *D) {
10683 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10684 if (!Var)
10685 return false;
10686
10687 return Var->isStaticDataMember();
10688}
John McCall731ad842009-12-19 09:28:58 +000010689/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10690/// an initializer for the out-of-line declaration 'Dcl'. The scope
10691/// is a fresh scope pushed for just this purpose.
10692///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010693/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10694/// static data member of class X, names should be looked up in the scope of
10695/// class X.
John McCalld226f652010-08-21 09:40:31 +000010696void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010697 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010698 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010699
John McCall731ad842009-12-19 09:28:58 +000010700 // We should only get called for declarations with scope specifiers, like:
10701 // int foo::bar;
10702 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010703 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010704
10705 // If we are parsing the initializer for a static data member, push a
10706 // new expression evaluation context that is associated with this static
10707 // data member.
10708 if (isStaticDataMember(D))
10709 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010710}
10711
10712/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010713/// initializer for the out-of-line declaration 'D'.
10714void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010715 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010716 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010717
Douglas Gregor552e2992012-02-21 02:22:07 +000010718 if (isStaticDataMember(D))
10719 PopExpressionEvaluationContext();
10720
John McCall731ad842009-12-19 09:28:58 +000010721 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010722 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010723}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010724
10725/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10726/// C++ if/switch/while/for statement.
10727/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010728DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010729 // C++ 6.4p2:
10730 // The declarator shall not specify a function or an array.
10731 // The type-specifier-seq shall not contain typedef and shall not declare a
10732 // new class or enumeration.
10733 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10734 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010735
10736 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010737 if (!Dcl)
10738 return true;
10739
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010740 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10741 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010742 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010743 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010744 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010745
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010746 return Dcl;
10747}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010748
Douglas Gregordfe65432011-07-28 19:11:31 +000010749void Sema::LoadExternalVTableUses() {
10750 if (!ExternalSource)
10751 return;
10752
10753 SmallVector<ExternalVTableUse, 4> VTables;
10754 ExternalSource->ReadUsedVTables(VTables);
10755 SmallVector<VTableUse, 4> NewUses;
10756 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10757 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10758 = VTablesUsed.find(VTables[I].Record);
10759 // Even if a definition wasn't required before, it may be required now.
10760 if (Pos != VTablesUsed.end()) {
10761 if (!Pos->second && VTables[I].DefinitionRequired)
10762 Pos->second = true;
10763 continue;
10764 }
10765
10766 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10767 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10768 }
10769
10770 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10771}
10772
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010773void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10774 bool DefinitionRequired) {
10775 // Ignore any vtable uses in unevaluated operands or for classes that do
10776 // not have a vtable.
10777 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10778 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010779 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010780 return;
10781
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010782 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010783 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010784 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10785 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10786 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10787 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010788 // If we already had an entry, check to see if we are promoting this vtable
10789 // to required a definition. If so, we need to reappend to the VTableUses
10790 // list, since we may have already processed the first entry.
10791 if (DefinitionRequired && !Pos.first->second) {
10792 Pos.first->second = true;
10793 } else {
10794 // Otherwise, we can early exit.
10795 return;
10796 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010797 }
10798
10799 // Local classes need to have their virtual members marked
10800 // immediately. For all other classes, we mark their virtual members
10801 // at the end of the translation unit.
10802 if (Class->isLocalClass())
10803 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010804 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010805 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010806}
10807
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010808bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010809 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010810 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010811 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010812
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010813 // Note: The VTableUses vector could grow as a result of marking
10814 // the members of a class as "used", so we check the size each
10815 // time through the loop and prefer indices (with are stable) to
10816 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010817 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010818 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010819 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010820 if (!Class)
10821 continue;
10822
10823 SourceLocation Loc = VTableUses[I].second;
10824
10825 // If this class has a key function, but that key function is
10826 // defined in another translation unit, we don't need to emit the
10827 // vtable even though we're using it.
10828 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010829 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010830 switch (KeyFunction->getTemplateSpecializationKind()) {
10831 case TSK_Undeclared:
10832 case TSK_ExplicitSpecialization:
10833 case TSK_ExplicitInstantiationDeclaration:
10834 // The key function is in another translation unit.
10835 continue;
10836
10837 case TSK_ExplicitInstantiationDefinition:
10838 case TSK_ImplicitInstantiation:
10839 // We will be instantiating the key function.
10840 break;
10841 }
10842 } else if (!KeyFunction) {
10843 // If we have a class with no key function that is the subject
10844 // of an explicit instantiation declaration, suppress the
10845 // vtable; it will live with the explicit instantiation
10846 // definition.
10847 bool IsExplicitInstantiationDeclaration
10848 = Class->getTemplateSpecializationKind()
10849 == TSK_ExplicitInstantiationDeclaration;
10850 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10851 REnd = Class->redecls_end();
10852 R != REnd; ++R) {
10853 TemplateSpecializationKind TSK
10854 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10855 if (TSK == TSK_ExplicitInstantiationDeclaration)
10856 IsExplicitInstantiationDeclaration = true;
10857 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10858 IsExplicitInstantiationDeclaration = false;
10859 break;
10860 }
10861 }
10862
10863 if (IsExplicitInstantiationDeclaration)
10864 continue;
10865 }
10866
10867 // Mark all of the virtual members of this class as referenced, so
10868 // that we can build a vtable. Then, tell the AST consumer that a
10869 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010870 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010871 MarkVirtualMembersReferenced(Loc, Class);
10872 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10873 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10874
10875 // Optionally warn if we're emitting a weak vtable.
10876 if (Class->getLinkage() == ExternalLinkage &&
10877 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010878 const FunctionDecl *KeyFunctionDef = 0;
10879 if (!KeyFunction ||
10880 (KeyFunction->hasBody(KeyFunctionDef) &&
10881 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010882 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10883 TSK_ExplicitInstantiationDefinition
10884 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10885 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010886 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010887 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010888 VTableUses.clear();
10889
Douglas Gregor78844032011-04-22 22:25:37 +000010890 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010891}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010892
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010893void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10894 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010895 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10896 e = RD->method_end(); i != e; ++i) {
10897 CXXMethodDecl *MD = *i;
10898
10899 // C++ [basic.def.odr]p2:
10900 // [...] A virtual member function is used if it is not pure. [...]
10901 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010902 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010903 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010904
10905 // Only classes that have virtual bases need a VTT.
10906 if (RD->getNumVBases() == 0)
10907 return;
10908
10909 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10910 e = RD->bases_end(); i != e; ++i) {
10911 const CXXRecordDecl *Base =
10912 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010913 if (Base->getNumVBases() == 0)
10914 continue;
10915 MarkVirtualMembersReferenced(Loc, Base);
10916 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010917}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010918
10919/// SetIvarInitializers - This routine builds initialization ASTs for the
10920/// Objective-C implementation whose ivars need be initialized.
10921void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010922 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010923 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010924 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010925 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010926 CollectIvarsToConstructOrDestruct(OID, ivars);
10927 if (ivars.empty())
10928 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010929 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010930 for (unsigned i = 0; i < ivars.size(); i++) {
10931 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010932 if (Field->isInvalidDecl())
10933 continue;
10934
Sean Huntcbb67482011-01-08 20:30:50 +000010935 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010936 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10937 InitializationKind InitKind =
10938 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10939
10940 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010941 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010942 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010943 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010944 // Note, MemberInit could actually come back empty if no initialization
10945 // is required (e.g., because it would call a trivial default constructor)
10946 if (!MemberInit.get() || MemberInit.isInvalid())
10947 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010948
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010949 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010950 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10951 SourceLocation(),
10952 MemberInit.takeAs<Expr>(),
10953 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010954 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010955
10956 // Be sure that the destructor is accessible and is marked as referenced.
10957 if (const RecordType *RecordTy
10958 = Context.getBaseElementType(Field->getType())
10959 ->getAs<RecordType>()) {
10960 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010961 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010962 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010963 CheckDestructorAccess(Field->getLocation(), Destructor,
10964 PDiag(diag::err_access_dtor_ivar)
10965 << Context.getBaseElementType(Field->getType()));
10966 }
10967 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010968 }
10969 ObjCImplementation->setIvarInitializers(Context,
10970 AllToInit.data(), AllToInit.size());
10971 }
10972}
Sean Huntfe57eef2011-05-04 05:57:24 +000010973
Sean Huntebcbe1d2011-05-04 23:29:54 +000010974static
10975void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10976 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10977 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10978 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10979 Sema &S) {
10980 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10981 CE = Current.end();
10982 if (Ctor->isInvalidDecl())
10983 return;
10984
10985 const FunctionDecl *FNTarget = 0;
10986 CXXConstructorDecl *Target;
10987
10988 // We ignore the result here since if we don't have a body, Target will be
10989 // null below.
10990 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10991 Target
10992= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10993
10994 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10995 // Avoid dereferencing a null pointer here.
10996 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10997
10998 if (!Current.insert(Canonical))
10999 return;
11000
11001 // We know that beyond here, we aren't chaining into a cycle.
11002 if (!Target || !Target->isDelegatingConstructor() ||
11003 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11004 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11005 Valid.insert(*CI);
11006 Current.clear();
11007 // We've hit a cycle.
11008 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11009 Current.count(TCanonical)) {
11010 // If we haven't diagnosed this cycle yet, do so now.
11011 if (!Invalid.count(TCanonical)) {
11012 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011013 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011014 << Ctor;
11015
11016 // Don't add a note for a function delegating directo to itself.
11017 if (TCanonical != Canonical)
11018 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11019
11020 CXXConstructorDecl *C = Target;
11021 while (C->getCanonicalDecl() != Canonical) {
11022 (void)C->getTargetConstructor()->hasBody(FNTarget);
11023 assert(FNTarget && "Ctor cycle through bodiless function");
11024
11025 C
11026 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11027 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11028 }
11029 }
11030
11031 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11032 Invalid.insert(*CI);
11033 Current.clear();
11034 } else {
11035 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11036 }
11037}
11038
11039
Sean Huntfe57eef2011-05-04 05:57:24 +000011040void Sema::CheckDelegatingCtorCycles() {
11041 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11042
Sean Huntebcbe1d2011-05-04 23:29:54 +000011043 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11044 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011045
Douglas Gregor0129b562011-07-27 21:57:17 +000011046 for (DelegatingCtorDeclsType::iterator
11047 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011048 E = DelegatingCtorDecls.end();
11049 I != E; ++I) {
11050 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011051 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011052
11053 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11054 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011055}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011056
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011057namespace {
11058 /// \brief AST visitor that finds references to the 'this' expression.
11059 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11060 Sema &S;
11061
11062 public:
11063 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11064
11065 bool VisitCXXThisExpr(CXXThisExpr *E) {
11066 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11067 << E->isImplicit();
11068 return false;
11069 }
11070 };
11071}
11072
11073bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11074 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11075 if (!TSInfo)
11076 return false;
11077
11078 TypeLoc TL = TSInfo->getTypeLoc();
11079 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11080 if (!ProtoTL)
11081 return false;
11082
11083 // C++11 [expr.prim.general]p3:
11084 // [The expression this] shall not appear before the optional
11085 // cv-qualifier-seq and it shall not appear within the declaration of a
11086 // static member function (although its type and value category are defined
11087 // within a static member function as they are within a non-static member
11088 // function). [ Note: this is because declaration matching does not occur
11089 // until the complete declarator is known. — end note ]
11090 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11091 FindCXXThisExpr Finder(*this);
11092
11093 // If the return type came after the cv-qualifier-seq, check it now.
11094 if (Proto->hasTrailingReturn() &&
11095 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11096 return true;
11097
11098 // Check the exception specification.
11099 switch (Proto->getExceptionSpecType()) {
11100 case EST_BasicNoexcept:
11101 case EST_Delayed:
11102 case EST_DynamicNone:
11103 case EST_MSAny:
11104 case EST_None:
11105 break;
11106
11107 case EST_ComputedNoexcept:
11108 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11109 return true;
11110
11111 case EST_Dynamic:
11112 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11113 EEnd = Proto->exception_end();
11114 E != EEnd; ++E) {
11115 if (!Finder.TraverseType(*E))
11116 return true;
11117 }
11118 break;
11119 }
11120
11121 return checkThisInStaticMemberFunctionAttributes(Method);
11122}
11123
11124bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11125 FindCXXThisExpr Finder(*this);
11126
11127 // Check attributes.
11128 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11129 A != AEnd; ++A) {
11130 // FIXME: This should be emitted by tblgen.
11131 Expr *Arg = 0;
11132 ArrayRef<Expr *> Args;
11133 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11134 Arg = G->getArg();
11135 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11136 Arg = G->getArg();
11137 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11138 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11139 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11140 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11141 else if (ExclusiveLockFunctionAttr *ELF
11142 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11143 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11144 else if (SharedLockFunctionAttr *SLF
11145 = dyn_cast<SharedLockFunctionAttr>(*A))
11146 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11147 else if (ExclusiveTrylockFunctionAttr *ETLF
11148 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11149 Arg = ETLF->getSuccessValue();
11150 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11151 } else if (SharedTrylockFunctionAttr *STLF
11152 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11153 Arg = STLF->getSuccessValue();
11154 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11155 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11156 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11157 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11158 Arg = LR->getArg();
11159 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11160 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11161 else if (ExclusiveLocksRequiredAttr *ELR
11162 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11163 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11164 else if (SharedLocksRequiredAttr *SLR
11165 = dyn_cast<SharedLocksRequiredAttr>(*A))
11166 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11167
11168 if (Arg && !Finder.TraverseStmt(Arg))
11169 return true;
11170
11171 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11172 if (!Finder.TraverseStmt(Args[I]))
11173 return true;
11174 }
11175 }
11176
11177 return false;
11178}
11179
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011180/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11181Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11182 // Implicitly declared functions (e.g. copy constructors) are
11183 // __host__ __device__
11184 if (D->isImplicit())
11185 return CFT_HostDevice;
11186
11187 if (D->hasAttr<CUDAGlobalAttr>())
11188 return CFT_Global;
11189
11190 if (D->hasAttr<CUDADeviceAttr>()) {
11191 if (D->hasAttr<CUDAHostAttr>())
11192 return CFT_HostDevice;
11193 else
11194 return CFT_Device;
11195 }
11196
11197 return CFT_Host;
11198}
11199
11200bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11201 CUDAFunctionTarget CalleeTarget) {
11202 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11203 // Callable from the device only."
11204 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11205 return true;
11206
11207 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11208 // Callable from the host only."
11209 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11210 // Callable from the host only."
11211 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11212 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11213 return true;
11214
11215 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11216 return true;
11217
11218 return false;
11219}