blob: 2d3f2c023962b1024292ed96e373e8daa86097d9 [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"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000250 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377// MergeCXXFunctionDecl - Merge two declarations of the same C++
378// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000379// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000521 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
522 CXXSpecialMember NewSM = getSpecialMember(Ctor),
523 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
524 if (NewSM != OldSM) {
525 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
526 << NewParam->getDefaultArgRange() << NewSM;
527 Diag(Old->getLocation(), diag::note_previous_declaration_special)
528 << OldSM;
529 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000530 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000531 }
532 }
533
Richard Smithff234882012-02-20 23:28:05 +0000534 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000535 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000536 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000537 if (New->isConstexpr() != Old->isConstexpr()) {
538 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
539 << New << New->isConstexpr();
540 Diag(Old->getLocation(), diag::note_previous_declaration);
541 Invalid = true;
542 }
543
Douglas Gregore13ad832010-02-12 07:32:17 +0000544 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000546
Douglas Gregorcda9c672009-02-16 17:45:42 +0000547 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000548}
549
Sebastian Redl60618fa2011-03-12 11:50:43 +0000550/// \brief Merge the exception specifications of two variable declarations.
551///
552/// This is called when there's a redeclaration of a VarDecl. The function
553/// checks if the redeclaration might have an exception specification and
554/// validates compatibility and merges the specs if necessary.
555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
556 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000557 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000558 return;
559
560 assert(Context.hasSameType(New->getType(), Old->getType()) &&
561 "Should only be called if types are otherwise the same.");
562
563 QualType NewType = New->getType();
564 QualType OldType = Old->getType();
565
566 // We're only interested in pointers and references to functions, as well
567 // as pointers to member functions.
568 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
569 NewType = R->getPointeeType();
570 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
571 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
572 NewType = P->getPointeeType();
573 OldType = OldType->getAs<PointerType>()->getPointeeType();
574 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
575 NewType = M->getPointeeType();
576 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
577 }
578
579 if (!NewType->isFunctionProtoType())
580 return;
581
582 // There's lots of special cases for functions. For function pointers, system
583 // libraries are hopefully not as broken so that we don't need these
584 // workarounds.
585 if (CheckEquivalentExceptionSpec(
586 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
587 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
588 New->setInvalidDecl();
589 }
590}
591
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592/// CheckCXXDefaultArguments - Verify that the default arguments for a
593/// function declaration are well-formed according to C++
594/// [dcl.fct.default].
595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
596 unsigned NumParams = FD->getNumParams();
597 unsigned p;
598
Douglas Gregorc6889e72012-02-14 22:28:59 +0000599 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
600 isa<CXXMethodDecl>(FD) &&
601 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
602
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 // Find first parameter with a default argument
604 for (p = 0; p < NumParams; ++p) {
605 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 if (Param->hasDefaultArg()) {
607 // C++11 [expr.prim.lambda]p5:
608 // [...] Default arguments (8.3.6) shall not be specified in the
609 // parameter-declaration-clause of a lambda-declarator.
610 //
611 // FIXME: Core issue 974 strikes this sentence, we only provide an
612 // extension warning.
613 if (IsLambda)
614 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
615 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000616 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000618 }
619
620 // C++ [dcl.fct.default]p4:
621 // In a given function declaration, all parameters
622 // subsequent to a parameter with a default argument shall
623 // have default arguments supplied in this or previous
624 // declarations. A default argument shall not be redefined
625 // by a later declaration (not even to the same value).
626 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000627 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000628 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000629 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000630 if (Param->isInvalidDecl())
631 /* We already complained about this parameter. */;
632 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000633 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000634 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000635 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 else
Mike Stump1eb44332009-09-09 15:08:12 +0000637 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000638 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 LastMissingDefaultArg = p;
641 }
642 }
643
644 if (LastMissingDefaultArg > 0) {
645 // Some default arguments were missing. Clear out all of the
646 // default arguments up to (and including) the last missing
647 // default argument, so that we leave the function parameters
648 // in a semantically valid state.
649 for (p = 0; p <= LastMissingDefaultArg; ++p) {
650 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000651 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652 Param->setDefaultArg(0);
653 }
654 }
655 }
656}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000657
Richard Smith9f569cc2011-10-01 02:31:28 +0000658// CheckConstexprParameterTypes - Check whether a function's parameter types
659// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000660// diagnostic and return false.
661static bool CheckConstexprParameterTypes(Sema &SemaRef,
662 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000663 unsigned ArgIndex = 0;
664 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
665 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
666 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
667 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
668 SourceLocation ParamLoc = PD->getLocation();
669 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000670 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000671 diag::err_constexpr_non_literal_param,
672 ArgIndex+1, PD->getSourceRange(),
673 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000675 }
676 return true;
677}
678
679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000680// the requirements of a constexpr function definition or a constexpr
681// constructor definition. If so, return true. If not, produce appropriate
682// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000683//
Richard Smith86c3ae42012-02-13 03:54:03 +0000684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000686 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
687 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 // C++11 [dcl.constexpr]p4:
689 // The definition of a constexpr constructor shall satisfy the following
690 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000691 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000692 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000694 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696 << RD->getNumVBases();
697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000699 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000700 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 return false;
702 }
Richard Smith35340502012-01-13 04:54:00 +0000703 }
704
705 if (!isa<CXXConstructorDecl>(NewFD)) {
706 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000707 // The definition of a constexpr function shall satisfy the following
708 // constraints:
709 // - it shall not be virtual;
710 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
711 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000713
Richard Smith86c3ae42012-02-13 03:54:03 +0000714 // If it's not obvious why this function is virtual, find an overridden
715 // function which uses the 'virtual' keyword.
716 const CXXMethodDecl *WrittenVirtual = Method;
717 while (!WrittenVirtual->isVirtualAsWritten())
718 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
719 if (WrittenVirtual != Method)
720 Diag(WrittenVirtual->getLocation(),
721 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
724
725 // - its return type shall be a literal type;
726 QualType RT = NewFD->getResultType();
727 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000731 }
732
Richard Smith35340502012-01-13 04:54:00 +0000733 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000734 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000735 return false;
736
Richard Smith9f569cc2011-10-01 02:31:28 +0000737 return true;
738}
739
740/// Check the given declaration statement is legal within a constexpr function
741/// body. C++0x [dcl.constexpr]p3,p4.
742///
743/// \return true if the body is OK, false if we have diagnosed a problem.
744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
745 DeclStmt *DS) {
746 // C++0x [dcl.constexpr]p3 and p4:
747 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
748 // contain only
749 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
750 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
751 switch ((*DclIt)->getKind()) {
752 case Decl::StaticAssert:
753 case Decl::Using:
754 case Decl::UsingShadow:
755 case Decl::UsingDirective:
756 case Decl::UnresolvedUsingTypename:
757 // - static_assert-declarations
758 // - using-declarations,
759 // - using-directives,
760 continue;
761
762 case Decl::Typedef:
763 case Decl::TypeAlias: {
764 // - typedef declarations and alias-declarations that do not define
765 // classes or enumerations,
766 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
767 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
768 // Don't allow variably-modified types in constexpr functions.
769 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
770 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
771 << TL.getSourceRange() << TL.getType()
772 << isa<CXXConstructorDecl>(Dcl);
773 return false;
774 }
775 continue;
776 }
777
778 case Decl::Enum:
779 case Decl::CXXRecord:
780 // As an extension, we allow the declaration (but not the definition) of
781 // classes and enumerations in all declarations, not just in typedef and
782 // alias declarations.
783 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
784 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
785 << isa<CXXConstructorDecl>(Dcl);
786 return false;
787 }
788 continue;
789
790 case Decl::Var:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794
795 default:
796 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
797 << isa<CXXConstructorDecl>(Dcl);
798 return false;
799 }
800 }
801
802 return true;
803}
804
805/// Check that the given field is initialized within a constexpr constructor.
806///
807/// \param Dcl The constexpr constructor being checked.
808/// \param Field The field being checked. This may be a member of an anonymous
809/// struct or union nested within the class being checked.
810/// \param Inits All declarations, including anonymous struct/union members and
811/// indirect members, for which any initialization was provided.
812/// \param Diagnosed Set to true if an error is produced.
813static void CheckConstexprCtorInitializer(Sema &SemaRef,
814 const FunctionDecl *Dcl,
815 FieldDecl *Field,
816 llvm::SmallSet<Decl*, 16> &Inits,
817 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000818 if (Field->isUnnamedBitfield())
819 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000820
821 if (Field->isAnonymousStructOrUnion() &&
822 Field->getType()->getAsCXXRecordDecl()->isEmpty())
823 return;
824
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 if (!Inits.count(Field)) {
826 if (!Diagnosed) {
827 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
828 Diagnosed = true;
829 }
830 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
831 } else if (Field->isAnonymousStructOrUnion()) {
832 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
833 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
834 I != E; ++I)
835 // If an anonymous union contains an anonymous struct of which any member
836 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000837 if (!RD->isUnion() || Inits.count(*I))
838 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 }
840}
841
842/// Check the body for the given constexpr function declaration only contains
843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
844///
845/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // The definition of a constexpr function shall satisfy the following
850 // constraints: [...]
851 // - its function-body shall be = delete, = default, or a
852 // compound-statement
853 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000854 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 // In the definition of a constexpr constructor, [...]
856 // - its function-body shall not be a function-try-block;
857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
858 << isa<CXXConstructorDecl>(Dcl);
859 return false;
860 }
861
862 // - its function-body shall be [...] a compound-statement that contains only
863 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
864
865 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
868 switch ((*BodyIt)->getStmtClass()) {
869 case Stmt::NullStmtClass:
870 // - null statements,
871 continue;
872
873 case Stmt::DeclStmtClass:
874 // - static_assert-declarations
875 // - using-declarations,
876 // - using-directives,
877 // - typedef declarations and alias-declarations that do not define
878 // classes or enumerations,
879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
880 return false;
881 continue;
882
883 case Stmt::ReturnStmtClass:
884 // - and exactly one return statement;
885 if (isa<CXXConstructorDecl>(Dcl))
886 break;
887
888 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000889 continue;
890
891 default:
892 break;
893 }
894
895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896 << isa<CXXConstructorDecl>(Dcl);
897 return false;
898 }
899
900 if (const CXXConstructorDecl *Constructor
901 = dyn_cast<CXXConstructorDecl>(Dcl)) {
902 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000903 // DR1359:
904 // - every non-variant non-static data member and base class sub-object
905 // shall be initialized;
906 // - if the class is a non-empty union, or for each non-empty anonymous
907 // union member of a non-union class, exactly one non-static data member
908 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000910 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000911 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
912 return false;
913 }
Richard Smith6e433752011-10-10 16:38:04 +0000914 } else if (!Constructor->isDependentContext() &&
915 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000916 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
917
918 // Skip detailed checking if we have enough initializers, and we would
919 // allow at most one initializer per member.
920 bool AnyAnonStructUnionMembers = false;
921 unsigned Fields = 0;
922 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
923 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000924 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000925 AnyAnonStructUnionMembers = true;
926 break;
927 }
928 }
929 if (AnyAnonStructUnionMembers ||
930 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
931 // Check initialization of non-static data members. Base classes are
932 // always initialized so do not need to be checked. Dependent bases
933 // might not have initializers in the member initializer list.
934 llvm::SmallSet<Decl*, 16> Inits;
935 for (CXXConstructorDecl::init_const_iterator
936 I = Constructor->init_begin(), E = Constructor->init_end();
937 I != E; ++I) {
938 if (FieldDecl *FD = (*I)->getMember())
939 Inits.insert(FD);
940 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
941 Inits.insert(ID->chain_begin(), ID->chain_end());
942 }
943
944 bool Diagnosed = false;
945 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
946 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000947 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 if (Diagnosed)
949 return false;
950 }
951 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000952 } else {
953 if (ReturnStmts.empty()) {
954 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
955 return false;
956 }
957 if (ReturnStmts.size() > 1) {
958 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
959 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
960 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
961 return false;
962 }
963 }
964
Richard Smith5ba73e12012-02-04 00:33:54 +0000965 // C++11 [dcl.constexpr]p5:
966 // if no function argument values exist such that the function invocation
967 // substitution would produce a constant expression, the program is
968 // ill-formed; no diagnostic required.
969 // C++11 [dcl.constexpr]p3:
970 // - every constructor call and implicit conversion used in initializing the
971 // return value shall be one of those allowed in a constant expression.
972 // C++11 [dcl.constexpr]p4:
973 // - every constructor involved in initializing non-static data members and
974 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978 << isa<CXXConstructorDecl>(Dcl);
979 for (size_t I = 0, N = Diags.size(); I != N; ++I)
980 Diag(Diags[I].first, Diags[I].second);
981 return false;
982 }
983
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 return true;
985}
986
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000993 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000994
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000996 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000997 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999 } else
1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001002 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003 return &II == CurDecl->getIdentifier();
1004 else
1005 return false;
1006}
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014 SourceRange SpecifierRange,
1015 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001016 TypeSourceInfo *TInfo,
1017 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001018 QualType BaseType = TInfo->getType();
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 // C++ [class.union]p1:
1021 // A union shall not have base classes.
1022 if (Class->isUnion()) {
1023 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024 << SpecifierRange;
1025 return 0;
1026 }
1027
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 if (EllipsisLoc.isValid() &&
1029 !TInfo->getType()->containsUnexpandedParameterPack()) {
1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031 << TInfo->getTypeLoc().getSourceRange();
1032 EllipsisLoc = SourceLocation();
1033 }
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001037 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001038 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001039
1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041
1042 // Base specifiers must be record types.
1043 if (!BaseType->isRecordType()) {
1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045 return 0;
1046 }
1047
1048 // C++ [class.union]p1:
1049 // A union shall not be used as a base class.
1050 if (BaseType->isUnionType()) {
1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052 return 0;
1053 }
1054
1055 // C++ [class.derived]p2:
1056 // The class-name in a base-specifier shall not be an incompletely
1057 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001059 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001060 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061 return 0;
John McCall572fc622010-08-17 07:23:57 +00001062 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001063
Eli Friedman1d954f62009-08-15 21:55:26 +00001064 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001065 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001067 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001068 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001069 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1070 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001071
Anders Carlsson1d209272011-03-25 14:55:14 +00001072 // C++ [class]p3:
1073 // If a class is marked final and it appears as a base-type-specifier in
1074 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001075 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001076 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1077 << CXXBaseDecl->getDeclName();
1078 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1079 << CXXBaseDecl->getDeclName();
1080 return 0;
1081 }
1082
John McCall572fc622010-08-17 07:23:57 +00001083 if (BaseDecl->isInvalidDecl())
1084 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001085
1086 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001087 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001088 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001089 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001090}
1091
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1093/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001094/// example:
1095/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001096/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001097BaseResult
John McCalld226f652010-08-21 09:40:31 +00001098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001099 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001100 ParsedType basetype, SourceLocation BaseLoc,
1101 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001102 if (!classdecl)
1103 return true;
1104
Douglas Gregor40808ce2009-03-09 23:48:35 +00001105 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001106 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001107 if (!Class)
1108 return true;
1109
Nick Lewycky56062202010-07-26 16:56:01 +00001110 TypeSourceInfo *TInfo = 0;
1111 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001112
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 if (EllipsisLoc.isInvalid() &&
1114 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001115 UPPC_BaseType))
1116 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001119 Virtual, Access, TInfo,
1120 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001122 else
1123 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregor2943aed2009-03-03 04:44:36 +00001125 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001126}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001127
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128/// \brief Performs the actual work of attaching the given base class
1129/// specifiers to a C++ class.
1130bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1131 unsigned NumBases) {
1132 if (NumBases == 0)
1133 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001134
1135 // Used to keep track of which base types we have already seen, so
1136 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001137 // that the key is always the unqualified canonical type of the base
1138 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001139 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1140
1141 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001142 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001144 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001145 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001146 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001147 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001148
1149 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1150 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001151 // C++ [class.mi]p3:
1152 // A class shall not be specified as a direct base class of a
1153 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001154 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001155 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001156 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001157 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001158
1159 // Delete the duplicate base class specifier; we're going to
1160 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001161 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001162
1163 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001164 } else {
1165 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001166 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001167 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001168 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001169 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1170 if (RD->hasAttr<WeakAttr>())
1171 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001172 }
1173 }
1174
1175 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001176 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001177
1178 // Delete the remaining (good) base class specifiers, since their
1179 // data has been copied into the CXXRecordDecl.
1180 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001181 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001182
1183 return Invalid;
1184}
1185
1186/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1187/// class, after checking whether there are any duplicate base
1188/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001189void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001190 unsigned NumBases) {
1191 if (!ClassDecl || !Bases || !NumBases)
1192 return;
1193
1194 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001195 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001196 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001197}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001198
John McCall3cb0ebd2010-03-10 03:28:59 +00001199static CXXRecordDecl *GetClassForType(QualType T) {
1200 if (const RecordType *RT = T->getAs<RecordType>())
1201 return cast<CXXRecordDecl>(RT->getDecl());
1202 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1203 return ICT->getDecl();
1204 else
1205 return 0;
1206}
1207
Douglas Gregora8f32e02009-10-06 17:59:45 +00001208/// \brief Determine whether the type \p Derived is a C++ class that is
1209/// derived from the type \p Base.
1210bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001211 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001212 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001213
1214 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1215 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001216 return false;
1217
John McCall3cb0ebd2010-03-10 03:28:59 +00001218 CXXRecordDecl *BaseRD = GetClassForType(Base);
1219 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001220 return false;
1221
John McCall86ff3082010-02-04 22:26:26 +00001222 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1223 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001224}
1225
1226/// \brief Determine whether the type \p Derived is a C++ class that is
1227/// derived from the type \p Base.
1228bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001229 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001230 return false;
1231
John McCall3cb0ebd2010-03-10 03:28:59 +00001232 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1233 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001234 return false;
1235
John McCall3cb0ebd2010-03-10 03:28:59 +00001236 CXXRecordDecl *BaseRD = GetClassForType(Base);
1237 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001238 return false;
1239
Douglas Gregora8f32e02009-10-06 17:59:45 +00001240 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1241}
1242
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001243void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001244 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001245 assert(BasePathArray.empty() && "Base path array must be empty!");
1246 assert(Paths.isRecordingPaths() && "Must record paths!");
1247
1248 const CXXBasePath &Path = Paths.front();
1249
1250 // We first go backward and check if we have a virtual base.
1251 // FIXME: It would be better if CXXBasePath had the base specifier for
1252 // the nearest virtual base.
1253 unsigned Start = 0;
1254 for (unsigned I = Path.size(); I != 0; --I) {
1255 if (Path[I - 1].Base->isVirtual()) {
1256 Start = I - 1;
1257 break;
1258 }
1259 }
1260
1261 // Now add all bases.
1262 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001263 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001264}
1265
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001266/// \brief Determine whether the given base path includes a virtual
1267/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001268bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1269 for (CXXCastPath::const_iterator B = BasePath.begin(),
1270 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001271 B != BEnd; ++B)
1272 if ((*B)->isVirtual())
1273 return true;
1274
1275 return false;
1276}
1277
Douglas Gregora8f32e02009-10-06 17:59:45 +00001278/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1279/// conversion (where Derived and Base are class types) is
1280/// well-formed, meaning that the conversion is unambiguous (and
1281/// that all of the base classes are accessible). Returns true
1282/// and emits a diagnostic if the code is ill-formed, returns false
1283/// otherwise. Loc is the location where this routine should point to
1284/// if there is an error, and Range is the source range to highlight
1285/// if there is an error.
1286bool
1287Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001288 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001289 unsigned AmbigiousBaseConvID,
1290 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001291 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001292 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001293 // First, determine whether the path from Derived to Base is
1294 // ambiguous. This is slightly more expensive than checking whether
1295 // the Derived to Base conversion exists, because here we need to
1296 // explore multiple paths to determine if there is an ambiguity.
1297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1298 /*DetectVirtual=*/false);
1299 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1300 assert(DerivationOkay &&
1301 "Can only be used with a derived-to-base conversion");
1302 (void)DerivationOkay;
1303
1304 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001305 if (InaccessibleBaseID) {
1306 // Check that the base class can be accessed.
1307 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1308 InaccessibleBaseID)) {
1309 case AR_inaccessible:
1310 return true;
1311 case AR_accessible:
1312 case AR_dependent:
1313 case AR_delayed:
1314 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001315 }
John McCall6b2accb2010-02-10 09:31:12 +00001316 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001317
1318 // Build a base path if necessary.
1319 if (BasePath)
1320 BuildBasePathArray(Paths, *BasePath);
1321 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 }
1323
1324 // We know that the derived-to-base conversion is ambiguous, and
1325 // we're going to produce a diagnostic. Perform the derived-to-base
1326 // search just one more time to compute all of the possible paths so
1327 // that we can print them out. This is more expensive than any of
1328 // the previous derived-to-base checks we've done, but at this point
1329 // performance isn't as much of an issue.
1330 Paths.clear();
1331 Paths.setRecordingPaths(true);
1332 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1333 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1334 (void)StillOkay;
1335
1336 // Build up a textual representation of the ambiguous paths, e.g.,
1337 // D -> B -> A, that will be used to illustrate the ambiguous
1338 // conversions in the diagnostic. We only print one of the paths
1339 // to each base class subobject.
1340 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1341
1342 Diag(Loc, AmbigiousBaseConvID)
1343 << Derived << Base << PathDisplayStr << Range << Name;
1344 return true;
1345}
1346
1347bool
1348Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001349 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001350 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001351 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001353 IgnoreAccess ? 0
1354 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001356 Loc, Range, DeclarationName(),
1357 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001358}
1359
1360
1361/// @brief Builds a string representing ambiguous paths from a
1362/// specific derived class to different subobjects of the same base
1363/// class.
1364///
1365/// This function builds a string that can be used in error messages
1366/// to show the different paths that one can take through the
1367/// inheritance hierarchy to go from the derived class to different
1368/// subobjects of a base class. The result looks something like this:
1369/// @code
1370/// struct D -> struct B -> struct A
1371/// struct D -> struct C -> struct A
1372/// @endcode
1373std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1374 std::string PathDisplayStr;
1375 std::set<unsigned> DisplayedPaths;
1376 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1377 Path != Paths.end(); ++Path) {
1378 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1379 // We haven't displayed a path to this particular base
1380 // class subobject yet.
1381 PathDisplayStr += "\n ";
1382 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1383 for (CXXBasePath::const_iterator Element = Path->begin();
1384 Element != Path->end(); ++Element)
1385 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1386 }
1387 }
1388
1389 return PathDisplayStr;
1390}
1391
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001392//===----------------------------------------------------------------------===//
1393// C++ class member Handling
1394//===----------------------------------------------------------------------===//
1395
Abramo Bagnara6206d532010-06-05 05:09:32 +00001396/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001397bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1398 SourceLocation ASLoc,
1399 SourceLocation ColonLoc,
1400 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001401 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001402 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001403 ASLoc, ColonLoc);
1404 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001405 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001406}
1407
Richard Smitha4b39652012-08-06 03:25:17 +00001408/// CheckOverrideControl - Check C++11 override control semantics.
1409void Sema::CheckOverrideControl(Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001410 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001411
Richard Smitha4b39652012-08-06 03:25:17 +00001412 // Do we know which functions this declaration might be overriding?
1413 bool OverridesAreKnown = !MD ||
1414 (!MD->getParent()->hasAnyDependentBases() &&
1415 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001416
Richard Smitha4b39652012-08-06 03:25:17 +00001417 if (!MD || !MD->isVirtual()) {
1418 if (OverridesAreKnown) {
1419 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1420 Diag(OA->getLocation(),
1421 diag::override_keyword_only_allowed_on_virtual_member_functions)
1422 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1423 D->dropAttr<OverrideAttr>();
1424 }
1425 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1426 Diag(FA->getLocation(),
1427 diag::override_keyword_only_allowed_on_virtual_member_functions)
1428 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1429 D->dropAttr<FinalAttr>();
1430 }
1431 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001432 return;
1433 }
Richard Smitha4b39652012-08-06 03:25:17 +00001434
1435 if (!OverridesAreKnown)
1436 return;
1437
1438 // C++11 [class.virtual]p5:
1439 // If a virtual function is marked with the virt-specifier override and
1440 // does not override a member function of a base class, the program is
1441 // ill-formed.
1442 bool HasOverriddenMethods =
1443 MD->begin_overridden_methods() != MD->end_overridden_methods();
1444 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1445 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1446 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001447}
1448
Richard Smitha4b39652012-08-06 03:25:17 +00001449/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001450/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001451/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001452bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1453 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001454 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001455 return false;
1456
1457 Diag(New->getLocation(), diag::err_final_function_overridden)
1458 << New->getDeclName();
1459 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1460 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001461}
1462
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001463static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001464 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1465 // FIXME: Destruction of ObjC lifetime types has side-effects.
1466 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1467 return !RD->isCompleteDefinition() ||
1468 !RD->hasTrivialDefaultConstructor() ||
1469 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001470 return false;
1471}
1472
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1474/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001475/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001476/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1477/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001478Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001480 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001481 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001482 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001483 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001484 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1485 DeclarationName Name = NameInfo.getName();
1486 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001487
1488 // For anonymous bitfields, the location should point to the type.
1489 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001490 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001491
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001493
John McCall4bde1e12010-06-04 08:34:12 +00001494 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001495 assert(!DS.isFriendSpecified());
1496
Richard Smith1ab0d902011-06-25 02:28:38 +00001497 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001498
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001499 // C++ 9.2p6: A member shall not be declared to have automatic storage
1500 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1502 // data members and cannot be applied to names declared const or static,
1503 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001504 switch (DS.getStorageClassSpec()) {
1505 case DeclSpec::SCS_unspecified:
1506 case DeclSpec::SCS_typedef:
1507 case DeclSpec::SCS_static:
1508 // FALL THROUGH.
1509 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001510 case DeclSpec::SCS_mutable:
1511 if (isFunc) {
1512 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001513 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001514 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001515 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Sebastian Redla11f42f2008-11-17 23:24:37 +00001517 // FIXME: It would be nicer if the keyword was ignored only for this
1518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001519 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001520 }
1521 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001522 default:
1523 if (DS.getStorageClassSpecLoc().isValid())
1524 Diag(DS.getStorageClassSpecLoc(),
1525 diag::err_storageclass_invalid_for_member);
1526 else
1527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1528 D.getMutableDeclSpec().ClearStorageClassSpecs();
1529 }
1530
Sebastian Redl669d5d72008-11-14 23:42:31 +00001531 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1532 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001533 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001534
1535 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001536 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001537 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001538
1539 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001540 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001541 Diag(Loc, diag::err_bad_variable_name)
1542 << Name;
1543 return 0;
1544 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001545
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001546 IdentifierInfo *II = Name.getAsIdentifierInfo();
1547
Douglas Gregorf2503652011-09-21 14:40:46 +00001548 // Member field could not be with "template" keyword.
1549 // So TemplateParameterLists should be empty in this case.
1550 if (TemplateParameterLists.size()) {
1551 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1552 if (TemplateParams->size()) {
1553 // There is no such thing as a member field template.
1554 Diag(D.getIdentifierLoc(), diag::err_template_member)
1555 << II
1556 << SourceRange(TemplateParams->getTemplateLoc(),
1557 TemplateParams->getRAngleLoc());
1558 } else {
1559 // There is an extraneous 'template<>' for this member.
1560 Diag(TemplateParams->getTemplateLoc(),
1561 diag::err_template_member_noparams)
1562 << II
1563 << SourceRange(TemplateParams->getTemplateLoc(),
1564 TemplateParams->getRAngleLoc());
1565 }
1566 return 0;
1567 }
1568
Douglas Gregor922fff22010-10-13 22:19:53 +00001569 if (SS.isSet() && !SS.isInvalid()) {
1570 // The user provided a superfluous scope specifier inside a class
1571 // definition:
1572 //
1573 // class X {
1574 // int X::member;
1575 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001576 if (DeclContext *DC = computeDeclContext(SS, false))
1577 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001578 else
1579 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1580 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001581
Douglas Gregor922fff22010-10-13 22:19:53 +00001582 SS.clear();
1583 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001584
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001585 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001586 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001587 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001588 } else {
Richard Smithca523302012-06-10 03:12:00 +00001589 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001590
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001591 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001592 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001593 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001594 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001595
1596 // Non-instance-fields can't have a bitfield.
1597 if (BitWidth) {
1598 if (Member->isInvalidDecl()) {
1599 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001600 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001601 // C++ 9.6p3: A bit-field shall not be a static member.
1602 // "static member 'A' cannot be a bit-field"
1603 Diag(Loc, diag::err_static_not_bitfield)
1604 << Name << BitWidth->getSourceRange();
1605 } else if (isa<TypedefDecl>(Member)) {
1606 // "typedef member 'x' cannot be a bit-field"
1607 Diag(Loc, diag::err_typedef_not_bitfield)
1608 << Name << BitWidth->getSourceRange();
1609 } else {
1610 // A function typedef ("typedef int f(); f a;").
1611 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1612 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001613 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001614 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner8b963ef2009-03-05 23:01:03 +00001617 BitWidth = 0;
1618 Member->setInvalidDecl();
1619 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001620
1621 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregor37b372b2009-08-20 22:52:58 +00001623 // If we have declared a member function template, set the access of the
1624 // templated declaration as well.
1625 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1626 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001627 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001628
Richard Smitha4b39652012-08-06 03:25:17 +00001629 if (VS.isOverrideSpecified())
1630 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1631 if (VS.isFinalSpecified())
1632 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001633
Douglas Gregorf5251602011-03-08 17:10:18 +00001634 if (VS.getLastLocation().isValid()) {
1635 // Update the end location of a method that has a virt-specifiers.
1636 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1637 MD->setRangeEnd(VS.getLastLocation());
1638 }
Richard Smitha4b39652012-08-06 03:25:17 +00001639
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001640 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001641
Douglas Gregor10bd3682008-11-17 22:58:34 +00001642 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001643
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001644 if (isInstField) {
1645 FieldDecl *FD = cast<FieldDecl>(Member);
1646 FieldCollector->Add(FD);
1647
1648 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1649 FD->getLocation())
1650 != DiagnosticsEngine::Ignored) {
1651 // Remember all explicit private FieldDecls that have a name, no side
1652 // effects and are not part of a dependent type declaration.
1653 if (!FD->isImplicit() && FD->getDeclName() &&
1654 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001655 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001656 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001657 !InitializationHasSideEffects(*FD))
1658 UnusedPrivateFields.insert(FD);
1659 }
1660 }
1661
John McCalld226f652010-08-21 09:40:31 +00001662 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001663}
1664
Richard Smith7a614d82011-06-11 17:19:42 +00001665/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001666/// in-class initializer for a non-static C++ class member, and after
1667/// instantiating an in-class initializer in a class template. Such actions
1668/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001669void
Richard Smithca523302012-06-10 03:12:00 +00001670Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001671 Expr *InitExpr) {
1672 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001673 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1674 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001675
1676 if (!InitExpr) {
1677 FD->setInvalidDecl();
1678 FD->removeInClassInitializer();
1679 return;
1680 }
1681
Peter Collingbournefef21892011-10-23 18:59:44 +00001682 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1683 FD->setInvalidDecl();
1684 FD->removeInClassInitializer();
1685 return;
1686 }
1687
Richard Smith7a614d82011-06-11 17:19:42 +00001688 ExprResult Init = InitExpr;
1689 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001690 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001691 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001692 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1693 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001694 Expr **Inits = &InitExpr;
1695 unsigned NumInits = 1;
1696 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001697 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001698 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001699 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001700 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1701 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001702 if (Init.isInvalid()) {
1703 FD->setInvalidDecl();
1704 return;
1705 }
1706
Richard Smithca523302012-06-10 03:12:00 +00001707 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001708 }
1709
1710 // C++0x [class.base.init]p7:
1711 // The initialization of each base and member constitutes a
1712 // full-expression.
1713 Init = MaybeCreateExprWithCleanups(Init);
1714 if (Init.isInvalid()) {
1715 FD->setInvalidDecl();
1716 return;
1717 }
1718
1719 InitExpr = Init.release();
1720
1721 FD->setInClassInitializer(InitExpr);
1722}
1723
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001724/// \brief Find the direct and/or virtual base specifiers that
1725/// correspond to the given base type, for use in base initialization
1726/// within a constructor.
1727static bool FindBaseInitializer(Sema &SemaRef,
1728 CXXRecordDecl *ClassDecl,
1729 QualType BaseType,
1730 const CXXBaseSpecifier *&DirectBaseSpec,
1731 const CXXBaseSpecifier *&VirtualBaseSpec) {
1732 // First, check for a direct base class.
1733 DirectBaseSpec = 0;
1734 for (CXXRecordDecl::base_class_const_iterator Base
1735 = ClassDecl->bases_begin();
1736 Base != ClassDecl->bases_end(); ++Base) {
1737 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1738 // We found a direct base of this type. That's what we're
1739 // initializing.
1740 DirectBaseSpec = &*Base;
1741 break;
1742 }
1743 }
1744
1745 // Check for a virtual base class.
1746 // FIXME: We might be able to short-circuit this if we know in advance that
1747 // there are no virtual bases.
1748 VirtualBaseSpec = 0;
1749 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1750 // We haven't found a base yet; search the class hierarchy for a
1751 // virtual base class.
1752 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1753 /*DetectVirtual=*/false);
1754 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1755 BaseType, Paths)) {
1756 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1757 Path != Paths.end(); ++Path) {
1758 if (Path->back().Base->isVirtual()) {
1759 VirtualBaseSpec = Path->back().Base;
1760 break;
1761 }
1762 }
1763 }
1764 }
1765
1766 return DirectBaseSpec || VirtualBaseSpec;
1767}
1768
Sebastian Redl6df65482011-09-24 17:48:25 +00001769/// \brief Handle a C++ member initializer using braced-init-list syntax.
1770MemInitResult
1771Sema::ActOnMemInitializer(Decl *ConstructorD,
1772 Scope *S,
1773 CXXScopeSpec &SS,
1774 IdentifierInfo *MemberOrBase,
1775 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001776 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001777 SourceLocation IdLoc,
1778 Expr *InitList,
1779 SourceLocation EllipsisLoc) {
1780 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001781 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001782 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001783}
1784
1785/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001786MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001787Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001788 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001789 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001790 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001791 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001792 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001793 SourceLocation IdLoc,
1794 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001795 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001796 SourceLocation RParenLoc,
1797 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001798 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1799 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001801 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001802}
1803
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001804namespace {
1805
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001806// Callback to only accept typo corrections that can be a valid C++ member
1807// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001808class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1809 public:
1810 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1811 : ClassDecl(ClassDecl) {}
1812
1813 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1814 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1815 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1816 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1817 else
1818 return isa<TypeDecl>(ND);
1819 }
1820 return false;
1821 }
1822
1823 private:
1824 CXXRecordDecl *ClassDecl;
1825};
1826
1827}
1828
Sebastian Redl6df65482011-09-24 17:48:25 +00001829/// \brief Handle a C++ member initializer.
1830MemInitResult
1831Sema::BuildMemInitializer(Decl *ConstructorD,
1832 Scope *S,
1833 CXXScopeSpec &SS,
1834 IdentifierInfo *MemberOrBase,
1835 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001836 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001837 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001838 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001839 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001840 if (!ConstructorD)
1841 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001843 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
1845 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001846 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 if (!Constructor) {
1848 // The user wrote a constructor initializer on a function that is
1849 // not a C++ constructor. Ignore the error for now, because we may
1850 // have more member initializers coming; we'll diagnose it just
1851 // once in ActOnMemInitializers.
1852 return true;
1853 }
1854
1855 CXXRecordDecl *ClassDecl = Constructor->getParent();
1856
1857 // C++ [class.base.init]p2:
1858 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001859 // constructor's class and, if not found in that scope, are looked
1860 // up in the scope containing the constructor's definition.
1861 // [Note: if the constructor's class contains a member with the
1862 // same name as a direct or virtual base class of the class, a
1863 // mem-initializer-id naming the member or base class and composed
1864 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001865 // mem-initializer-id for the hidden base class may be specified
1866 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001867 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001868 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001870 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001871 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001872 ValueDecl *Member;
1873 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1874 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001875 if (EllipsisLoc.isValid())
1876 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001877 << MemberOrBase
1878 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001879
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001880 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001881 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001882 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001883 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001884 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001885 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001886 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001887
1888 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001889 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001890 } else if (DS.getTypeSpecType() == TST_decltype) {
1891 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001892 } else {
1893 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1894 LookupParsedName(R, S, &SS);
1895
1896 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1897 if (!TyD) {
1898 if (R.isAmbiguous()) return true;
1899
John McCallfd225442010-04-09 19:01:14 +00001900 // We don't want access-control diagnostics here.
1901 R.suppressDiagnostics();
1902
Douglas Gregor7a886e12010-01-19 06:46:48 +00001903 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1904 bool NotUnknownSpecialization = false;
1905 DeclContext *DC = computeDeclContext(SS, false);
1906 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1907 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1908
1909 if (!NotUnknownSpecialization) {
1910 // When the scope specifier can refer to a member of an unknown
1911 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001912 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1913 SS.getWithLocInContext(Context),
1914 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001915 if (BaseType.isNull())
1916 return true;
1917
Douglas Gregor7a886e12010-01-19 06:46:48 +00001918 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001919 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001920 }
1921 }
1922
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001924 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001925 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001926 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001927 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001928 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001929 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1930 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001931 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001932 // We have found a non-static data member with a similar
1933 // name to what was typed; complain and initialize that
1934 // member.
1935 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1936 << MemberOrBase << true << CorrectedQuotedStr
1937 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1938 Diag(Member->getLocation(), diag::note_previous_decl)
1939 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001940
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001941 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001942 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001943 const CXXBaseSpecifier *DirectBaseSpec;
1944 const CXXBaseSpecifier *VirtualBaseSpec;
1945 if (FindBaseInitializer(*this, ClassDecl,
1946 Context.getTypeDeclType(Type),
1947 DirectBaseSpec, VirtualBaseSpec)) {
1948 // We have found a direct or virtual base class with a
1949 // similar name to what was typed; complain and initialize
1950 // that base class.
1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001952 << MemberOrBase << false << CorrectedQuotedStr
1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001954
1955 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1956 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001957 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001958 diag::note_base_class_specified_here)
1959 << BaseSpec->getType()
1960 << BaseSpec->getSourceRange();
1961
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001962 TyD = Type;
1963 }
1964 }
1965 }
1966
Douglas Gregor7a886e12010-01-19 06:46:48 +00001967 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001968 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001969 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001970 return true;
1971 }
John McCall2b194412009-12-21 10:41:20 +00001972 }
1973
Douglas Gregor7a886e12010-01-19 06:46:48 +00001974 if (BaseType.isNull()) {
1975 BaseType = Context.getTypeDeclType(TyD);
1976 if (SS.isSet()) {
1977 NestedNameSpecifier *Qualifier =
1978 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001979
Douglas Gregor7a886e12010-01-19 06:46:48 +00001980 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001981 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001982 }
John McCall2b194412009-12-21 10:41:20 +00001983 }
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
John McCalla93c9342009-12-07 02:54:59 +00001986 if (!TInfo)
1987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001988
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001990}
1991
Chandler Carruth81c64772011-09-03 01:14:15 +00001992/// Checks a member initializer expression for cases where reference (or
1993/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001994static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1995 Expr *Init,
1996 SourceLocation IdLoc) {
1997 QualType MemberTy = Member->getType();
1998
1999 // We only handle pointers and references currently.
2000 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2001 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2002 return;
2003
2004 const bool IsPointer = MemberTy->isPointerType();
2005 if (IsPointer) {
2006 if (const UnaryOperator *Op
2007 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2008 // The only case we're worried about with pointers requires taking the
2009 // address.
2010 if (Op->getOpcode() != UO_AddrOf)
2011 return;
2012
2013 Init = Op->getSubExpr();
2014 } else {
2015 // We only handle address-of expression initializers for pointers.
2016 return;
2017 }
2018 }
2019
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002020 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2021 // Taking the address of a temporary will be diagnosed as a hard error.
2022 if (IsPointer)
2023 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002024
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002025 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2026 << Member << Init->getSourceRange();
2027 } else if (const DeclRefExpr *DRE
2028 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2029 // We only warn when referring to a non-reference parameter declaration.
2030 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2031 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002032 return;
2033
2034 S.Diag(Init->getExprLoc(),
2035 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2036 : diag::warn_bind_ref_member_to_parameter)
2037 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002038 } else {
2039 // Other initializers are fine.
2040 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002041 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002042
2043 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2044 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002045}
2046
Richard Trieude5e75c2012-06-14 23:11:34 +00002047namespace {
2048 class UninitializedFieldVisitor
2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2050 Sema &S;
2051 ValueDecl *VD;
2052 public:
2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2055 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002056 }
2057
Richard Trieude5e75c2012-06-14 23:11:34 +00002058 void HandleExpr(Expr *E) {
2059 if (!E) return;
2060
2061 // Expressions like x(x) sometimes lack the surrounding expressions
2062 // but need to be checked anyways.
2063 HandleValue(E);
2064 Visit(E);
2065 }
2066
2067 void HandleValue(Expr *E) {
2068 E = E->IgnoreParens();
2069
Richard Trieue0991252012-06-14 23:18:09 +00002070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002071 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2072 return;
Richard Trieue0991252012-06-14 23:18:09 +00002073 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002074 while (isa<MemberExpr>(Base)) {
2075 ME = dyn_cast<MemberExpr>(Base);
2076 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2077 if (VarD->hasGlobalStorage())
2078 return;
2079 Base = ME->getBase();
2080 }
2081
2082 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg5965b7c2012-08-20 08:52:22 +00002083 unsigned diag = VD->getType()->isReferenceType()
2084 ? diag::warn_reference_field_is_uninit
2085 : diag::warn_field_is_uninit;
2086 S.Diag(ME->getExprLoc(), diag);
Richard Trieude5e75c2012-06-14 23:11:34 +00002087 return;
2088 }
John McCallb4190042009-11-04 23:02:40 +00002089 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002090
2091 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2092 HandleValue(CO->getTrueExpr());
2093 HandleValue(CO->getFalseExpr());
2094 return;
2095 }
2096
2097 if (BinaryConditionalOperator *BCO =
2098 dyn_cast<BinaryConditionalOperator>(E)) {
2099 HandleValue(BCO->getCommon());
2100 HandleValue(BCO->getFalseExpr());
2101 return;
2102 }
2103
2104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2105 switch (BO->getOpcode()) {
2106 default:
2107 return;
2108 case(BO_PtrMemD):
2109 case(BO_PtrMemI):
2110 HandleValue(BO->getLHS());
2111 return;
2112 case(BO_Comma):
2113 HandleValue(BO->getRHS());
2114 return;
2115 }
2116 }
John McCallb4190042009-11-04 23:02:40 +00002117 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002118
2119 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2120 if (E->getCastKind() == CK_LValueToRValue)
2121 HandleValue(E->getSubExpr());
2122
2123 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002124 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002125
2126 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2127 Expr *Callee = E->getCallee();
2128 if (isa<MemberExpr>(Callee))
2129 HandleValue(Callee);
2130
2131 Inherited::VisitCXXMemberCallExpr(E);
2132 }
2133 };
2134 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2135 ValueDecl *VD) {
2136 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002137 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002138} // namespace
John McCallb4190042009-11-04 23:02:40 +00002139
John McCallf312b1e2010-08-26 23:41:50 +00002140MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002141Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002142 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002143 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2144 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2145 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002146 "Member must be a FieldDecl or IndirectFieldDecl");
2147
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002148 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002149 return true;
2150
Douglas Gregor464b2f02010-11-05 22:21:31 +00002151 if (Member->isInvalidDecl())
2152 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002153
John McCallb4190042009-11-04 23:02:40 +00002154 // Diagnose value-uses of fields to initialize themselves, e.g.
2155 // foo(foo)
2156 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002157 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002158 Expr **Args;
2159 unsigned NumArgs;
2160 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2161 Args = ParenList->getExprs();
2162 NumArgs = ParenList->getNumExprs();
2163 } else {
2164 InitListExpr *InitList = cast<InitListExpr>(Init);
2165 Args = InitList->getInits();
2166 NumArgs = InitList->getNumInits();
2167 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002168
Richard Trieude5e75c2012-06-14 23:11:34 +00002169 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2170 != DiagnosticsEngine::Ignored)
2171 for (unsigned i = 0; i < NumArgs; ++i)
2172 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002173 // uninitialized. For example, let this field be the i'th field. When
2174 // initializing the i'th field, throw a warning if any of the >= i'th
2175 // fields are used, as they are not yet initialized.
2176 // Right now we are only handling the case where the i'th field uses
2177 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002178 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002179
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002180 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002181
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002183 // Can't check initialization for a member of dependent type or when
2184 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002185 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002186 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002187 bool InitList = false;
2188 if (isa<InitListExpr>(Init)) {
2189 InitList = true;
2190 Args = &Init;
2191 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002192
2193 if (isStdInitializerList(Member->getType(), 0)) {
2194 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2195 << /*at end of ctor*/1 << InitRange;
2196 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002197 }
2198
Chandler Carruth894aed92010-12-06 09:23:57 +00002199 // Initialize the member.
2200 InitializedEntity MemberEntity =
2201 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2202 : InitializedEntity::InitializeMember(IndirectMember, 0);
2203 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002204 InitList ? InitializationKind::CreateDirectList(IdLoc)
2205 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2206 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002207
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002208 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2209 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2210 MultiExprArg(*this, Args, NumArgs),
2211 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002212 if (MemberInit.isInvalid())
2213 return true;
2214
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002215 CheckImplicitConversions(MemberInit.get(),
2216 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002217
2218 // C++0x [class.base.init]p7:
2219 // The initialization of each base and member constitutes a
2220 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002221 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002222 if (MemberInit.isInvalid())
2223 return true;
2224
2225 // If we are in a dependent context, template instantiation will
2226 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002228 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2229 // of the information that we have about the member
2230 // initializer. However, deconstructing the ASTs is a dicey process,
2231 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002232 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002233 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002234 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002235 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002236 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2237 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002238 }
2239
Chandler Carruth894aed92010-12-06 09:23:57 +00002240 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2242 InitRange.getBegin(), Init,
2243 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002244 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002245 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2246 InitRange.getBegin(), Init,
2247 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002248 }
Eli Friedman59c04372009-07-29 19:44:27 +00002249}
2250
John McCallf312b1e2010-08-26 23:41:50 +00002251MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002252Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002253 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002254 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002255 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002256 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002257 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002258 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002259
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002260 bool InitList = true;
2261 Expr **Args = &Init;
2262 unsigned NumArgs = 1;
2263 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2264 InitList = false;
2265 Args = ParenList->getExprs();
2266 NumArgs = ParenList->getNumExprs();
2267 }
2268
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002269 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002270 // Initialize the object.
2271 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2272 QualType(ClassDecl->getTypeForDecl(), 0));
2273 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002274 InitList ? InitializationKind::CreateDirectList(NameLoc)
2275 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2276 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002277 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2278 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2279 MultiExprArg(*this, Args,NumArgs),
2280 0);
Sean Hunt41717662011-02-26 19:13:13 +00002281 if (DelegationInit.isInvalid())
2282 return true;
2283
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002284 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2285 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002286
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002287 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002288
2289 // C++0x [class.base.init]p7:
2290 // The initialization of each base and member constitutes a
2291 // full-expression.
2292 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2293 if (DelegationInit.isInvalid())
2294 return true;
2295
Eli Friedmand21016f2012-05-19 23:35:23 +00002296 // If we are in a dependent context, template instantiation will
2297 // perform this type-checking again. Just save the arguments that we
2298 // received in a ParenListExpr.
2299 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2300 // of the information that we have about the base
2301 // initializer. However, deconstructing the ASTs is a dicey process,
2302 // and this approach is far more likely to get the corner cases right.
2303 if (CurContext->isDependentContext())
2304 DelegationInit = Owned(Init);
2305
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002306 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002307 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002308 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002309}
2310
2311MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002312Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002313 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002314 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002315 SourceLocation BaseLoc
2316 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002317
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002318 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2319 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2320 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2321
2322 // C++ [class.base.init]p2:
2323 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002324 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002325 // of that class, the mem-initializer is ill-formed. A
2326 // mem-initializer-list can initialize a base class using any
2327 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002328 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002329
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002330 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002331 if (EllipsisLoc.isValid()) {
2332 // This is a pack expansion.
2333 if (!BaseType->containsUnexpandedParameterPack()) {
2334 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002335 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002336
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002337 EllipsisLoc = SourceLocation();
2338 }
2339 } else {
2340 // Check for any unexpanded parameter packs.
2341 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2342 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002343
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002344 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002345 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002346 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002347
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002348 // Check for direct and virtual base classes.
2349 const CXXBaseSpecifier *DirectBaseSpec = 0;
2350 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2351 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002352 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2353 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002354 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002355
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002356 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2357 VirtualBaseSpec);
2358
2359 // C++ [base.class.init]p2:
2360 // Unless the mem-initializer-id names a nonstatic data member of the
2361 // constructor's class or a direct or virtual base of that class, the
2362 // mem-initializer is ill-formed.
2363 if (!DirectBaseSpec && !VirtualBaseSpec) {
2364 // If the class has any dependent bases, then it's possible that
2365 // one of those types will resolve to the same type as
2366 // BaseType. Therefore, just treat this as a dependent base
2367 // class initialization. FIXME: Should we try to check the
2368 // initialization anyway? It seems odd.
2369 if (ClassDecl->hasAnyDependentBases())
2370 Dependent = true;
2371 else
2372 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2373 << BaseType << Context.getTypeDeclType(ClassDecl)
2374 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2375 }
2376 }
2377
2378 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002379 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Sebastian Redl6df65482011-09-24 17:48:25 +00002381 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2382 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002383 InitRange.getBegin(), Init,
2384 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002385 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386
2387 // C++ [base.class.init]p2:
2388 // If a mem-initializer-id is ambiguous because it designates both
2389 // a direct non-virtual base class and an inherited virtual base
2390 // class, the mem-initializer is ill-formed.
2391 if (DirectBaseSpec && VirtualBaseSpec)
2392 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002393 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002394
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002395 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002396 if (!BaseSpec)
2397 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2398
2399 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002400 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 Expr **Args = &Init;
2402 unsigned NumArgs = 1;
2403 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002404 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 Args = ParenList->getExprs();
2406 NumArgs = ParenList->getNumExprs();
2407 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002408
2409 InitializedEntity BaseEntity =
2410 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2411 InitializationKind Kind =
2412 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2413 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2414 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002415 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2416 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2417 MultiExprArg(*this, Args, NumArgs),
2418 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002419 if (BaseInit.isInvalid())
2420 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002421
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002423
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002424 // C++0x [class.base.init]p7:
2425 // The initialization of each base and member constitutes a
2426 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002427 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002428 if (BaseInit.isInvalid())
2429 return true;
2430
2431 // If we are in a dependent context, template instantiation will
2432 // perform this type-checking again. Just save the arguments that we
2433 // received in a ParenListExpr.
2434 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2435 // of the information that we have about the base
2436 // initializer. However, deconstructing the ASTs is a dicey process,
2437 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002438 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002439 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002440
Sean Huntcbb67482011-01-08 20:30:50 +00002441 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002442 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002443 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002444 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002446}
2447
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002448// Create a static_cast\<T&&>(expr).
2449static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2450 QualType ExprType = E->getType();
2451 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2452 SourceLocation ExprLoc = E->getLocStart();
2453 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2454 TargetType, ExprLoc);
2455
2456 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2457 SourceRange(ExprLoc, ExprLoc),
2458 E->getSourceRange()).take();
2459}
2460
Anders Carlssone5ef7402010-04-23 03:10:23 +00002461/// ImplicitInitializerKind - How an implicit base or member initializer should
2462/// initialize its base or member.
2463enum ImplicitInitializerKind {
2464 IIK_Default,
2465 IIK_Copy,
2466 IIK_Move
2467};
2468
Anders Carlssondefefd22010-04-23 02:00:02 +00002469static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002470BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002471 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002472 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002473 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002474 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002475 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002476 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2477 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002478
John McCall60d7b3a2010-08-24 06:29:42 +00002479 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002480
2481 switch (ImplicitInitKind) {
2482 case IIK_Default: {
2483 InitializationKind InitKind
2484 = InitializationKind::CreateDefault(Constructor->getLocation());
2485 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2486 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002487 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002488 break;
2489 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002490
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002491 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002492 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002494 ParmVarDecl *Param = Constructor->getParamDecl(0);
2495 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002496
Anders Carlssone5ef7402010-04-23 03:10:23 +00002497 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002498 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002499 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002500 Constructor->getLocation(), ParamType,
2501 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002502
Eli Friedman5f2987c2012-02-02 03:46:19 +00002503 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2504
Anders Carlssonc7957502010-04-24 22:02:54 +00002505 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002506 QualType ArgTy =
2507 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2508 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002509
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002510 if (Moving) {
2511 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2512 }
2513
John McCallf871d0c2010-08-07 06:22:56 +00002514 CXXCastPath BasePath;
2515 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002516 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2517 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002518 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002519 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002520
Anders Carlssone5ef7402010-04-23 03:10:23 +00002521 InitializationKind InitKind
2522 = InitializationKind::CreateDirect(Constructor->getLocation(),
2523 SourceLocation(), SourceLocation());
2524 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2525 &CopyCtorArg, 1);
2526 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002527 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002528 break;
2529 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002530 }
John McCall9ae2f072010-08-23 23:25:46 +00002531
Douglas Gregor53c374f2010-12-07 00:41:46 +00002532 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002533 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002534 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002535
Anders Carlssondefefd22010-04-23 02:00:02 +00002536 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002537 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002538 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2539 SourceLocation()),
2540 BaseSpec->isVirtual(),
2541 SourceLocation(),
2542 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002543 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002544 SourceLocation());
2545
Anders Carlssondefefd22010-04-23 02:00:02 +00002546 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002547}
2548
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002549static bool RefersToRValueRef(Expr *MemRef) {
2550 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2551 return Referenced->getType()->isRValueReferenceType();
2552}
2553
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002554static bool
2555BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002556 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002557 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002558 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002559 if (Field->isInvalidDecl())
2560 return true;
2561
Chandler Carruthf186b542010-06-29 23:50:44 +00002562 SourceLocation Loc = Constructor->getLocation();
2563
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002564 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2565 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002566 ParmVarDecl *Param = Constructor->getParamDecl(0);
2567 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002568
2569 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002570 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2571 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002572
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002573 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002574 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002575 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002576 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002577
Eli Friedman5f2987c2012-02-02 03:46:19 +00002578 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2579
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002580 if (Moving) {
2581 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2582 }
2583
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002584 // Build a reference to this field within the parameter.
2585 CXXScopeSpec SS;
2586 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2587 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002588 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2589 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002591 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002592 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002593 ParamType, Loc,
2594 /*IsArrow=*/false,
2595 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002596 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002597 /*FirstQualifierInScope=*/0,
2598 MemberLookup,
2599 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002600 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002601 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002602
2603 // C++11 [class.copy]p15:
2604 // - if a member m has rvalue reference type T&&, it is direct-initialized
2605 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002606 if (RefersToRValueRef(CtorArg.get())) {
2607 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002608 }
2609
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610 // When the field we are copying is an array, create index variables for
2611 // each dimension of the array. We use these index variables to subscript
2612 // the source array, and other clients (e.g., CodeGen) will perform the
2613 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002614 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002615 QualType BaseType = Field->getType();
2616 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002617 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002618 while (const ConstantArrayType *Array
2619 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002620 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002621 // Create the iteration variable for this array index.
2622 IdentifierInfo *IterationVarName = 0;
2623 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002624 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002625 llvm::raw_svector_ostream OS(Str);
2626 OS << "__i" << IndexVariables.size();
2627 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2628 }
2629 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002630 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631 IterationVarName, SizeType,
2632 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002633 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002634 IndexVariables.push_back(IterationVar);
2635
2636 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002637 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002638 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002639 assert(!IterationVarRef.isInvalid() &&
2640 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002641 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2642 assert(!IterationVarRef.isInvalid() &&
2643 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002644
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002645 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002646 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002647 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002648 Loc);
2649 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002650 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002652 BaseType = Array->getElementType();
2653 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002654
2655 // The array subscript expression is an lvalue, which is wrong for moving.
2656 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002657 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002658
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002659 // Construct the entity that we will be initializing. For an array, this
2660 // will be first element in the array, which may require several levels
2661 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002662 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002663 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002664 if (Indirect)
2665 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2666 else
2667 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002668 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2669 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2670 0,
2671 Entities.back()));
2672
2673 // Direct-initialize to use the copy constructor.
2674 InitializationKind InitKind =
2675 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2676
Sebastian Redl74e611a2011-09-04 18:14:28 +00002677 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002678 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002679 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002680
John McCall60d7b3a2010-08-24 06:29:42 +00002681 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002682 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002683 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002684 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002685 if (MemberInit.isInvalid())
2686 return true;
2687
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002688 if (Indirect) {
2689 assert(IndexVariables.size() == 0 &&
2690 "Indirect field improperly initialized");
2691 CXXMemberInit
2692 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2693 Loc, Loc,
2694 MemberInit.takeAs<Expr>(),
2695 Loc);
2696 } else
2697 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2698 Loc, MemberInit.takeAs<Expr>(),
2699 Loc,
2700 IndexVariables.data(),
2701 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002702 return false;
2703 }
2704
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002705 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2706
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002707 QualType FieldBaseElementType =
2708 SemaRef.Context.getBaseElementType(Field->getType());
2709
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002710 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002711 InitializedEntity InitEntity
2712 = Indirect? InitializedEntity::InitializeMember(Indirect)
2713 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002714 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002715 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002716
2717 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002718 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002719 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002720
Douglas Gregor53c374f2010-12-07 00:41:46 +00002721 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002722 if (MemberInit.isInvalid())
2723 return true;
2724
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002725 if (Indirect)
2726 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2727 Indirect, Loc,
2728 Loc,
2729 MemberInit.get(),
2730 Loc);
2731 else
2732 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2733 Field, Loc, Loc,
2734 MemberInit.get(),
2735 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002736 return false;
2737 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002738
Sean Hunt1f2f3842011-05-17 00:19:05 +00002739 if (!Field->getParent()->isUnion()) {
2740 if (FieldBaseElementType->isReferenceType()) {
2741 SemaRef.Diag(Constructor->getLocation(),
2742 diag::err_uninitialized_member_in_ctor)
2743 << (int)Constructor->isImplicit()
2744 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2745 << 0 << Field->getDeclName();
2746 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2747 return true;
2748 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002749
Sean Hunt1f2f3842011-05-17 00:19:05 +00002750 if (FieldBaseElementType.isConstQualified()) {
2751 SemaRef.Diag(Constructor->getLocation(),
2752 diag::err_uninitialized_member_in_ctor)
2753 << (int)Constructor->isImplicit()
2754 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2755 << 1 << Field->getDeclName();
2756 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2757 return true;
2758 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002759 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002760
David Blaikie4e4d0842012-03-11 07:00:24 +00002761 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002762 FieldBaseElementType->isObjCRetainableType() &&
2763 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2764 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002765 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002766 // Default-initialize Objective-C pointers to NULL.
2767 CXXMemberInit
2768 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2769 Loc, Loc,
2770 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2771 Loc);
2772 return false;
2773 }
2774
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002775 // Nothing to initialize.
2776 CXXMemberInit = 0;
2777 return false;
2778}
John McCallf1860e52010-05-20 23:23:51 +00002779
2780namespace {
2781struct BaseAndFieldInfo {
2782 Sema &S;
2783 CXXConstructorDecl *Ctor;
2784 bool AnyErrorsInInits;
2785 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002786 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002787 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002788
2789 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2790 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002791 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2792 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002793 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002794 else if (Generated && Ctor->isMoveConstructor())
2795 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002796 else
2797 IIK = IIK_Default;
2798 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002799
2800 bool isImplicitCopyOrMove() const {
2801 switch (IIK) {
2802 case IIK_Copy:
2803 case IIK_Move:
2804 return true;
2805
2806 case IIK_Default:
2807 return false;
2808 }
David Blaikie30263482012-01-20 21:50:17 +00002809
2810 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002811 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002812
2813 bool addFieldInitializer(CXXCtorInitializer *Init) {
2814 AllToInit.push_back(Init);
2815
2816 // Check whether this initializer makes the field "used".
2817 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2818 S.UnusedPrivateFields.remove(Init->getAnyMember());
2819
2820 return false;
2821 }
John McCallf1860e52010-05-20 23:23:51 +00002822};
2823}
2824
Richard Smitha4950662011-09-19 13:34:43 +00002825/// \brief Determine whether the given indirect field declaration is somewhere
2826/// within an anonymous union.
2827static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2828 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2829 CEnd = F->chain_end();
2830 C != CEnd; ++C)
2831 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2832 if (Record->isUnion())
2833 return true;
2834
2835 return false;
2836}
2837
Douglas Gregorddb21472011-11-02 23:04:16 +00002838/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2839/// array type.
2840static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2841 if (T->isIncompleteArrayType())
2842 return true;
2843
2844 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2845 if (!ArrayT->getSize())
2846 return true;
2847
2848 T = ArrayT->getElementType();
2849 }
2850
2851 return false;
2852}
2853
Richard Smith7a614d82011-06-11 17:19:42 +00002854static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002855 FieldDecl *Field,
2856 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002857
Chandler Carruthe861c602010-06-30 02:59:29 +00002858 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002859 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2860 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002861
Richard Smith0b8220a2012-08-07 21:30:42 +00002862 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002863 // has a brace-or-equal-initializer, the entity is initialized as specified
2864 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002865 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002866 CXXCtorInitializer *Init;
2867 if (Indirect)
2868 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2869 SourceLocation(),
2870 SourceLocation(), 0,
2871 SourceLocation());
2872 else
2873 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2874 SourceLocation(),
2875 SourceLocation(), 0,
2876 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002877 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002878 }
2879
Richard Smithc115f632011-09-18 11:14:50 +00002880 // Don't build an implicit initializer for union members if none was
2881 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002882 if (Field->getParent()->isUnion() ||
2883 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002884 return false;
2885
Douglas Gregorddb21472011-11-02 23:04:16 +00002886 // Don't initialize incomplete or zero-length arrays.
2887 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2888 return false;
2889
John McCallf1860e52010-05-20 23:23:51 +00002890 // Don't try to build an implicit initializer if there were semantic
2891 // errors in any of the initializers (and therefore we might be
2892 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002893 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002894 return false;
2895
Sean Huntcbb67482011-01-08 20:30:50 +00002896 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002897 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2898 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002899 return true;
John McCallf1860e52010-05-20 23:23:51 +00002900
Richard Smith0b8220a2012-08-07 21:30:42 +00002901 if (!Init)
2902 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002903
Richard Smith0b8220a2012-08-07 21:30:42 +00002904 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002905}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002906
2907bool
2908Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2909 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002910 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002911 Constructor->setNumCtorInitializers(1);
2912 CXXCtorInitializer **initializer =
2913 new (Context) CXXCtorInitializer*[1];
2914 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2915 Constructor->setCtorInitializers(initializer);
2916
Sean Huntb76af9c2011-05-03 23:05:34 +00002917 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002918 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002919 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2920 }
2921
Sean Huntc1598702011-05-05 00:05:47 +00002922 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002923
Sean Hunt059ce0d2011-05-01 07:04:31 +00002924 return false;
2925}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002926
John McCallb77115d2011-06-17 00:18:42 +00002927bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2928 CXXCtorInitializer **Initializers,
2929 unsigned NumInitializers,
2930 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002931 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002932 // Just store the initializers as written, they will be checked during
2933 // instantiation.
2934 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002935 Constructor->setNumCtorInitializers(NumInitializers);
2936 CXXCtorInitializer **baseOrMemberInitializers =
2937 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002938 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002939 NumInitializers * sizeof(CXXCtorInitializer*));
2940 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002941 }
2942
2943 return false;
2944 }
2945
John McCallf1860e52010-05-20 23:23:51 +00002946 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002947
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002948 // We need to build the initializer AST according to order of construction
2949 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002950 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002951 if (!ClassDecl)
2952 return true;
2953
Eli Friedman80c30da2009-11-09 19:20:36 +00002954 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002956 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002957 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002958
2959 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002960 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002961 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002962 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002963 }
2964
Anders Carlsson711f34a2010-04-21 19:52:01 +00002965 // Keep track of the direct virtual bases.
2966 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2967 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2968 E = ClassDecl->bases_end(); I != E; ++I) {
2969 if (I->isVirtual())
2970 DirectVBases.insert(I);
2971 }
2972
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002973 // Push virtual bases before others.
2974 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2975 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2976
Sean Huntcbb67482011-01-08 20:30:50 +00002977 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002978 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2979 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002980 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002981 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002982 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002983 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002984 VBase, IsInheritedVirtualBase,
2985 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002986 HadError = true;
2987 continue;
2988 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002989
John McCallf1860e52010-05-20 23:23:51 +00002990 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002991 }
2992 }
Mike Stump1eb44332009-09-09 15:08:12 +00002993
John McCallf1860e52010-05-20 23:23:51 +00002994 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002995 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2996 E = ClassDecl->bases_end(); Base != E; ++Base) {
2997 // Virtuals are in the virtual base list and already constructed.
2998 if (Base->isVirtual())
2999 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Sean Huntcbb67482011-01-08 20:30:50 +00003001 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003002 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3003 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003004 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003005 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003006 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003007 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003008 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003009 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003010 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003011 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003012
John McCallf1860e52010-05-20 23:23:51 +00003013 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003014 }
3015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
John McCallf1860e52010-05-20 23:23:51 +00003017 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003018 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3019 MemEnd = ClassDecl->decls_end();
3020 Mem != MemEnd; ++Mem) {
3021 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003022 // C++ [class.bit]p2:
3023 // A declaration for a bit-field that omits the identifier declares an
3024 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3025 // initialized.
3026 if (F->isUnnamedBitfield())
3027 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003028
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003029 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003030 // handle anonymous struct/union fields based on their individual
3031 // indirect fields.
3032 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3033 continue;
3034
3035 if (CollectFieldInitializer(*this, Info, F))
3036 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003037 continue;
3038 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003039
3040 // Beyond this point, we only consider default initialization.
3041 if (Info.IIK != IIK_Default)
3042 continue;
3043
3044 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3045 if (F->getType()->isIncompleteArrayType()) {
3046 assert(ClassDecl->hasFlexibleArrayMember() &&
3047 "Incomplete array type is not valid");
3048 continue;
3049 }
3050
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003051 // Initialize each field of an anonymous struct individually.
3052 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3053 HadError = true;
3054
3055 continue;
3056 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003057 }
Mike Stump1eb44332009-09-09 15:08:12 +00003058
John McCallf1860e52010-05-20 23:23:51 +00003059 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003060 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003061 Constructor->setNumCtorInitializers(NumInitializers);
3062 CXXCtorInitializer **baseOrMemberInitializers =
3063 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003064 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003065 NumInitializers * sizeof(CXXCtorInitializer*));
3066 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003067
John McCallef027fe2010-03-16 21:39:52 +00003068 // Constructors implicitly reference the base and member
3069 // destructors.
3070 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3071 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003072 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003073
3074 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003075}
3076
Eli Friedman6347f422009-07-21 19:28:10 +00003077static void *GetKeyForTopLevelField(FieldDecl *Field) {
3078 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003079 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003080 if (RT->getDecl()->isAnonymousStructOrUnion())
3081 return static_cast<void *>(RT->getDecl());
3082 }
3083 return static_cast<void *>(Field);
3084}
3085
Anders Carlssonea356fb2010-04-02 05:42:15 +00003086static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003087 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003088}
3089
Anders Carlssonea356fb2010-04-02 05:42:15 +00003090static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003091 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003092 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003093 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003094
Eli Friedman6347f422009-07-21 19:28:10 +00003095 // For fields injected into the class via declaration of an anonymous union,
3096 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003097 FieldDecl *Field = Member->getAnyMember();
3098
John McCall3c3ccdb2010-04-10 09:28:51 +00003099 // If the field is a member of an anonymous struct or union, our key
3100 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003101 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003102 if (RD->isAnonymousStructOrUnion()) {
3103 while (true) {
3104 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3105 if (Parent->isAnonymousStructOrUnion())
3106 RD = Parent;
3107 else
3108 break;
3109 }
3110
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003111 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003112 }
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003114 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003115}
3116
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003117static void
3118DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003119 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003120 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003121 unsigned NumInits) {
3122 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003123 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003125 // Don't check initializers order unless the warning is enabled at the
3126 // location of at least one initializer.
3127 bool ShouldCheckOrder = false;
3128 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003129 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003130 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3131 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003132 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003133 ShouldCheckOrder = true;
3134 break;
3135 }
3136 }
3137 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003138 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003139
John McCalld6ca8da2010-04-10 07:37:23 +00003140 // Build the list of bases and members in the order that they'll
3141 // actually be initialized. The explicit initializers should be in
3142 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003143 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Anders Carlsson071d6102010-04-02 03:38:04 +00003145 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3146
John McCalld6ca8da2010-04-10 07:37:23 +00003147 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003148 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003149 ClassDecl->vbases_begin(),
3150 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003151 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003152
John McCalld6ca8da2010-04-10 07:37:23 +00003153 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003154 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003155 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003156 if (Base->isVirtual())
3157 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003158 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003159 }
Mike Stump1eb44332009-09-09 15:08:12 +00003160
John McCalld6ca8da2010-04-10 07:37:23 +00003161 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003162 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003163 E = ClassDecl->field_end(); Field != E; ++Field) {
3164 if (Field->isUnnamedBitfield())
3165 continue;
3166
David Blaikie581deb32012-06-06 20:45:41 +00003167 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003168 }
3169
John McCalld6ca8da2010-04-10 07:37:23 +00003170 unsigned NumIdealInits = IdealInitKeys.size();
3171 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003172
Sean Huntcbb67482011-01-08 20:30:50 +00003173 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003174 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003175 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003176 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003177
3178 // Scan forward to try to find this initializer in the idealized
3179 // initializers list.
3180 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3181 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003182 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003183
3184 // If we didn't find this initializer, it must be because we
3185 // scanned past it on a previous iteration. That can only
3186 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003187 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003188 Sema::SemaDiagnosticBuilder D =
3189 SemaRef.Diag(PrevInit->getSourceLocation(),
3190 diag::warn_initializer_out_of_order);
3191
Francois Pichet00eb3f92010-12-04 09:14:42 +00003192 if (PrevInit->isAnyMemberInitializer())
3193 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003194 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003195 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003196
Francois Pichet00eb3f92010-12-04 09:14:42 +00003197 if (Init->isAnyMemberInitializer())
3198 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003199 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003200 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003201
3202 // Move back to the initializer's location in the ideal list.
3203 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3204 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003205 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003206
3207 assert(IdealIndex != NumIdealInits &&
3208 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003209 }
John McCalld6ca8da2010-04-10 07:37:23 +00003210
3211 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003212 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003213}
3214
John McCall3c3ccdb2010-04-10 09:28:51 +00003215namespace {
3216bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003217 CXXCtorInitializer *Init,
3218 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003219 if (!PrevInit) {
3220 PrevInit = Init;
3221 return false;
3222 }
3223
3224 if (FieldDecl *Field = Init->getMember())
3225 S.Diag(Init->getSourceLocation(),
3226 diag::err_multiple_mem_initialization)
3227 << Field->getDeclName()
3228 << Init->getSourceRange();
3229 else {
John McCallf4c73712011-01-19 06:33:43 +00003230 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003231 assert(BaseClass && "neither field nor base");
3232 S.Diag(Init->getSourceLocation(),
3233 diag::err_multiple_base_initialization)
3234 << QualType(BaseClass, 0)
3235 << Init->getSourceRange();
3236 }
3237 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3238 << 0 << PrevInit->getSourceRange();
3239
3240 return true;
3241}
3242
Sean Huntcbb67482011-01-08 20:30:50 +00003243typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003244typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3245
3246bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003247 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003248 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003249 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003250 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003251 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003252
3253 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003254 if (Parent->isUnion()) {
3255 UnionEntry &En = Unions[Parent];
3256 if (En.first && En.first != Child) {
3257 S.Diag(Init->getSourceLocation(),
3258 diag::err_multiple_mem_union_initialization)
3259 << Field->getDeclName()
3260 << Init->getSourceRange();
3261 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3262 << 0 << En.second->getSourceRange();
3263 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003264 }
3265 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003266 En.first = Child;
3267 En.second = Init;
3268 }
David Blaikie6fe29652011-11-17 06:01:57 +00003269 if (!Parent->isAnonymousStructOrUnion())
3270 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003271 }
3272
3273 Child = Parent;
3274 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003275 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003276
3277 return false;
3278}
3279}
3280
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003281/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003282void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003283 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003284 CXXCtorInitializer **meminits,
3285 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003286 bool AnyErrors) {
3287 if (!ConstructorDecl)
3288 return;
3289
3290 AdjustDeclIfTemplate(ConstructorDecl);
3291
3292 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003293 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003294
3295 if (!Constructor) {
3296 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3297 return;
3298 }
3299
Sean Huntcbb67482011-01-08 20:30:50 +00003300 CXXCtorInitializer **MemInits =
3301 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003302
3303 // Mapping for the duplicate initializers check.
3304 // For member initializers, this is keyed with a FieldDecl*.
3305 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003306 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003307
3308 // Mapping for the inconsistent anonymous-union initializers check.
3309 RedundantUnionMap MemberUnions;
3310
Anders Carlssonea356fb2010-04-02 05:42:15 +00003311 bool HadError = false;
3312 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003313 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003314
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003315 // Set the source order index.
3316 Init->setSourceOrder(i);
3317
Francois Pichet00eb3f92010-12-04 09:14:42 +00003318 if (Init->isAnyMemberInitializer()) {
3319 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003320 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3321 CheckRedundantUnionInit(*this, Init, MemberUnions))
3322 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003323 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003324 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3325 if (CheckRedundantInit(*this, Init, Members[Key]))
3326 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003327 } else {
3328 assert(Init->isDelegatingInitializer());
3329 // This must be the only initializer
3330 if (i != 0 || NumMemInits > 1) {
3331 Diag(MemInits[0]->getSourceLocation(),
3332 diag::err_delegating_initializer_alone)
3333 << MemInits[0]->getSourceRange();
3334 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003335 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003336 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003337 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003338 // Return immediately as the initializer is set.
3339 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003340 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003341 }
3342
Anders Carlssonea356fb2010-04-02 05:42:15 +00003343 if (HadError)
3344 return;
3345
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003346 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003347
Sean Huntcbb67482011-01-08 20:30:50 +00003348 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003349}
3350
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003351void
John McCallef027fe2010-03-16 21:39:52 +00003352Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3353 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003354 // Ignore dependent contexts. Also ignore unions, since their members never
3355 // have destructors implicitly called.
3356 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003357 return;
John McCall58e6f342010-03-16 05:22:47 +00003358
3359 // FIXME: all the access-control diagnostics are positioned on the
3360 // field/base declaration. That's probably good; that said, the
3361 // user might reasonably want to know why the destructor is being
3362 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003363
Anders Carlsson9f853df2009-11-17 04:44:12 +00003364 // Non-static data members.
3365 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3366 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003367 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003368 if (Field->isInvalidDecl())
3369 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003370
3371 // Don't destroy incomplete or zero-length arrays.
3372 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3373 continue;
3374
Anders Carlsson9f853df2009-11-17 04:44:12 +00003375 QualType FieldType = Context.getBaseElementType(Field->getType());
3376
3377 const RecordType* RT = FieldType->getAs<RecordType>();
3378 if (!RT)
3379 continue;
3380
3381 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003382 if (FieldClassDecl->isInvalidDecl())
3383 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003384 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003385 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003386 // The destructor for an implicit anonymous union member is never invoked.
3387 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3388 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003389
Douglas Gregordb89f282010-07-01 22:47:18 +00003390 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003391 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003392 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003393 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003394 << Field->getDeclName()
3395 << FieldType);
3396
Eli Friedman5f2987c2012-02-02 03:46:19 +00003397 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003398 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003399 }
3400
John McCall58e6f342010-03-16 05:22:47 +00003401 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3402
Anders Carlsson9f853df2009-11-17 04:44:12 +00003403 // Bases.
3404 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3405 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003406 // Bases are always records in a well-formed non-dependent class.
3407 const RecordType *RT = Base->getType()->getAs<RecordType>();
3408
3409 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003410 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003411 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003412
John McCall58e6f342010-03-16 05:22:47 +00003413 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003414 // If our base class is invalid, we probably can't get its dtor anyway.
3415 if (BaseClassDecl->isInvalidDecl())
3416 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003417 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003418 continue;
John McCall58e6f342010-03-16 05:22:47 +00003419
Douglas Gregordb89f282010-07-01 22:47:18 +00003420 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003421 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003422
3423 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003424 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003425 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003426 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003427 << Base->getSourceRange(),
3428 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003429
Eli Friedman5f2987c2012-02-02 03:46:19 +00003430 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003431 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003432 }
3433
3434 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003435 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3436 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003437
3438 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003439 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003440
3441 // Ignore direct virtual bases.
3442 if (DirectVirtualBases.count(RT))
3443 continue;
3444
John McCall58e6f342010-03-16 05:22:47 +00003445 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003446 // If our base class is invalid, we probably can't get its dtor anyway.
3447 if (BaseClassDecl->isInvalidDecl())
3448 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003449 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003450 continue;
John McCall58e6f342010-03-16 05:22:47 +00003451
Douglas Gregordb89f282010-07-01 22:47:18 +00003452 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003453 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003454 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003455 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003456 << VBase->getType(),
3457 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003458
Eli Friedman5f2987c2012-02-02 03:46:19 +00003459 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003460 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003461 }
3462}
3463
John McCalld226f652010-08-21 09:40:31 +00003464void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003465 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003466 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Mike Stump1eb44332009-09-09 15:08:12 +00003468 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003469 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003470 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003471}
3472
Mike Stump1eb44332009-09-09 15:08:12 +00003473bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003474 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003475 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3476 unsigned DiagID;
3477 AbstractDiagSelID SelID;
3478
3479 public:
3480 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3481 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3482
3483 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003484 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003485 if (SelID == -1)
3486 S.Diag(Loc, DiagID) << T;
3487 else
3488 S.Diag(Loc, DiagID) << SelID << T;
3489 }
3490 } Diagnoser(DiagID, SelID);
3491
3492 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003493}
3494
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003495bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003496 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003497 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003498 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Anders Carlsson11f21a02009-03-23 19:10:31 +00003500 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003501 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Ted Kremenek6217b802009-07-29 21:53:49 +00003503 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003504 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003505 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003506 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003508 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003509 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003510 }
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Ted Kremenek6217b802009-07-29 21:53:49 +00003512 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003513 if (!RT)
3514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003515
John McCall86ff3082010-02-04 22:26:26 +00003516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003517
John McCall94c3b562010-08-18 09:41:07 +00003518 // We can't answer whether something is abstract until it has a
3519 // definition. If it's currently being defined, we'll walk back
3520 // over all the declarations when we have a full definition.
3521 const CXXRecordDecl *Def = RD->getDefinition();
3522 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003523 return false;
3524
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003525 if (!RD->isAbstract())
3526 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003528 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003529 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003530
John McCall94c3b562010-08-18 09:41:07 +00003531 return true;
3532}
3533
3534void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3535 // Check if we've already emitted the list of pure virtual functions
3536 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003537 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003538 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003540 CXXFinalOverriderMap FinalOverriders;
3541 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003543 // Keep a set of seen pure methods so we won't diagnose the same method
3544 // more than once.
3545 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3546
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003547 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3548 MEnd = FinalOverriders.end();
3549 M != MEnd;
3550 ++M) {
3551 for (OverridingMethods::iterator SO = M->second.begin(),
3552 SOEnd = M->second.end();
3553 SO != SOEnd; ++SO) {
3554 // C++ [class.abstract]p4:
3555 // A class is abstract if it contains or inherits at least one
3556 // pure virtual function for which the final overrider is pure
3557 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003559 //
3560 if (SO->second.size() != 1)
3561 continue;
3562
3563 if (!SO->second.front().Method->isPure())
3564 continue;
3565
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003566 if (!SeenPureMethods.insert(SO->second.front().Method))
3567 continue;
3568
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003569 Diag(SO->second.front().Method->getLocation(),
3570 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003571 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003572 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003573 }
3574
3575 if (!PureVirtualClassDiagSet)
3576 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3577 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003578}
3579
Anders Carlsson8211eff2009-03-24 01:19:16 +00003580namespace {
John McCall94c3b562010-08-18 09:41:07 +00003581struct AbstractUsageInfo {
3582 Sema &S;
3583 CXXRecordDecl *Record;
3584 CanQualType AbstractType;
3585 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003586
John McCall94c3b562010-08-18 09:41:07 +00003587 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3588 : S(S), Record(Record),
3589 AbstractType(S.Context.getCanonicalType(
3590 S.Context.getTypeDeclType(Record))),
3591 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003592
John McCall94c3b562010-08-18 09:41:07 +00003593 void DiagnoseAbstractType() {
3594 if (Invalid) return;
3595 S.DiagnoseAbstractType(Record);
3596 Invalid = true;
3597 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003598
John McCall94c3b562010-08-18 09:41:07 +00003599 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3600};
3601
3602struct CheckAbstractUsage {
3603 AbstractUsageInfo &Info;
3604 const NamedDecl *Ctx;
3605
3606 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3607 : Info(Info), Ctx(Ctx) {}
3608
3609 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3610 switch (TL.getTypeLocClass()) {
3611#define ABSTRACT_TYPELOC(CLASS, PARENT)
3612#define TYPELOC(CLASS, PARENT) \
3613 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3614#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003615 }
John McCall94c3b562010-08-18 09:41:07 +00003616 }
Mike Stump1eb44332009-09-09 15:08:12 +00003617
John McCall94c3b562010-08-18 09:41:07 +00003618 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3619 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3620 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003621 if (!TL.getArg(I))
3622 continue;
3623
John McCall94c3b562010-08-18 09:41:07 +00003624 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3625 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003626 }
John McCall94c3b562010-08-18 09:41:07 +00003627 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003628
John McCall94c3b562010-08-18 09:41:07 +00003629 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3630 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
John McCall94c3b562010-08-18 09:41:07 +00003633 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3634 // Visit the type parameters from a permissive context.
3635 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3636 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3637 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3638 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3639 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3640 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003641 }
John McCall94c3b562010-08-18 09:41:07 +00003642 }
Mike Stump1eb44332009-09-09 15:08:12 +00003643
John McCall94c3b562010-08-18 09:41:07 +00003644 // Visit pointee types from a permissive context.
3645#define CheckPolymorphic(Type) \
3646 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3647 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3648 }
3649 CheckPolymorphic(PointerTypeLoc)
3650 CheckPolymorphic(ReferenceTypeLoc)
3651 CheckPolymorphic(MemberPointerTypeLoc)
3652 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003653 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003654
John McCall94c3b562010-08-18 09:41:07 +00003655 /// Handle all the types we haven't given a more specific
3656 /// implementation for above.
3657 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3658 // Every other kind of type that we haven't called out already
3659 // that has an inner type is either (1) sugar or (2) contains that
3660 // inner type in some way as a subobject.
3661 if (TypeLoc Next = TL.getNextTypeLoc())
3662 return Visit(Next, Sel);
3663
3664 // If there's no inner type and we're in a permissive context,
3665 // don't diagnose.
3666 if (Sel == Sema::AbstractNone) return;
3667
3668 // Check whether the type matches the abstract type.
3669 QualType T = TL.getType();
3670 if (T->isArrayType()) {
3671 Sel = Sema::AbstractArrayType;
3672 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003673 }
John McCall94c3b562010-08-18 09:41:07 +00003674 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3675 if (CT != Info.AbstractType) return;
3676
3677 // It matched; do some magic.
3678 if (Sel == Sema::AbstractArrayType) {
3679 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3680 << T << TL.getSourceRange();
3681 } else {
3682 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3683 << Sel << T << TL.getSourceRange();
3684 }
3685 Info.DiagnoseAbstractType();
3686 }
3687};
3688
3689void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3690 Sema::AbstractDiagSelID Sel) {
3691 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3692}
3693
3694}
3695
3696/// Check for invalid uses of an abstract type in a method declaration.
3697static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3698 CXXMethodDecl *MD) {
3699 // No need to do the check on definitions, which require that
3700 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003701 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003702 return;
3703
3704 // For safety's sake, just ignore it if we don't have type source
3705 // information. This should never happen for non-implicit methods,
3706 // but...
3707 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3708 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3709}
3710
3711/// Check for invalid uses of an abstract type within a class definition.
3712static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3713 CXXRecordDecl *RD) {
3714 for (CXXRecordDecl::decl_iterator
3715 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3716 Decl *D = *I;
3717 if (D->isImplicit()) continue;
3718
3719 // Methods and method templates.
3720 if (isa<CXXMethodDecl>(D)) {
3721 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3722 } else if (isa<FunctionTemplateDecl>(D)) {
3723 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3724 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3725
3726 // Fields and static variables.
3727 } else if (isa<FieldDecl>(D)) {
3728 FieldDecl *FD = cast<FieldDecl>(D);
3729 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3730 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3731 } else if (isa<VarDecl>(D)) {
3732 VarDecl *VD = cast<VarDecl>(D);
3733 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3734 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3735
3736 // Nested classes and class templates.
3737 } else if (isa<CXXRecordDecl>(D)) {
3738 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3739 } else if (isa<ClassTemplateDecl>(D)) {
3740 CheckAbstractClassUsage(Info,
3741 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3742 }
3743 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003744}
3745
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003746/// \brief Perform semantic checks on a class definition that has been
3747/// completing, introducing implicitly-declared members, checking for
3748/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003749void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003750 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003751 return;
3752
John McCall94c3b562010-08-18 09:41:07 +00003753 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3754 AbstractUsageInfo Info(*this, Record);
3755 CheckAbstractClassUsage(Info, Record);
3756 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003757
3758 // If this is not an aggregate type and has no user-declared constructor,
3759 // complain about any non-static data members of reference or const scalar
3760 // type, since they will never get initializers.
3761 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003762 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3763 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003764 bool Complained = false;
3765 for (RecordDecl::field_iterator F = Record->field_begin(),
3766 FEnd = Record->field_end();
3767 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003768 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003769 continue;
3770
Douglas Gregor325e5932010-04-15 00:00:53 +00003771 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003772 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003773 if (!Complained) {
3774 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3775 << Record->getTagKind() << Record;
3776 Complained = true;
3777 }
3778
3779 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3780 << F->getType()->isReferenceType()
3781 << F->getDeclName();
3782 }
3783 }
3784 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003785
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003786 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003787 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003788
3789 if (Record->getIdentifier()) {
3790 // C++ [class.mem]p13:
3791 // If T is the name of a class, then each of the following shall have a
3792 // name different from T:
3793 // - every member of every anonymous union that is a member of class T.
3794 //
3795 // C++ [class.mem]p14:
3796 // In addition, if class T has a user-declared constructor (12.1), every
3797 // non-static data member of class T shall have a name different from T.
3798 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003799 R.first != R.second; ++R.first) {
3800 NamedDecl *D = *R.first;
3801 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3802 isa<IndirectFieldDecl>(D)) {
3803 Diag(D->getLocation(), diag::err_member_name_of_class)
3804 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003805 break;
3806 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003807 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003808 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003809
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003810 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003811 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003812 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003813 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003814 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3815 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3816 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003817
3818 // See if a method overloads virtual methods in a base
3819 /// class without overriding any.
3820 if (!Record->isDependentType()) {
3821 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3822 MEnd = Record->method_end();
3823 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003824 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003825 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003826 }
3827 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003828
Richard Smith9f569cc2011-10-01 02:31:28 +00003829 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3830 // function that is not a constructor declares that member function to be
3831 // const. [...] The class of which that function is a member shall be
3832 // a literal type.
3833 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003834 // If the class has virtual bases, any constexpr members will already have
3835 // been diagnosed by the checks performed on the member declaration, so
3836 // suppress this (less useful) diagnostic.
3837 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3838 !Record->isLiteral() && !Record->getNumVBases()) {
3839 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3840 MEnd = Record->method_end();
3841 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003842 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003843 switch (Record->getTemplateSpecializationKind()) {
3844 case TSK_ImplicitInstantiation:
3845 case TSK_ExplicitInstantiationDeclaration:
3846 case TSK_ExplicitInstantiationDefinition:
3847 // If a template instantiates to a non-literal type, but its members
3848 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003849 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003850 continue;
3851
3852 case TSK_Undeclared:
3853 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003854 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003855 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003856 break;
3857 }
3858
3859 // Only produce one error per class.
3860 break;
3861 }
3862 }
3863 }
3864
Sebastian Redlf677ea32011-02-05 19:23:19 +00003865 // Declare inherited constructors. We do this eagerly here because:
3866 // - The standard requires an eager diagnostic for conflicting inherited
3867 // constructors from different classes.
3868 // - The lazy declaration of the other implicit constructors is so as to not
3869 // waste space and performance on classes that are not meant to be
3870 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3871 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003872 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003873}
3874
3875void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003876 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3877 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003878 MI != ME; ++MI)
3879 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003880 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003881}
3882
Richard Smith7756afa2012-06-10 05:43:50 +00003883/// Is the special member function which would be selected to perform the
3884/// specified operation on the specified class type a constexpr constructor?
3885static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3886 Sema::CXXSpecialMember CSM,
3887 bool ConstArg) {
3888 Sema::SpecialMemberOverloadResult *SMOR =
3889 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3890 false, false, false, false);
3891 if (!SMOR || !SMOR->getMethod())
3892 // A constructor we wouldn't select can't be "involved in initializing"
3893 // anything.
3894 return true;
3895 return SMOR->getMethod()->isConstexpr();
3896}
3897
3898/// Determine whether the specified special member function would be constexpr
3899/// if it were implicitly defined.
3900static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3901 Sema::CXXSpecialMember CSM,
3902 bool ConstArg) {
3903 if (!S.getLangOpts().CPlusPlus0x)
3904 return false;
3905
3906 // C++11 [dcl.constexpr]p4:
3907 // In the definition of a constexpr constructor [...]
3908 switch (CSM) {
3909 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003910 // Since default constructor lookup is essentially trivial (and cannot
3911 // involve, for instance, template instantiation), we compute whether a
3912 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3913 //
3914 // This is important for performance; we need to know whether the default
3915 // constructor is constexpr to determine whether the type is a literal type.
3916 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3917
Richard Smith7756afa2012-06-10 05:43:50 +00003918 case Sema::CXXCopyConstructor:
3919 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003920 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003921 break;
3922
3923 case Sema::CXXCopyAssignment:
3924 case Sema::CXXMoveAssignment:
3925 case Sema::CXXDestructor:
3926 case Sema::CXXInvalid:
3927 return false;
3928 }
3929
3930 // -- if the class is a non-empty union, or for each non-empty anonymous
3931 // union member of a non-union class, exactly one non-static data member
3932 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003933 //
3934 // If we squint, this is guaranteed, since exactly one non-static data member
3935 // will be initialized (if the constructor isn't deleted), we just don't know
3936 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003937 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003938 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003939
3940 // -- the class shall not have any virtual base classes;
3941 if (ClassDecl->getNumVBases())
3942 return false;
3943
3944 // -- every constructor involved in initializing [...] base class
3945 // sub-objects shall be a constexpr constructor;
3946 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3947 BEnd = ClassDecl->bases_end();
3948 B != BEnd; ++B) {
3949 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3950 if (!BaseType) continue;
3951
3952 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3953 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3954 return false;
3955 }
3956
3957 // -- every constructor involved in initializing non-static data members
3958 // [...] shall be a constexpr constructor;
3959 // -- every non-static data member and base class sub-object shall be
3960 // initialized
3961 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3962 FEnd = ClassDecl->field_end();
3963 F != FEnd; ++F) {
3964 if (F->isInvalidDecl())
3965 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003966 if (const RecordType *RecordTy =
3967 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003968 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3969 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3970 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003971 }
3972 }
3973
3974 // All OK, it's constexpr!
3975 return true;
3976}
3977
Richard Smithb9d0b762012-07-27 04:22:15 +00003978static Sema::ImplicitExceptionSpecification
3979computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3980 switch (S.getSpecialMember(MD)) {
3981 case Sema::CXXDefaultConstructor:
3982 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3983 case Sema::CXXCopyConstructor:
3984 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3985 case Sema::CXXCopyAssignment:
3986 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
3987 case Sema::CXXMoveConstructor:
3988 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
3989 case Sema::CXXMoveAssignment:
3990 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
3991 case Sema::CXXDestructor:
3992 return S.ComputeDefaultedDtorExceptionSpec(MD);
3993 case Sema::CXXInvalid:
3994 break;
3995 }
3996 llvm_unreachable("only special members have implicit exception specs");
3997}
3998
Richard Smithdd25e802012-07-30 23:48:14 +00003999static void
4000updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4001 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4002 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4003 ExceptSpec.getEPI(EPI);
4004 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4005 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4006 FPT->getNumArgs(), EPI));
4007 FD->setType(QualType(NewFPT, 0));
4008}
4009
Richard Smithb9d0b762012-07-27 04:22:15 +00004010void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4011 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4012 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4013 return;
4014
Richard Smithdd25e802012-07-30 23:48:14 +00004015 // Evaluate the exception specification.
4016 ImplicitExceptionSpecification ExceptSpec =
4017 computeImplicitExceptionSpec(*this, Loc, MD);
4018
4019 // Update the type of the special member to use it.
4020 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4021
4022 // A user-provided destructor can be defined outside the class. When that
4023 // happens, be sure to update the exception specification on both
4024 // declarations.
4025 const FunctionProtoType *CanonicalFPT =
4026 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4027 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4028 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4029 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004030}
4031
4032static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4033static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4034
Richard Smith3003e1d2012-05-15 04:39:51 +00004035void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4036 CXXRecordDecl *RD = MD->getParent();
4037 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004038
Richard Smith3003e1d2012-05-15 04:39:51 +00004039 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4040 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004041
4042 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004043 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004044 bool First = MD == MD->getCanonicalDecl();
4045
4046 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004047
4048 // C++11 [dcl.fct.def.default]p1:
4049 // A function that is explicitly defaulted shall
4050 // -- be a special member function (checked elsewhere),
4051 // -- have the same type (except for ref-qualifiers, and except that a
4052 // copy operation can take a non-const reference) as an implicit
4053 // declaration, and
4054 // -- not have default arguments.
4055 unsigned ExpectedParams = 1;
4056 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4057 ExpectedParams = 0;
4058 if (MD->getNumParams() != ExpectedParams) {
4059 // This also checks for default arguments: a copy or move constructor with a
4060 // default argument is classified as a default constructor, and assignment
4061 // operations and destructors can't have default arguments.
4062 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4063 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004064 HadError = true;
4065 }
4066
Richard Smith3003e1d2012-05-15 04:39:51 +00004067 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004068
Richard Smithb9d0b762012-07-27 04:22:15 +00004069 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004070 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004071 bool Trivial;
4072 switch (CSM) {
4073 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004074 Trivial = RD->hasTrivialDefaultConstructor();
4075 break;
4076 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004077 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004078 Trivial = RD->hasTrivialCopyConstructor();
4079 break;
4080 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004081 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004082 Trivial = RD->hasTrivialCopyAssignment();
4083 break;
4084 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004085 Trivial = RD->hasTrivialMoveConstructor();
4086 break;
4087 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004088 Trivial = RD->hasTrivialMoveAssignment();
4089 break;
4090 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004091 Trivial = RD->hasTrivialDestructor();
4092 break;
4093 case CXXInvalid:
4094 llvm_unreachable("non-special member explicitly defaulted!");
4095 }
Sean Hunt2b188082011-05-14 05:23:28 +00004096
Richard Smith3003e1d2012-05-15 04:39:51 +00004097 QualType ReturnType = Context.VoidTy;
4098 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4099 // Check for return type matching.
4100 ReturnType = Type->getResultType();
4101 QualType ExpectedReturnType =
4102 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4103 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4104 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4105 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4106 HadError = true;
4107 }
4108
4109 // A defaulted special member cannot have cv-qualifiers.
4110 if (Type->getTypeQuals()) {
4111 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4112 << (CSM == CXXMoveAssignment);
4113 HadError = true;
4114 }
4115 }
4116
4117 // Check for parameter type matching.
4118 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004119 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004120 if (ExpectedParams && ArgType->isReferenceType()) {
4121 // Argument must be reference to possibly-const T.
4122 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004123 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004124
4125 if (ReferentType.isVolatileQualified()) {
4126 Diag(MD->getLocation(),
4127 diag::err_defaulted_special_member_volatile_param) << CSM;
4128 HadError = true;
4129 }
4130
Richard Smith7756afa2012-06-10 05:43:50 +00004131 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004132 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4133 Diag(MD->getLocation(),
4134 diag::err_defaulted_special_member_copy_const_param)
4135 << (CSM == CXXCopyAssignment);
4136 // FIXME: Explain why this special member can't be const.
4137 } else {
4138 Diag(MD->getLocation(),
4139 diag::err_defaulted_special_member_move_const_param)
4140 << (CSM == CXXMoveAssignment);
4141 }
4142 HadError = true;
4143 }
4144
4145 // If a function is explicitly defaulted on its first declaration, it shall
4146 // have the same parameter type as if it had been implicitly declared.
4147 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004148 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004149 Diag(MD->getLocation(),
4150 diag::err_defaulted_special_member_copy_non_const_param)
4151 << (CSM == CXXCopyAssignment);
4152 } else if (ExpectedParams) {
4153 // A copy assignment operator can take its argument by value, but a
4154 // defaulted one cannot.
4155 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004156 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004157 HadError = true;
4158 }
Sean Huntbe631222011-05-17 20:44:43 +00004159
Richard Smithb9d0b762012-07-27 04:22:15 +00004160 // Rebuild the type with the implicit exception specification added, if we
4161 // are going to need it.
4162 const FunctionProtoType *ImplicitType = 0;
4163 if (First || Type->hasExceptionSpec()) {
4164 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4165 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4166 ImplicitType = cast<FunctionProtoType>(
4167 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4168 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004169
Richard Smith61802452011-12-22 02:22:31 +00004170 // C++11 [dcl.fct.def.default]p2:
4171 // An explicitly-defaulted function may be declared constexpr only if it
4172 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004173 // Do not apply this rule to members of class templates, since core issue 1358
4174 // makes such functions always instantiate to constexpr functions. For
4175 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004176 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4177 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004178 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4179 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4180 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004181 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004182 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004183 }
4184 // and may have an explicit exception-specification only if it is compatible
4185 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004186 if (Type->hasExceptionSpec() &&
4187 CheckEquivalentExceptionSpec(
4188 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4189 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4190 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004191
4192 // If a function is explicitly defaulted on its first declaration,
4193 if (First) {
4194 // -- it is implicitly considered to be constexpr if the implicit
4195 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004196 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004197
Richard Smith3003e1d2012-05-15 04:39:51 +00004198 // -- it is implicitly considered to have the same exception-specification
4199 // as if it had been implicitly declared,
4200 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004201
4202 // Such a function is also trivial if the implicitly-declared function
4203 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004204 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004205 }
4206
Richard Smith3003e1d2012-05-15 04:39:51 +00004207 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004208 if (First) {
4209 MD->setDeletedAsWritten();
4210 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004211 // C++11 [dcl.fct.def.default]p4:
4212 // [For a] user-provided explicitly-defaulted function [...] if such a
4213 // function is implicitly defined as deleted, the program is ill-formed.
4214 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4215 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004216 }
4217 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004218
Richard Smith3003e1d2012-05-15 04:39:51 +00004219 if (HadError)
4220 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004221}
4222
Richard Smith7d5088a2012-02-18 02:02:13 +00004223namespace {
4224struct SpecialMemberDeletionInfo {
4225 Sema &S;
4226 CXXMethodDecl *MD;
4227 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004228 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004229
4230 // Properties of the special member, computed for convenience.
4231 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4232 SourceLocation Loc;
4233
4234 bool AllFieldsAreConst;
4235
4236 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004237 Sema::CXXSpecialMember CSM, bool Diagnose)
4238 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004239 IsConstructor(false), IsAssignment(false), IsMove(false),
4240 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4241 AllFieldsAreConst(true) {
4242 switch (CSM) {
4243 case Sema::CXXDefaultConstructor:
4244 case Sema::CXXCopyConstructor:
4245 IsConstructor = true;
4246 break;
4247 case Sema::CXXMoveConstructor:
4248 IsConstructor = true;
4249 IsMove = true;
4250 break;
4251 case Sema::CXXCopyAssignment:
4252 IsAssignment = true;
4253 break;
4254 case Sema::CXXMoveAssignment:
4255 IsAssignment = true;
4256 IsMove = true;
4257 break;
4258 case Sema::CXXDestructor:
4259 break;
4260 case Sema::CXXInvalid:
4261 llvm_unreachable("invalid special member kind");
4262 }
4263
4264 if (MD->getNumParams()) {
4265 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4266 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4267 }
4268 }
4269
4270 bool inUnion() const { return MD->getParent()->isUnion(); }
4271
4272 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004273 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4274 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004275 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004276 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4277 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4278 Quals = 0;
4279 return S.LookupSpecialMember(Class, CSM,
4280 ConstArg || (Quals & Qualifiers::Const),
4281 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004282 MD->getRefQualifier() == RQ_RValue,
4283 TQ & Qualifiers::Const,
4284 TQ & Qualifiers::Volatile);
4285 }
4286
Richard Smith6c4c36c2012-03-30 20:53:28 +00004287 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004288
Richard Smith6c4c36c2012-03-30 20:53:28 +00004289 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004290 bool shouldDeleteForField(FieldDecl *FD);
4291 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004292
Richard Smith517bb842012-07-18 03:51:16 +00004293 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4294 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004295 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4296 Sema::SpecialMemberOverloadResult *SMOR,
4297 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004298
4299 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004300};
4301}
4302
John McCall12d8d802012-04-09 20:53:23 +00004303/// Is the given special member inaccessible when used on the given
4304/// sub-object.
4305bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4306 CXXMethodDecl *target) {
4307 /// If we're operating on a base class, the object type is the
4308 /// type of this special member.
4309 QualType objectTy;
4310 AccessSpecifier access = target->getAccess();;
4311 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4312 objectTy = S.Context.getTypeDeclType(MD->getParent());
4313 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4314
4315 // If we're operating on a field, the object type is the type of the field.
4316 } else {
4317 objectTy = S.Context.getTypeDeclType(target->getParent());
4318 }
4319
4320 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4321}
4322
Richard Smith6c4c36c2012-03-30 20:53:28 +00004323/// Check whether we should delete a special member due to the implicit
4324/// definition containing a call to a special member of a subobject.
4325bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4326 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4327 bool IsDtorCallInCtor) {
4328 CXXMethodDecl *Decl = SMOR->getMethod();
4329 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4330
4331 int DiagKind = -1;
4332
4333 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4334 DiagKind = !Decl ? 0 : 1;
4335 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4336 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004337 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004338 DiagKind = 3;
4339 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4340 !Decl->isTrivial()) {
4341 // A member of a union must have a trivial corresponding special member.
4342 // As a weird special case, a destructor call from a union's constructor
4343 // must be accessible and non-deleted, but need not be trivial. Such a
4344 // destructor is never actually called, but is semantically checked as
4345 // if it were.
4346 DiagKind = 4;
4347 }
4348
4349 if (DiagKind == -1)
4350 return false;
4351
4352 if (Diagnose) {
4353 if (Field) {
4354 S.Diag(Field->getLocation(),
4355 diag::note_deleted_special_member_class_subobject)
4356 << CSM << MD->getParent() << /*IsField*/true
4357 << Field << DiagKind << IsDtorCallInCtor;
4358 } else {
4359 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4360 S.Diag(Base->getLocStart(),
4361 diag::note_deleted_special_member_class_subobject)
4362 << CSM << MD->getParent() << /*IsField*/false
4363 << Base->getType() << DiagKind << IsDtorCallInCtor;
4364 }
4365
4366 if (DiagKind == 1)
4367 S.NoteDeletedFunction(Decl);
4368 // FIXME: Explain inaccessibility if DiagKind == 3.
4369 }
4370
4371 return true;
4372}
4373
Richard Smith9a561d52012-02-26 09:11:52 +00004374/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004375/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004376bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004377 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004378 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004379
4380 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004381 // -- any direct or virtual base class, or non-static data member with no
4382 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004383 // either M has no default constructor or overload resolution as applied
4384 // to M's default constructor results in an ambiguity or in a function
4385 // that is deleted or inaccessible
4386 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4387 // -- a direct or virtual base class B that cannot be copied/moved because
4388 // overload resolution, as applied to B's corresponding special member,
4389 // results in an ambiguity or a function that is deleted or inaccessible
4390 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004391 // C++11 [class.dtor]p5:
4392 // -- any direct or virtual base class [...] has a type with a destructor
4393 // that is deleted or inaccessible
4394 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004395 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004396 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004397 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004398
Richard Smith6c4c36c2012-03-30 20:53:28 +00004399 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4400 // -- any direct or virtual base class or non-static data member has a
4401 // type with a destructor that is deleted or inaccessible
4402 if (IsConstructor) {
4403 Sema::SpecialMemberOverloadResult *SMOR =
4404 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4405 false, false, false, false, false);
4406 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4407 return true;
4408 }
4409
Richard Smith9a561d52012-02-26 09:11:52 +00004410 return false;
4411}
4412
4413/// Check whether we should delete a special member function due to the class
4414/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004415bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004416 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004417 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004418}
4419
4420/// Check whether we should delete a special member function due to the class
4421/// having a particular non-static data member.
4422bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4423 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4424 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4425
4426 if (CSM == Sema::CXXDefaultConstructor) {
4427 // For a default constructor, all references must be initialized in-class
4428 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004429 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4430 if (Diagnose)
4431 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4432 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004433 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004434 }
Richard Smith79363f52012-02-27 06:07:25 +00004435 // C++11 [class.ctor]p5: any non-variant non-static data member of
4436 // const-qualified type (or array thereof) with no
4437 // brace-or-equal-initializer does not have a user-provided default
4438 // constructor.
4439 if (!inUnion() && FieldType.isConstQualified() &&
4440 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004441 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4442 if (Diagnose)
4443 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004444 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004445 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004446 }
4447
4448 if (inUnion() && !FieldType.isConstQualified())
4449 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004450 } else if (CSM == Sema::CXXCopyConstructor) {
4451 // For a copy constructor, data members must not be of rvalue reference
4452 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004453 if (FieldType->isRValueReferenceType()) {
4454 if (Diagnose)
4455 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4456 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004457 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004458 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004459 } else if (IsAssignment) {
4460 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004461 if (FieldType->isReferenceType()) {
4462 if (Diagnose)
4463 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4464 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004465 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004466 }
4467 if (!FieldRecord && FieldType.isConstQualified()) {
4468 // C++11 [class.copy]p23:
4469 // -- a non-static data member of const non-class type (or array thereof)
4470 if (Diagnose)
4471 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004472 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004473 return true;
4474 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004475 }
4476
4477 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004478 // Some additional restrictions exist on the variant members.
4479 if (!inUnion() && FieldRecord->isUnion() &&
4480 FieldRecord->isAnonymousStructOrUnion()) {
4481 bool AllVariantFieldsAreConst = true;
4482
Richard Smithdf8dc862012-03-29 19:00:10 +00004483 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004484 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4485 UE = FieldRecord->field_end();
4486 UI != UE; ++UI) {
4487 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004488
4489 if (!UnionFieldType.isConstQualified())
4490 AllVariantFieldsAreConst = false;
4491
Richard Smith9a561d52012-02-26 09:11:52 +00004492 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4493 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004494 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4495 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004496 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004497 }
4498
4499 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004500 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004501 FieldRecord->field_begin() != FieldRecord->field_end()) {
4502 if (Diagnose)
4503 S.Diag(FieldRecord->getLocation(),
4504 diag::note_deleted_default_ctor_all_const)
4505 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004506 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004507 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004508
Richard Smithdf8dc862012-03-29 19:00:10 +00004509 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004510 // This is technically non-conformant, but sanity demands it.
4511 return false;
4512 }
4513
Richard Smith517bb842012-07-18 03:51:16 +00004514 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4515 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004516 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004517 }
4518
4519 return false;
4520}
4521
4522/// C++11 [class.ctor] p5:
4523/// A defaulted default constructor for a class X is defined as deleted if
4524/// X is a union and all of its variant members are of const-qualified type.
4525bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004526 // This is a silly definition, because it gives an empty union a deleted
4527 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004528 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4529 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4530 if (Diagnose)
4531 S.Diag(MD->getParent()->getLocation(),
4532 diag::note_deleted_default_ctor_all_const)
4533 << MD->getParent() << /*not anonymous union*/0;
4534 return true;
4535 }
4536 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004537}
4538
4539/// Determine whether a defaulted special member function should be defined as
4540/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4541/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004542bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4543 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004544 if (MD->isInvalidDecl())
4545 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004546 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004547 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004548 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004549 return false;
4550
Richard Smith7d5088a2012-02-18 02:02:13 +00004551 // C++11 [expr.lambda.prim]p19:
4552 // The closure type associated with a lambda-expression has a
4553 // deleted (8.4.3) default constructor and a deleted copy
4554 // assignment operator.
4555 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004556 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4557 if (Diagnose)
4558 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004559 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004560 }
4561
Richard Smith5bdaac52012-04-02 20:59:25 +00004562 // For an anonymous struct or union, the copy and assignment special members
4563 // will never be used, so skip the check. For an anonymous union declared at
4564 // namespace scope, the constructor and destructor are used.
4565 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4566 RD->isAnonymousStructOrUnion())
4567 return false;
4568
Richard Smith6c4c36c2012-03-30 20:53:28 +00004569 // C++11 [class.copy]p7, p18:
4570 // If the class definition declares a move constructor or move assignment
4571 // operator, an implicitly declared copy constructor or copy assignment
4572 // operator is defined as deleted.
4573 if (MD->isImplicit() &&
4574 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4575 CXXMethodDecl *UserDeclaredMove = 0;
4576
4577 // In Microsoft mode, a user-declared move only causes the deletion of the
4578 // corresponding copy operation, not both copy operations.
4579 if (RD->hasUserDeclaredMoveConstructor() &&
4580 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4581 if (!Diagnose) return true;
4582 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004583 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004584 } else if (RD->hasUserDeclaredMoveAssignment() &&
4585 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4586 if (!Diagnose) return true;
4587 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004588 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004589 }
4590
4591 if (UserDeclaredMove) {
4592 Diag(UserDeclaredMove->getLocation(),
4593 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004594 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004595 << UserDeclaredMove->isMoveAssignmentOperator();
4596 return true;
4597 }
4598 }
Sean Hunte16da072011-10-10 06:18:57 +00004599
Richard Smith5bdaac52012-04-02 20:59:25 +00004600 // Do access control from the special member function
4601 ContextRAII MethodContext(*this, MD);
4602
Richard Smith9a561d52012-02-26 09:11:52 +00004603 // C++11 [class.dtor]p5:
4604 // -- for a virtual destructor, lookup of the non-array deallocation function
4605 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004606 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004607 FunctionDecl *OperatorDelete = 0;
4608 DeclarationName Name =
4609 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4610 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004611 OperatorDelete, false)) {
4612 if (Diagnose)
4613 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004614 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004615 }
Richard Smith9a561d52012-02-26 09:11:52 +00004616 }
4617
Richard Smith6c4c36c2012-03-30 20:53:28 +00004618 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004619
Sean Huntcdee3fe2011-05-11 22:34:38 +00004620 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004621 BE = RD->bases_end(); BI != BE; ++BI)
4622 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004623 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004624 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004625
4626 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004628 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004629 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004630
4631 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004632 FE = RD->field_end(); FI != FE; ++FI)
4633 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004634 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004635 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004636
Richard Smith7d5088a2012-02-18 02:02:13 +00004637 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004638 return true;
4639
4640 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004641}
4642
4643/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004644namespace {
4645 struct FindHiddenVirtualMethodData {
4646 Sema *S;
4647 CXXMethodDecl *Method;
4648 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004649 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004650 };
4651}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004652
4653/// \brief Member lookup function that determines whether a given C++
4654/// method overloads virtual methods in a base class without overriding any,
4655/// to be used with CXXRecordDecl::lookupInBases().
4656static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4657 CXXBasePath &Path,
4658 void *UserData) {
4659 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4660
4661 FindHiddenVirtualMethodData &Data
4662 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4663
4664 DeclarationName Name = Data.Method->getDeclName();
4665 assert(Name.getNameKind() == DeclarationName::Identifier);
4666
4667 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004668 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004669 for (Path.Decls = BaseRecord->lookup(Name);
4670 Path.Decls.first != Path.Decls.second;
4671 ++Path.Decls.first) {
4672 NamedDecl *D = *Path.Decls.first;
4673 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004674 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004675 foundSameNameMethod = true;
4676 // Interested only in hidden virtual methods.
4677 if (!MD->isVirtual())
4678 continue;
4679 // If the method we are checking overrides a method from its base
4680 // don't warn about the other overloaded methods.
4681 if (!Data.S->IsOverload(Data.Method, MD, false))
4682 return true;
4683 // Collect the overload only if its hidden.
4684 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4685 overloadedMethods.push_back(MD);
4686 }
4687 }
4688
4689 if (foundSameNameMethod)
4690 Data.OverloadedMethods.append(overloadedMethods.begin(),
4691 overloadedMethods.end());
4692 return foundSameNameMethod;
4693}
4694
4695/// \brief See if a method overloads virtual methods in a base class without
4696/// overriding any.
4697void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4698 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004699 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004700 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004701 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004702 return;
4703
4704 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4705 /*bool RecordPaths=*/false,
4706 /*bool DetectVirtual=*/false);
4707 FindHiddenVirtualMethodData Data;
4708 Data.Method = MD;
4709 Data.S = this;
4710
4711 // Keep the base methods that were overriden or introduced in the subclass
4712 // by 'using' in a set. A base method not in this set is hidden.
4713 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4714 res.first != res.second; ++res.first) {
4715 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4716 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4717 E = MD->end_overridden_methods();
4718 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004719 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004720 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4721 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004722 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004723 }
4724
4725 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4726 !Data.OverloadedMethods.empty()) {
4727 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4728 << MD << (Data.OverloadedMethods.size() > 1);
4729
4730 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4731 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4732 Diag(overloadedMD->getLocation(),
4733 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4734 }
4735 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004736}
4737
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004738void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004739 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004740 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004741 SourceLocation RBrac,
4742 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004743 if (!TagDecl)
4744 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Douglas Gregor42af25f2009-05-11 19:58:34 +00004746 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004747
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004748 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4749 if (l->getKind() != AttributeList::AT_Visibility)
4750 continue;
4751 l->setInvalid();
4752 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4753 l->getName();
4754 }
4755
David Blaikie77b6de02011-09-22 02:58:26 +00004756 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004757 // strict aliasing violation!
4758 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004759 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004760
Douglas Gregor23c94db2010-07-02 17:43:08 +00004761 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004762 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004763}
4764
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004765/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4766/// special functions, such as the default constructor, copy
4767/// constructor, or destructor, to the given C++ class (C++
4768/// [special]p1). This routine can only be executed just before the
4769/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004770void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004771 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004772 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004773
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004774 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004775 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004776
David Blaikie4e4d0842012-03-11 07:00:24 +00004777 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004778 ++ASTContext::NumImplicitMoveConstructors;
4779
Douglas Gregora376d102010-07-02 21:50:04 +00004780 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4781 ++ASTContext::NumImplicitCopyAssignmentOperators;
4782
4783 // If we have a dynamic class, then the copy assignment operator may be
4784 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4785 // it shows up in the right place in the vtable and that we diagnose
4786 // problems with the implicit exception specification.
4787 if (ClassDecl->isDynamicClass())
4788 DeclareImplicitCopyAssignment(ClassDecl);
4789 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004790
Richard Smith1c931be2012-04-02 18:40:40 +00004791 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004792 ++ASTContext::NumImplicitMoveAssignmentOperators;
4793
4794 // Likewise for the move assignment operator.
4795 if (ClassDecl->isDynamicClass())
4796 DeclareImplicitMoveAssignment(ClassDecl);
4797 }
4798
Douglas Gregor4923aa22010-07-02 20:37:36 +00004799 if (!ClassDecl->hasUserDeclaredDestructor()) {
4800 ++ASTContext::NumImplicitDestructors;
4801
4802 // If we have a dynamic class, then the destructor may be virtual, so we
4803 // have to declare the destructor immediately. This ensures that, e.g., it
4804 // shows up in the right place in the vtable and that we diagnose problems
4805 // with the implicit exception specification.
4806 if (ClassDecl->isDynamicClass())
4807 DeclareImplicitDestructor(ClassDecl);
4808 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004809}
4810
Francois Pichet8387e2a2011-04-22 22:18:13 +00004811void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4812 if (!D)
4813 return;
4814
4815 int NumParamList = D->getNumTemplateParameterLists();
4816 for (int i = 0; i < NumParamList; i++) {
4817 TemplateParameterList* Params = D->getTemplateParameterList(i);
4818 for (TemplateParameterList::iterator Param = Params->begin(),
4819 ParamEnd = Params->end();
4820 Param != ParamEnd; ++Param) {
4821 NamedDecl *Named = cast<NamedDecl>(*Param);
4822 if (Named->getDeclName()) {
4823 S->AddDecl(Named);
4824 IdResolver.AddDecl(Named);
4825 }
4826 }
4827 }
4828}
4829
John McCalld226f652010-08-21 09:40:31 +00004830void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004831 if (!D)
4832 return;
4833
4834 TemplateParameterList *Params = 0;
4835 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4836 Params = Template->getTemplateParameters();
4837 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4838 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4839 Params = PartialSpec->getTemplateParameters();
4840 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004841 return;
4842
Douglas Gregor6569d682009-05-27 23:11:45 +00004843 for (TemplateParameterList::iterator Param = Params->begin(),
4844 ParamEnd = Params->end();
4845 Param != ParamEnd; ++Param) {
4846 NamedDecl *Named = cast<NamedDecl>(*Param);
4847 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004848 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004849 IdResolver.AddDecl(Named);
4850 }
4851 }
4852}
4853
John McCalld226f652010-08-21 09:40:31 +00004854void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004855 if (!RecordD) return;
4856 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004857 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004858 PushDeclContext(S, Record);
4859}
4860
John McCalld226f652010-08-21 09:40:31 +00004861void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004862 if (!RecordD) return;
4863 PopDeclContext();
4864}
4865
Douglas Gregor72b505b2008-12-16 21:30:33 +00004866/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4867/// parsing a top-level (non-nested) C++ class, and we are now
4868/// parsing those parts of the given Method declaration that could
4869/// not be parsed earlier (C++ [class.mem]p2), such as default
4870/// arguments. This action should enter the scope of the given
4871/// Method declaration as if we had just parsed the qualified method
4872/// name. However, it should not bring the parameters into scope;
4873/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004874void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004875}
4876
4877/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4878/// C++ method declaration. We're (re-)introducing the given
4879/// function parameter into scope for use in parsing later parts of
4880/// the method declaration. For example, we could see an
4881/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004882void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004883 if (!ParamD)
4884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004885
John McCalld226f652010-08-21 09:40:31 +00004886 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004887
4888 // If this parameter has an unparsed default argument, clear it out
4889 // to make way for the parsed default argument.
4890 if (Param->hasUnparsedDefaultArg())
4891 Param->setDefaultArg(0);
4892
John McCalld226f652010-08-21 09:40:31 +00004893 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004894 if (Param->getDeclName())
4895 IdResolver.AddDecl(Param);
4896}
4897
4898/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4899/// processing the delayed method declaration for Method. The method
4900/// declaration is now considered finished. There may be a separate
4901/// ActOnStartOfFunctionDef action later (not necessarily
4902/// immediately!) for this method, if it was also defined inside the
4903/// class body.
John McCalld226f652010-08-21 09:40:31 +00004904void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004905 if (!MethodD)
4906 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004908 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004909
John McCalld226f652010-08-21 09:40:31 +00004910 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004911
4912 // Now that we have our default arguments, check the constructor
4913 // again. It could produce additional diagnostics or affect whether
4914 // the class has implicitly-declared destructors, among other
4915 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004916 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4917 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004918
4919 // Check the default arguments, which we may have added.
4920 if (!Method->isInvalidDecl())
4921 CheckCXXDefaultArguments(Method);
4922}
4923
Douglas Gregor42a552f2008-11-05 20:51:48 +00004924/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004925/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004926/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004927/// emit diagnostics and set the invalid bit to true. In any case, the type
4928/// will be updated to reflect a well-formed type for the constructor and
4929/// returned.
4930QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004931 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004932 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004933
4934 // C++ [class.ctor]p3:
4935 // A constructor shall not be virtual (10.3) or static (9.4). A
4936 // constructor can be invoked for a const, volatile or const
4937 // volatile object. A constructor shall not be declared const,
4938 // volatile, or const volatile (9.3.2).
4939 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004940 if (!D.isInvalidType())
4941 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4942 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4943 << SourceRange(D.getIdentifierLoc());
4944 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004945 }
John McCalld931b082010-08-26 03:08:43 +00004946 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004947 if (!D.isInvalidType())
4948 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4949 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4950 << SourceRange(D.getIdentifierLoc());
4951 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004952 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004953 }
Mike Stump1eb44332009-09-09 15:08:12 +00004954
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004955 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004956 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004957 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004958 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4959 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004960 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004961 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4962 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004963 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004964 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4965 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004966 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004967 }
Mike Stump1eb44332009-09-09 15:08:12 +00004968
Douglas Gregorc938c162011-01-26 05:01:58 +00004969 // C++0x [class.ctor]p4:
4970 // A constructor shall not be declared with a ref-qualifier.
4971 if (FTI.hasRefQualifier()) {
4972 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4973 << FTI.RefQualifierIsLValueRef
4974 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4975 D.setInvalidType();
4976 }
4977
Douglas Gregor42a552f2008-11-05 20:51:48 +00004978 // Rebuild the function type "R" without any type qualifiers (in
4979 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004980 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004981 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004982 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4983 return R;
4984
4985 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4986 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004987 EPI.RefQualifier = RQ_None;
4988
Chris Lattner65401802009-04-25 08:28:21 +00004989 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004990 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004991}
4992
Douglas Gregor72b505b2008-12-16 21:30:33 +00004993/// CheckConstructor - Checks a fully-formed constructor for
4994/// well-formedness, issuing any diagnostics required. Returns true if
4995/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004996void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004997 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004998 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4999 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005000 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005001
5002 // C++ [class.copy]p3:
5003 // A declaration of a constructor for a class X is ill-formed if
5004 // its first parameter is of type (optionally cv-qualified) X and
5005 // either there are no other parameters or else all other
5006 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005007 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005008 ((Constructor->getNumParams() == 1) ||
5009 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005010 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5011 Constructor->getTemplateSpecializationKind()
5012 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005013 QualType ParamType = Constructor->getParamDecl(0)->getType();
5014 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5015 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005016 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005017 const char *ConstRef
5018 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5019 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005020 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005021 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005022
5023 // FIXME: Rather that making the constructor invalid, we should endeavor
5024 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005025 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005026 }
5027 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005028}
5029
John McCall15442822010-08-04 01:04:25 +00005030/// CheckDestructor - Checks a fully-formed destructor definition for
5031/// well-formedness, issuing any diagnostics required. Returns true
5032/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005033bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005034 CXXRecordDecl *RD = Destructor->getParent();
5035
5036 if (Destructor->isVirtual()) {
5037 SourceLocation Loc;
5038
5039 if (!Destructor->isImplicit())
5040 Loc = Destructor->getLocation();
5041 else
5042 Loc = RD->getLocation();
5043
5044 // If we have a virtual destructor, look up the deallocation function
5045 FunctionDecl *OperatorDelete = 0;
5046 DeclarationName Name =
5047 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005048 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005049 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005050
Eli Friedman5f2987c2012-02-02 03:46:19 +00005051 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005052
5053 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005054 }
Anders Carlsson37909802009-11-30 21:24:50 +00005055
5056 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005057}
5058
Mike Stump1eb44332009-09-09 15:08:12 +00005059static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005060FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5061 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5062 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005063 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005064}
5065
Douglas Gregor42a552f2008-11-05 20:51:48 +00005066/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5067/// the well-formednes of the destructor declarator @p D with type @p
5068/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005069/// emit diagnostics and set the declarator to invalid. Even if this happens,
5070/// will be updated to reflect a well-formed type for the destructor and
5071/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005072QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005073 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005074 // C++ [class.dtor]p1:
5075 // [...] A typedef-name that names a class is a class-name
5076 // (7.1.3); however, a typedef-name that names a class shall not
5077 // be used as the identifier in the declarator for a destructor
5078 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005079 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005080 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005081 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005082 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005083 else if (const TemplateSpecializationType *TST =
5084 DeclaratorType->getAs<TemplateSpecializationType>())
5085 if (TST->isTypeAlias())
5086 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5087 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005088
5089 // C++ [class.dtor]p2:
5090 // A destructor is used to destroy objects of its class type. A
5091 // destructor takes no parameters, and no return type can be
5092 // specified for it (not even void). The address of a destructor
5093 // shall not be taken. A destructor shall not be static. A
5094 // destructor can be invoked for a const, volatile or const
5095 // volatile object. A destructor shall not be declared const,
5096 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005097 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005098 if (!D.isInvalidType())
5099 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5100 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005101 << SourceRange(D.getIdentifierLoc())
5102 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5103
John McCalld931b082010-08-26 03:08:43 +00005104 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005105 }
Chris Lattner65401802009-04-25 08:28:21 +00005106 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005107 // Destructors don't have return types, but the parser will
5108 // happily parse something like:
5109 //
5110 // class X {
5111 // float ~X();
5112 // };
5113 //
5114 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005115 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5116 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5117 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005118 }
Mike Stump1eb44332009-09-09 15:08:12 +00005119
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005120 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005121 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005122 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005123 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5124 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005125 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005126 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5127 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005128 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005129 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5130 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005131 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005132 }
5133
Douglas Gregorc938c162011-01-26 05:01:58 +00005134 // C++0x [class.dtor]p2:
5135 // A destructor shall not be declared with a ref-qualifier.
5136 if (FTI.hasRefQualifier()) {
5137 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5138 << FTI.RefQualifierIsLValueRef
5139 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5140 D.setInvalidType();
5141 }
5142
Douglas Gregor42a552f2008-11-05 20:51:48 +00005143 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005144 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005145 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5146
5147 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005148 FTI.freeArgs();
5149 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005150 }
5151
Mike Stump1eb44332009-09-09 15:08:12 +00005152 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005153 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005154 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005155 D.setInvalidType();
5156 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005157
5158 // Rebuild the function type "R" without any type qualifiers or
5159 // parameters (in case any of the errors above fired) and with
5160 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005161 // types.
John McCalle23cf432010-12-14 08:05:40 +00005162 if (!D.isInvalidType())
5163 return R;
5164
Douglas Gregord92ec472010-07-01 05:10:53 +00005165 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005166 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5167 EPI.Variadic = false;
5168 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005169 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005170 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005171}
5172
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005173/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5174/// well-formednes of the conversion function declarator @p D with
5175/// type @p R. If there are any errors in the declarator, this routine
5176/// will emit diagnostics and return true. Otherwise, it will return
5177/// false. Either way, the type @p R will be updated to reflect a
5178/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005179void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005180 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005181 // C++ [class.conv.fct]p1:
5182 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005183 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005184 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005185 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005186 if (!D.isInvalidType())
5187 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5188 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5189 << SourceRange(D.getIdentifierLoc());
5190 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005191 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005192 }
John McCalla3f81372010-04-13 00:04:31 +00005193
5194 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5195
Chris Lattner6e475012009-04-25 08:35:12 +00005196 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005197 // Conversion functions don't have return types, but the parser will
5198 // happily parse something like:
5199 //
5200 // class X {
5201 // float operator bool();
5202 // };
5203 //
5204 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005205 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5206 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5207 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005208 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005209 }
5210
John McCalla3f81372010-04-13 00:04:31 +00005211 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5212
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005213 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005214 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005215 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5216
5217 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005218 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005219 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005220 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005221 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005222 D.setInvalidType();
5223 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005224
John McCalla3f81372010-04-13 00:04:31 +00005225 // Diagnose "&operator bool()" and other such nonsense. This
5226 // is actually a gcc extension which we don't support.
5227 if (Proto->getResultType() != ConvType) {
5228 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5229 << Proto->getResultType();
5230 D.setInvalidType();
5231 ConvType = Proto->getResultType();
5232 }
5233
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005234 // C++ [class.conv.fct]p4:
5235 // The conversion-type-id shall not represent a function type nor
5236 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005237 if (ConvType->isArrayType()) {
5238 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5239 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005240 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005241 } else if (ConvType->isFunctionType()) {
5242 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5243 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005244 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005245 }
5246
5247 // Rebuild the function type "R" without any parameters (in case any
5248 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005249 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005250 if (D.isInvalidType())
5251 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005252
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005253 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005254 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005255 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005256 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005257 diag::warn_cxx98_compat_explicit_conversion_functions :
5258 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005259 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005260}
5261
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005262/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5263/// the declaration of the given C++ conversion function. This routine
5264/// is responsible for recording the conversion function in the C++
5265/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005266Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005267 assert(Conversion && "Expected to receive a conversion function declaration");
5268
Douglas Gregor9d350972008-12-12 08:25:50 +00005269 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005270
5271 // Make sure we aren't redeclaring the conversion function.
5272 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005273
5274 // C++ [class.conv.fct]p1:
5275 // [...] A conversion function is never used to convert a
5276 // (possibly cv-qualified) object to the (possibly cv-qualified)
5277 // same object type (or a reference to it), to a (possibly
5278 // cv-qualified) base class of that type (or a reference to it),
5279 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005280 // FIXME: Suppress this warning if the conversion function ends up being a
5281 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005282 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005283 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005284 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005285 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005286 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5287 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005288 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005289 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005290 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5291 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005292 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005293 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005294 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005295 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005296 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005297 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005298 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005299 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005300 }
5301
Douglas Gregore80622f2010-09-29 04:25:11 +00005302 if (FunctionTemplateDecl *ConversionTemplate
5303 = Conversion->getDescribedFunctionTemplate())
5304 return ConversionTemplate;
5305
John McCalld226f652010-08-21 09:40:31 +00005306 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005307}
5308
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005309//===----------------------------------------------------------------------===//
5310// Namespace Handling
5311//===----------------------------------------------------------------------===//
5312
John McCallea318642010-08-26 09:15:37 +00005313
5314
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005315/// ActOnStartNamespaceDef - This is called at the start of a namespace
5316/// definition.
John McCalld226f652010-08-21 09:40:31 +00005317Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005318 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005319 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005320 SourceLocation IdentLoc,
5321 IdentifierInfo *II,
5322 SourceLocation LBrace,
5323 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005324 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5325 // For anonymous namespace, take the location of the left brace.
5326 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005327 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005328 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005329 bool IsStd = false;
5330 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005331 Scope *DeclRegionScope = NamespcScope->getParent();
5332
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005333 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005334 if (II) {
5335 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005336 // The identifier in an original-namespace-definition shall not
5337 // have been previously defined in the declarative region in
5338 // which the original-namespace-definition appears. The
5339 // identifier in an original-namespace-definition is the name of
5340 // the namespace. Subsequently in that declarative region, it is
5341 // treated as an original-namespace-name.
5342 //
5343 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005344 // look through using directives, just look for any ordinary names.
5345
5346 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5348 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005349 NamedDecl *PrevDecl = 0;
5350 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005351 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005352 R.first != R.second; ++R.first) {
5353 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5354 PrevDecl = *R.first;
5355 break;
5356 }
5357 }
5358
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005359 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5360
5361 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005362 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005363 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005364 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005365 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005366 // The user probably just forgot the 'inline', so suggest that it
5367 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005368 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005369 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5370 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005371 Diag(Loc, diag::err_inline_namespace_mismatch)
5372 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005373 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005374 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5375
5376 IsInline = PrevNS->isInline();
5377 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005378 } else if (PrevDecl) {
5379 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005380 Diag(Loc, diag::err_redefinition_different_kind)
5381 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005382 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005383 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005384 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005385 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005386 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005387 // This is the first "real" definition of the namespace "std", so update
5388 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005389 PrevNS = getStdNamespace();
5390 IsStd = true;
5391 AddToKnown = !IsInline;
5392 } else {
5393 // We've seen this namespace for the first time.
5394 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005395 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005396 } else {
John McCall9aeed322009-10-01 00:25:31 +00005397 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005398
5399 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005400 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005401 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005402 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005403 } else {
5404 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005405 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005406 }
5407
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005408 if (PrevNS && IsInline != PrevNS->isInline()) {
5409 // inline-ness must match
5410 Diag(Loc, diag::err_inline_namespace_mismatch)
5411 << IsInline;
5412 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005413
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005414 // Recover by ignoring the new namespace's inline status.
5415 IsInline = PrevNS->isInline();
5416 }
5417 }
5418
5419 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5420 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005421 if (IsInvalid)
5422 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005423
5424 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005425
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005426 // FIXME: Should we be merging attributes?
5427 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005428 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005429
5430 if (IsStd)
5431 StdNamespace = Namespc;
5432 if (AddToKnown)
5433 KnownNamespaces[Namespc] = false;
5434
5435 if (II) {
5436 PushOnScopeChains(Namespc, DeclRegionScope);
5437 } else {
5438 // Link the anonymous namespace into its parent.
5439 DeclContext *Parent = CurContext->getRedeclContext();
5440 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5441 TU->setAnonymousNamespace(Namespc);
5442 } else {
5443 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005444 }
John McCall9aeed322009-10-01 00:25:31 +00005445
Douglas Gregora4181472010-03-24 00:46:35 +00005446 CurContext->addDecl(Namespc);
5447
John McCall9aeed322009-10-01 00:25:31 +00005448 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5449 // behaves as if it were replaced by
5450 // namespace unique { /* empty body */ }
5451 // using namespace unique;
5452 // namespace unique { namespace-body }
5453 // where all occurrences of 'unique' in a translation unit are
5454 // replaced by the same identifier and this identifier differs
5455 // from all other identifiers in the entire program.
5456
5457 // We just create the namespace with an empty name and then add an
5458 // implicit using declaration, just like the standard suggests.
5459 //
5460 // CodeGen enforces the "universally unique" aspect by giving all
5461 // declarations semantically contained within an anonymous
5462 // namespace internal linkage.
5463
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005464 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005465 UsingDirectiveDecl* UD
5466 = UsingDirectiveDecl::Create(Context, CurContext,
5467 /* 'using' */ LBrace,
5468 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005469 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005470 /* identifier */ SourceLocation(),
5471 Namespc,
5472 /* Ancestor */ CurContext);
5473 UD->setImplicit();
5474 CurContext->addDecl(UD);
5475 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005476 }
5477
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005478 ActOnDocumentableDecl(Namespc);
5479
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005480 // Although we could have an invalid decl (i.e. the namespace name is a
5481 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005482 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5483 // for the namespace has the declarations that showed up in that particular
5484 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005485 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005486 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005487}
5488
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005489/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5490/// is a namespace alias, returns the namespace it points to.
5491static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5492 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5493 return AD->getNamespace();
5494 return dyn_cast_or_null<NamespaceDecl>(D);
5495}
5496
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005497/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5498/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005499void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005500 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5501 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005502 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005503 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005504 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005505 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005506}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005507
John McCall384aff82010-08-25 07:42:41 +00005508CXXRecordDecl *Sema::getStdBadAlloc() const {
5509 return cast_or_null<CXXRecordDecl>(
5510 StdBadAlloc.get(Context.getExternalSource()));
5511}
5512
5513NamespaceDecl *Sema::getStdNamespace() const {
5514 return cast_or_null<NamespaceDecl>(
5515 StdNamespace.get(Context.getExternalSource()));
5516}
5517
Douglas Gregor66992202010-06-29 17:53:46 +00005518/// \brief Retrieve the special "std" namespace, which may require us to
5519/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005520NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005521 if (!StdNamespace) {
5522 // The "std" namespace has not yet been defined, so build one implicitly.
5523 StdNamespace = NamespaceDecl::Create(Context,
5524 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005525 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005526 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005527 &PP.getIdentifierTable().get("std"),
5528 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005529 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005530 }
5531
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005532 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005533}
5534
Sebastian Redl395e04d2012-01-17 22:49:33 +00005535bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005536 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005537 "Looking for std::initializer_list outside of C++.");
5538
5539 // We're looking for implicit instantiations of
5540 // template <typename E> class std::initializer_list.
5541
5542 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5543 return false;
5544
Sebastian Redl84760e32012-01-17 22:49:58 +00005545 ClassTemplateDecl *Template = 0;
5546 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005547
Sebastian Redl84760e32012-01-17 22:49:58 +00005548 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005549
Sebastian Redl84760e32012-01-17 22:49:58 +00005550 ClassTemplateSpecializationDecl *Specialization =
5551 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5552 if (!Specialization)
5553 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005554
Sebastian Redl84760e32012-01-17 22:49:58 +00005555 Template = Specialization->getSpecializedTemplate();
5556 Arguments = Specialization->getTemplateArgs().data();
5557 } else if (const TemplateSpecializationType *TST =
5558 Ty->getAs<TemplateSpecializationType>()) {
5559 Template = dyn_cast_or_null<ClassTemplateDecl>(
5560 TST->getTemplateName().getAsTemplateDecl());
5561 Arguments = TST->getArgs();
5562 }
5563 if (!Template)
5564 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005565
5566 if (!StdInitializerList) {
5567 // Haven't recognized std::initializer_list yet, maybe this is it.
5568 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5569 if (TemplateClass->getIdentifier() !=
5570 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005571 !getStdNamespace()->InEnclosingNamespaceSetOf(
5572 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005573 return false;
5574 // This is a template called std::initializer_list, but is it the right
5575 // template?
5576 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005577 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005578 return false;
5579 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5580 return false;
5581
5582 // It's the right template.
5583 StdInitializerList = Template;
5584 }
5585
5586 if (Template != StdInitializerList)
5587 return false;
5588
5589 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005590 if (Element)
5591 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005592 return true;
5593}
5594
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005595static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5596 NamespaceDecl *Std = S.getStdNamespace();
5597 if (!Std) {
5598 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5599 return 0;
5600 }
5601
5602 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5603 Loc, Sema::LookupOrdinaryName);
5604 if (!S.LookupQualifiedName(Result, Std)) {
5605 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5606 return 0;
5607 }
5608 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5609 if (!Template) {
5610 Result.suppressDiagnostics();
5611 // We found something weird. Complain about the first thing we found.
5612 NamedDecl *Found = *Result.begin();
5613 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5614 return 0;
5615 }
5616
5617 // We found some template called std::initializer_list. Now verify that it's
5618 // correct.
5619 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005620 if (Params->getMinRequiredArguments() != 1 ||
5621 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005622 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5623 return 0;
5624 }
5625
5626 return Template;
5627}
5628
5629QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5630 if (!StdInitializerList) {
5631 StdInitializerList = LookupStdInitializerList(*this, Loc);
5632 if (!StdInitializerList)
5633 return QualType();
5634 }
5635
5636 TemplateArgumentListInfo Args(Loc, Loc);
5637 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5638 Context.getTrivialTypeSourceInfo(Element,
5639 Loc)));
5640 return Context.getCanonicalType(
5641 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5642}
5643
Sebastian Redl98d36062012-01-17 22:50:14 +00005644bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5645 // C++ [dcl.init.list]p2:
5646 // A constructor is an initializer-list constructor if its first parameter
5647 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5648 // std::initializer_list<E> for some type E, and either there are no other
5649 // parameters or else all other parameters have default arguments.
5650 if (Ctor->getNumParams() < 1 ||
5651 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5652 return false;
5653
5654 QualType ArgType = Ctor->getParamDecl(0)->getType();
5655 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5656 ArgType = RT->getPointeeType().getUnqualifiedType();
5657
5658 return isStdInitializerList(ArgType, 0);
5659}
5660
Douglas Gregor9172aa62011-03-26 22:25:30 +00005661/// \brief Determine whether a using statement is in a context where it will be
5662/// apply in all contexts.
5663static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5664 switch (CurContext->getDeclKind()) {
5665 case Decl::TranslationUnit:
5666 return true;
5667 case Decl::LinkageSpec:
5668 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5669 default:
5670 return false;
5671 }
5672}
5673
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005674namespace {
5675
5676// Callback to only accept typo corrections that are namespaces.
5677class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5678 public:
5679 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5680 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5681 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5682 }
5683 return false;
5684 }
5685};
5686
5687}
5688
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005689static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5690 CXXScopeSpec &SS,
5691 SourceLocation IdentLoc,
5692 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005693 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005694 R.clear();
5695 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005696 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005697 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005698 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5699 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005700 if (DeclContext *DC = S.computeDeclContext(SS, false))
5701 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5702 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5703 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5704 else
5705 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5706 << Ident << CorrectedQuotedStr
5707 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005708
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005709 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5710 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005711
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005712 R.addDecl(Corrected.getCorrectionDecl());
5713 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005714 }
5715 return false;
5716}
5717
John McCalld226f652010-08-21 09:40:31 +00005718Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005719 SourceLocation UsingLoc,
5720 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005721 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005722 SourceLocation IdentLoc,
5723 IdentifierInfo *NamespcName,
5724 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005725 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5726 assert(NamespcName && "Invalid NamespcName.");
5727 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005728
5729 // This can only happen along a recovery path.
5730 while (S->getFlags() & Scope::TemplateParamScope)
5731 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005732 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005733
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005734 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005735 NestedNameSpecifier *Qualifier = 0;
5736 if (SS.isSet())
5737 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5738
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005739 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005740 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5741 LookupParsedName(R, S, &SS);
5742 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005743 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005744
Douglas Gregor66992202010-06-29 17:53:46 +00005745 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005746 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005747 // Allow "using namespace std;" or "using namespace ::std;" even if
5748 // "std" hasn't been defined yet, for GCC compatibility.
5749 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5750 NamespcName->isStr("std")) {
5751 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005752 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005753 R.resolveKind();
5754 }
5755 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005756 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005757 }
5758
John McCallf36e02d2009-10-09 21:13:30 +00005759 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005760 NamedDecl *Named = R.getFoundDecl();
5761 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5762 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005763 // C++ [namespace.udir]p1:
5764 // A using-directive specifies that the names in the nominated
5765 // namespace can be used in the scope in which the
5766 // using-directive appears after the using-directive. During
5767 // unqualified name lookup (3.4.1), the names appear as if they
5768 // were declared in the nearest enclosing namespace which
5769 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005770 // namespace. [Note: in this context, "contains" means "contains
5771 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005772
5773 // Find enclosing context containing both using-directive and
5774 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005775 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005776 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5777 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5778 CommonAncestor = CommonAncestor->getParent();
5779
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005780 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005781 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005782 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005783
Douglas Gregor9172aa62011-03-26 22:25:30 +00005784 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005785 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005786 Diag(IdentLoc, diag::warn_using_directive_in_header);
5787 }
5788
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005789 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005790 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005791 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005792 }
5793
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005794 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005795 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005796}
5797
5798void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005799 // If the scope has an associated entity and the using directive is at
5800 // namespace or translation unit scope, add the UsingDirectiveDecl into
5801 // its lookup structure so qualified name lookup can find it.
5802 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5803 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005804 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005805 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005806 // Otherwise, it is at block sope. The using-directives will affect lookup
5807 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005808 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005809}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005810
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005811
John McCalld226f652010-08-21 09:40:31 +00005812Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005813 AccessSpecifier AS,
5814 bool HasUsingKeyword,
5815 SourceLocation UsingLoc,
5816 CXXScopeSpec &SS,
5817 UnqualifiedId &Name,
5818 AttributeList *AttrList,
5819 bool IsTypeName,
5820 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005821 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005822
Douglas Gregor12c118a2009-11-04 16:30:06 +00005823 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005824 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005825 case UnqualifiedId::IK_Identifier:
5826 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005827 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005828 case UnqualifiedId::IK_ConversionFunctionId:
5829 break;
5830
5831 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005832 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005833 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005834 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005835 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005836 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5837 // instead once inheriting constructors work.
5838 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005839 diag::err_using_decl_constructor)
5840 << SS.getRange();
5841
David Blaikie4e4d0842012-03-11 07:00:24 +00005842 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005843
John McCalld226f652010-08-21 09:40:31 +00005844 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005845
5846 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005847 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005848 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005849 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005850
5851 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005852 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005853 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005854 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005855 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005856
5857 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5858 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005859 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005860 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005861
John McCall60fa3cf2009-12-11 02:10:03 +00005862 // Warn about using declarations.
5863 // TODO: store that the declaration was written without 'using' and
5864 // talk about access decls instead of using decls in the
5865 // diagnostics.
5866 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005867 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005868
5869 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005870 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005871 }
5872
Douglas Gregor56c04582010-12-16 00:46:58 +00005873 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5874 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5875 return 0;
5876
John McCall9488ea12009-11-17 05:59:44 +00005877 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005878 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005879 /* IsInstantiation */ false,
5880 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005881 if (UD)
5882 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005883
John McCalld226f652010-08-21 09:40:31 +00005884 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005885}
5886
Douglas Gregor09acc982010-07-07 23:08:52 +00005887/// \brief Determine whether a using declaration considers the given
5888/// declarations as "equivalent", e.g., if they are redeclarations of
5889/// the same entity or are both typedefs of the same type.
5890static bool
5891IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5892 bool &SuppressRedeclaration) {
5893 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5894 SuppressRedeclaration = false;
5895 return true;
5896 }
5897
Richard Smith162e1c12011-04-15 14:24:37 +00005898 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5899 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005900 SuppressRedeclaration = true;
5901 return Context.hasSameType(TD1->getUnderlyingType(),
5902 TD2->getUnderlyingType());
5903 }
5904
5905 return false;
5906}
5907
5908
John McCall9f54ad42009-12-10 09:41:52 +00005909/// Determines whether to create a using shadow decl for a particular
5910/// decl, given the set of decls existing prior to this using lookup.
5911bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5912 const LookupResult &Previous) {
5913 // Diagnose finding a decl which is not from a base class of the
5914 // current class. We do this now because there are cases where this
5915 // function will silently decide not to build a shadow decl, which
5916 // will pre-empt further diagnostics.
5917 //
5918 // We don't need to do this in C++0x because we do the check once on
5919 // the qualifier.
5920 //
5921 // FIXME: diagnose the following if we care enough:
5922 // struct A { int foo; };
5923 // struct B : A { using A::foo; };
5924 // template <class T> struct C : A {};
5925 // template <class T> struct D : C<T> { using B::foo; } // <---
5926 // This is invalid (during instantiation) in C++03 because B::foo
5927 // resolves to the using decl in B, which is not a base class of D<T>.
5928 // We can't diagnose it immediately because C<T> is an unknown
5929 // specialization. The UsingShadowDecl in D<T> then points directly
5930 // to A::foo, which will look well-formed when we instantiate.
5931 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005932 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005933 DeclContext *OrigDC = Orig->getDeclContext();
5934
5935 // Handle enums and anonymous structs.
5936 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5937 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5938 while (OrigRec->isAnonymousStructOrUnion())
5939 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5940
5941 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5942 if (OrigDC == CurContext) {
5943 Diag(Using->getLocation(),
5944 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005945 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005946 Diag(Orig->getLocation(), diag::note_using_decl_target);
5947 return true;
5948 }
5949
Douglas Gregordc355712011-02-25 00:36:19 +00005950 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005951 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005952 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005953 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005954 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005955 Diag(Orig->getLocation(), diag::note_using_decl_target);
5956 return true;
5957 }
5958 }
5959
5960 if (Previous.empty()) return false;
5961
5962 NamedDecl *Target = Orig;
5963 if (isa<UsingShadowDecl>(Target))
5964 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5965
John McCalld7533ec2009-12-11 02:33:26 +00005966 // If the target happens to be one of the previous declarations, we
5967 // don't have a conflict.
5968 //
5969 // FIXME: but we might be increasing its access, in which case we
5970 // should redeclare it.
5971 NamedDecl *NonTag = 0, *Tag = 0;
5972 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5973 I != E; ++I) {
5974 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005975 bool Result;
5976 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5977 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005978
5979 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5980 }
5981
John McCall9f54ad42009-12-10 09:41:52 +00005982 if (Target->isFunctionOrFunctionTemplate()) {
5983 FunctionDecl *FD;
5984 if (isa<FunctionTemplateDecl>(Target))
5985 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5986 else
5987 FD = cast<FunctionDecl>(Target);
5988
5989 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005990 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005991 case Ovl_Overload:
5992 return false;
5993
5994 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005995 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005996 break;
5997
5998 // We found a decl with the exact signature.
5999 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006000 // If we're in a record, we want to hide the target, so we
6001 // return true (without a diagnostic) to tell the caller not to
6002 // build a shadow decl.
6003 if (CurContext->isRecord())
6004 return true;
6005
6006 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006007 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006008 break;
6009 }
6010
6011 Diag(Target->getLocation(), diag::note_using_decl_target);
6012 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6013 return true;
6014 }
6015
6016 // Target is not a function.
6017
John McCall9f54ad42009-12-10 09:41:52 +00006018 if (isa<TagDecl>(Target)) {
6019 // No conflict between a tag and a non-tag.
6020 if (!Tag) return false;
6021
John McCall41ce66f2009-12-10 19:51:03 +00006022 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006023 Diag(Target->getLocation(), diag::note_using_decl_target);
6024 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6025 return true;
6026 }
6027
6028 // No conflict between a tag and a non-tag.
6029 if (!NonTag) return false;
6030
John McCall41ce66f2009-12-10 19:51:03 +00006031 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006032 Diag(Target->getLocation(), diag::note_using_decl_target);
6033 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6034 return true;
6035}
6036
John McCall9488ea12009-11-17 05:59:44 +00006037/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006038UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006039 UsingDecl *UD,
6040 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006041
6042 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006043 NamedDecl *Target = Orig;
6044 if (isa<UsingShadowDecl>(Target)) {
6045 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6046 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006047 }
6048
6049 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006050 = UsingShadowDecl::Create(Context, CurContext,
6051 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006052 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006053
6054 Shadow->setAccess(UD->getAccess());
6055 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6056 Shadow->setInvalidDecl();
6057
John McCall9488ea12009-11-17 05:59:44 +00006058 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006059 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006060 else
John McCall604e7f12009-12-08 07:46:18 +00006061 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006062
John McCall604e7f12009-12-08 07:46:18 +00006063
John McCall9f54ad42009-12-10 09:41:52 +00006064 return Shadow;
6065}
John McCall604e7f12009-12-08 07:46:18 +00006066
John McCall9f54ad42009-12-10 09:41:52 +00006067/// Hides a using shadow declaration. This is required by the current
6068/// using-decl implementation when a resolvable using declaration in a
6069/// class is followed by a declaration which would hide or override
6070/// one or more of the using decl's targets; for example:
6071///
6072/// struct Base { void foo(int); };
6073/// struct Derived : Base {
6074/// using Base::foo;
6075/// void foo(int);
6076/// };
6077///
6078/// The governing language is C++03 [namespace.udecl]p12:
6079///
6080/// When a using-declaration brings names from a base class into a
6081/// derived class scope, member functions in the derived class
6082/// override and/or hide member functions with the same name and
6083/// parameter types in a base class (rather than conflicting).
6084///
6085/// There are two ways to implement this:
6086/// (1) optimistically create shadow decls when they're not hidden
6087/// by existing declarations, or
6088/// (2) don't create any shadow decls (or at least don't make them
6089/// visible) until we've fully parsed/instantiated the class.
6090/// The problem with (1) is that we might have to retroactively remove
6091/// a shadow decl, which requires several O(n) operations because the
6092/// decl structures are (very reasonably) not designed for removal.
6093/// (2) avoids this but is very fiddly and phase-dependent.
6094void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006095 if (Shadow->getDeclName().getNameKind() ==
6096 DeclarationName::CXXConversionFunctionName)
6097 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6098
John McCall9f54ad42009-12-10 09:41:52 +00006099 // Remove it from the DeclContext...
6100 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006101
John McCall9f54ad42009-12-10 09:41:52 +00006102 // ...and the scope, if applicable...
6103 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006104 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006105 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006106 }
6107
John McCall9f54ad42009-12-10 09:41:52 +00006108 // ...and the using decl.
6109 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6110
6111 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006112 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006113}
6114
John McCall7ba107a2009-11-18 02:36:19 +00006115/// Builds a using declaration.
6116///
6117/// \param IsInstantiation - Whether this call arises from an
6118/// instantiation of an unresolved using declaration. We treat
6119/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006120NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6121 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006122 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006123 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006124 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006125 bool IsInstantiation,
6126 bool IsTypeName,
6127 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006128 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006129 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006130 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006131
Anders Carlsson550b14b2009-08-28 05:49:21 +00006132 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006133
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006134 if (SS.isEmpty()) {
6135 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006136 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006137 }
Mike Stump1eb44332009-09-09 15:08:12 +00006138
John McCall9f54ad42009-12-10 09:41:52 +00006139 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006140 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006141 ForRedeclaration);
6142 Previous.setHideTags(false);
6143 if (S) {
6144 LookupName(Previous, S);
6145
6146 // It is really dumb that we have to do this.
6147 LookupResult::Filter F = Previous.makeFilter();
6148 while (F.hasNext()) {
6149 NamedDecl *D = F.next();
6150 if (!isDeclInScope(D, CurContext, S))
6151 F.erase();
6152 }
6153 F.done();
6154 } else {
6155 assert(IsInstantiation && "no scope in non-instantiation");
6156 assert(CurContext->isRecord() && "scope not record in instantiation");
6157 LookupQualifiedName(Previous, CurContext);
6158 }
6159
John McCall9f54ad42009-12-10 09:41:52 +00006160 // Check for invalid redeclarations.
6161 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6162 return 0;
6163
6164 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006165 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6166 return 0;
6167
John McCallaf8e6ed2009-11-12 03:15:40 +00006168 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006169 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006170 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006171 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006172 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006173 // FIXME: not all declaration name kinds are legal here
6174 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6175 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006176 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006177 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006178 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006179 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6180 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006181 }
John McCalled976492009-12-04 22:46:56 +00006182 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006183 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6184 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006185 }
John McCalled976492009-12-04 22:46:56 +00006186 D->setAccess(AS);
6187 CurContext->addDecl(D);
6188
6189 if (!LookupContext) return D;
6190 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006191
John McCall77bb1aa2010-05-01 00:40:08 +00006192 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006193 UD->setInvalidDecl();
6194 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006195 }
6196
Richard Smithc5a89a12012-04-02 01:30:27 +00006197 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006198 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006199 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006200 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006201 return UD;
6202 }
6203
6204 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006205
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006206 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006207
John McCall604e7f12009-12-08 07:46:18 +00006208 // Unlike most lookups, we don't always want to hide tag
6209 // declarations: tag names are visible through the using declaration
6210 // even if hidden by ordinary names, *except* in a dependent context
6211 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006212 if (!IsInstantiation)
6213 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006214
John McCallb9abd8722012-04-07 03:04:20 +00006215 // For the purposes of this lookup, we have a base object type
6216 // equal to that of the current context.
6217 if (CurContext->isRecord()) {
6218 R.setBaseObjectType(
6219 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6220 }
6221
John McCalla24dc2e2009-11-17 02:14:36 +00006222 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006223
John McCallf36e02d2009-10-09 21:13:30 +00006224 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006225 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006226 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006227 UD->setInvalidDecl();
6228 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006229 }
6230
John McCalled976492009-12-04 22:46:56 +00006231 if (R.isAmbiguous()) {
6232 UD->setInvalidDecl();
6233 return UD;
6234 }
Mike Stump1eb44332009-09-09 15:08:12 +00006235
John McCall7ba107a2009-11-18 02:36:19 +00006236 if (IsTypeName) {
6237 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006238 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006239 Diag(IdentLoc, diag::err_using_typename_non_type);
6240 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6241 Diag((*I)->getUnderlyingDecl()->getLocation(),
6242 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006243 UD->setInvalidDecl();
6244 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006245 }
6246 } else {
6247 // If we asked for a non-typename and we got a type, error out,
6248 // but only if this is an instantiation of an unresolved using
6249 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006250 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006251 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6252 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006253 UD->setInvalidDecl();
6254 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006255 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006256 }
6257
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006258 // C++0x N2914 [namespace.udecl]p6:
6259 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006260 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006261 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6262 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006263 UD->setInvalidDecl();
6264 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006265 }
Mike Stump1eb44332009-09-09 15:08:12 +00006266
John McCall9f54ad42009-12-10 09:41:52 +00006267 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6268 if (!CheckUsingShadowDecl(UD, *I, Previous))
6269 BuildUsingShadowDecl(S, UD, *I);
6270 }
John McCall9488ea12009-11-17 05:59:44 +00006271
6272 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006273}
6274
Sebastian Redlf677ea32011-02-05 19:23:19 +00006275/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006276bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6277 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006278
Douglas Gregordc355712011-02-25 00:36:19 +00006279 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006280 assert(SourceType &&
6281 "Using decl naming constructor doesn't have type in scope spec.");
6282 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6283
6284 // Check whether the named type is a direct base class.
6285 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6286 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6287 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6288 BaseIt != BaseE; ++BaseIt) {
6289 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6290 if (CanonicalSourceType == BaseType)
6291 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006292 if (BaseIt->getType()->isDependentType())
6293 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006294 }
6295
6296 if (BaseIt == BaseE) {
6297 // Did not find SourceType in the bases.
6298 Diag(UD->getUsingLocation(),
6299 diag::err_using_decl_constructor_not_in_direct_base)
6300 << UD->getNameInfo().getSourceRange()
6301 << QualType(SourceType, 0) << TargetClass;
6302 return true;
6303 }
6304
Richard Smithc5a89a12012-04-02 01:30:27 +00006305 if (!CurContext->isDependentContext())
6306 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006307
6308 return false;
6309}
6310
John McCall9f54ad42009-12-10 09:41:52 +00006311/// Checks that the given using declaration is not an invalid
6312/// redeclaration. Note that this is checking only for the using decl
6313/// itself, not for any ill-formedness among the UsingShadowDecls.
6314bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6315 bool isTypeName,
6316 const CXXScopeSpec &SS,
6317 SourceLocation NameLoc,
6318 const LookupResult &Prev) {
6319 // C++03 [namespace.udecl]p8:
6320 // C++0x [namespace.udecl]p10:
6321 // A using-declaration is a declaration and can therefore be used
6322 // repeatedly where (and only where) multiple declarations are
6323 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006324 //
John McCall8a726212010-11-29 18:01:58 +00006325 // That's in non-member contexts.
6326 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006327 return false;
6328
6329 NestedNameSpecifier *Qual
6330 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6331
6332 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6333 NamedDecl *D = *I;
6334
6335 bool DTypename;
6336 NestedNameSpecifier *DQual;
6337 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6338 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006339 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006340 } else if (UnresolvedUsingValueDecl *UD
6341 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6342 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006343 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006344 } else if (UnresolvedUsingTypenameDecl *UD
6345 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6346 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006347 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006348 } else continue;
6349
6350 // using decls differ if one says 'typename' and the other doesn't.
6351 // FIXME: non-dependent using decls?
6352 if (isTypeName != DTypename) continue;
6353
6354 // using decls differ if they name different scopes (but note that
6355 // template instantiation can cause this check to trigger when it
6356 // didn't before instantiation).
6357 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6358 Context.getCanonicalNestedNameSpecifier(DQual))
6359 continue;
6360
6361 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006362 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006363 return true;
6364 }
6365
6366 return false;
6367}
6368
John McCall604e7f12009-12-08 07:46:18 +00006369
John McCalled976492009-12-04 22:46:56 +00006370/// Checks that the given nested-name qualifier used in a using decl
6371/// in the current context is appropriately related to the current
6372/// scope. If an error is found, diagnoses it and returns true.
6373bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6374 const CXXScopeSpec &SS,
6375 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006376 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006377
John McCall604e7f12009-12-08 07:46:18 +00006378 if (!CurContext->isRecord()) {
6379 // C++03 [namespace.udecl]p3:
6380 // C++0x [namespace.udecl]p8:
6381 // A using-declaration for a class member shall be a member-declaration.
6382
6383 // If we weren't able to compute a valid scope, it must be a
6384 // dependent class scope.
6385 if (!NamedContext || NamedContext->isRecord()) {
6386 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6387 << SS.getRange();
6388 return true;
6389 }
6390
6391 // Otherwise, everything is known to be fine.
6392 return false;
6393 }
6394
6395 // The current scope is a record.
6396
6397 // If the named context is dependent, we can't decide much.
6398 if (!NamedContext) {
6399 // FIXME: in C++0x, we can diagnose if we can prove that the
6400 // nested-name-specifier does not refer to a base class, which is
6401 // still possible in some cases.
6402
6403 // Otherwise we have to conservatively report that things might be
6404 // okay.
6405 return false;
6406 }
6407
6408 if (!NamedContext->isRecord()) {
6409 // Ideally this would point at the last name in the specifier,
6410 // but we don't have that level of source info.
6411 Diag(SS.getRange().getBegin(),
6412 diag::err_using_decl_nested_name_specifier_is_not_class)
6413 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6414 return true;
6415 }
6416
Douglas Gregor6fb07292010-12-21 07:41:49 +00006417 if (!NamedContext->isDependentContext() &&
6418 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6419 return true;
6420
David Blaikie4e4d0842012-03-11 07:00:24 +00006421 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006422 // C++0x [namespace.udecl]p3:
6423 // In a using-declaration used as a member-declaration, the
6424 // nested-name-specifier shall name a base class of the class
6425 // being defined.
6426
6427 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6428 cast<CXXRecordDecl>(NamedContext))) {
6429 if (CurContext == NamedContext) {
6430 Diag(NameLoc,
6431 diag::err_using_decl_nested_name_specifier_is_current_class)
6432 << SS.getRange();
6433 return true;
6434 }
6435
6436 Diag(SS.getRange().getBegin(),
6437 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6438 << (NestedNameSpecifier*) SS.getScopeRep()
6439 << cast<CXXRecordDecl>(CurContext)
6440 << SS.getRange();
6441 return true;
6442 }
6443
6444 return false;
6445 }
6446
6447 // C++03 [namespace.udecl]p4:
6448 // A using-declaration used as a member-declaration shall refer
6449 // to a member of a base class of the class being defined [etc.].
6450
6451 // Salient point: SS doesn't have to name a base class as long as
6452 // lookup only finds members from base classes. Therefore we can
6453 // diagnose here only if we can prove that that can't happen,
6454 // i.e. if the class hierarchies provably don't intersect.
6455
6456 // TODO: it would be nice if "definitely valid" results were cached
6457 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6458 // need to be repeated.
6459
6460 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006461 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006462
6463 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6464 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6465 Data->Bases.insert(Base);
6466 return true;
6467 }
6468
6469 bool hasDependentBases(const CXXRecordDecl *Class) {
6470 return !Class->forallBases(collect, this);
6471 }
6472
6473 /// Returns true if the base is dependent or is one of the
6474 /// accumulated base classes.
6475 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6476 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6477 return !Data->Bases.count(Base);
6478 }
6479
6480 bool mightShareBases(const CXXRecordDecl *Class) {
6481 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6482 }
6483 };
6484
6485 UserData Data;
6486
6487 // Returns false if we find a dependent base.
6488 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6489 return false;
6490
6491 // Returns false if the class has a dependent base or if it or one
6492 // of its bases is present in the base set of the current context.
6493 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6494 return false;
6495
6496 Diag(SS.getRange().getBegin(),
6497 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6498 << (NestedNameSpecifier*) SS.getScopeRep()
6499 << cast<CXXRecordDecl>(CurContext)
6500 << SS.getRange();
6501
6502 return true;
John McCalled976492009-12-04 22:46:56 +00006503}
6504
Richard Smith162e1c12011-04-15 14:24:37 +00006505Decl *Sema::ActOnAliasDeclaration(Scope *S,
6506 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006507 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006508 SourceLocation UsingLoc,
6509 UnqualifiedId &Name,
6510 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006511 // Skip up to the relevant declaration scope.
6512 while (S->getFlags() & Scope::TemplateParamScope)
6513 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006514 assert((S->getFlags() & Scope::DeclScope) &&
6515 "got alias-declaration outside of declaration scope");
6516
6517 if (Type.isInvalid())
6518 return 0;
6519
6520 bool Invalid = false;
6521 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6522 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006523 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006524
6525 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6526 return 0;
6527
6528 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006529 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006530 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006531 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6532 TInfo->getTypeLoc().getBeginLoc());
6533 }
Richard Smith162e1c12011-04-15 14:24:37 +00006534
6535 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6536 LookupName(Previous, S);
6537
6538 // Warn about shadowing the name of a template parameter.
6539 if (Previous.isSingleResult() &&
6540 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006541 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006542 Previous.clear();
6543 }
6544
6545 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6546 "name in alias declaration must be an identifier");
6547 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6548 Name.StartLocation,
6549 Name.Identifier, TInfo);
6550
6551 NewTD->setAccess(AS);
6552
6553 if (Invalid)
6554 NewTD->setInvalidDecl();
6555
Richard Smith3e4c6c42011-05-05 21:57:07 +00006556 CheckTypedefForVariablyModifiedType(S, NewTD);
6557 Invalid |= NewTD->isInvalidDecl();
6558
Richard Smith162e1c12011-04-15 14:24:37 +00006559 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006560
6561 NamedDecl *NewND;
6562 if (TemplateParamLists.size()) {
6563 TypeAliasTemplateDecl *OldDecl = 0;
6564 TemplateParameterList *OldTemplateParams = 0;
6565
6566 if (TemplateParamLists.size() != 1) {
6567 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6568 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6569 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6570 }
6571 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6572
6573 // Only consider previous declarations in the same scope.
6574 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6575 /*ExplicitInstantiationOrSpecialization*/false);
6576 if (!Previous.empty()) {
6577 Redeclaration = true;
6578
6579 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6580 if (!OldDecl && !Invalid) {
6581 Diag(UsingLoc, diag::err_redefinition_different_kind)
6582 << Name.Identifier;
6583
6584 NamedDecl *OldD = Previous.getRepresentativeDecl();
6585 if (OldD->getLocation().isValid())
6586 Diag(OldD->getLocation(), diag::note_previous_definition);
6587
6588 Invalid = true;
6589 }
6590
6591 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6592 if (TemplateParameterListsAreEqual(TemplateParams,
6593 OldDecl->getTemplateParameters(),
6594 /*Complain=*/true,
6595 TPL_TemplateMatch))
6596 OldTemplateParams = OldDecl->getTemplateParameters();
6597 else
6598 Invalid = true;
6599
6600 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6601 if (!Invalid &&
6602 !Context.hasSameType(OldTD->getUnderlyingType(),
6603 NewTD->getUnderlyingType())) {
6604 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6605 // but we can't reasonably accept it.
6606 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6607 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6608 if (OldTD->getLocation().isValid())
6609 Diag(OldTD->getLocation(), diag::note_previous_definition);
6610 Invalid = true;
6611 }
6612 }
6613 }
6614
6615 // Merge any previous default template arguments into our parameters,
6616 // and check the parameter list.
6617 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6618 TPC_TypeAliasTemplate))
6619 return 0;
6620
6621 TypeAliasTemplateDecl *NewDecl =
6622 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6623 Name.Identifier, TemplateParams,
6624 NewTD);
6625
6626 NewDecl->setAccess(AS);
6627
6628 if (Invalid)
6629 NewDecl->setInvalidDecl();
6630 else if (OldDecl)
6631 NewDecl->setPreviousDeclaration(OldDecl);
6632
6633 NewND = NewDecl;
6634 } else {
6635 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6636 NewND = NewTD;
6637 }
Richard Smith162e1c12011-04-15 14:24:37 +00006638
6639 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006640 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006641
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006642 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006643 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006644}
6645
John McCalld226f652010-08-21 09:40:31 +00006646Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006647 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006648 SourceLocation AliasLoc,
6649 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006650 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006651 SourceLocation IdentLoc,
6652 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006653
Anders Carlsson81c85c42009-03-28 23:53:49 +00006654 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006655 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6656 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006657
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006658 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006659 NamedDecl *PrevDecl
6660 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6661 ForRedeclaration);
6662 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6663 PrevDecl = 0;
6664
6665 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006666 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006667 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006668 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006669 // FIXME: At some point, we'll want to create the (redundant)
6670 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006671 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006672 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006673 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006674 }
Mike Stump1eb44332009-09-09 15:08:12 +00006675
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006676 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6677 diag::err_redefinition_different_kind;
6678 Diag(AliasLoc, DiagID) << Alias;
6679 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006680 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006681 }
6682
John McCalla24dc2e2009-11-17 02:14:36 +00006683 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006684 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006685
John McCallf36e02d2009-10-09 21:13:30 +00006686 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006687 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006688 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006689 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006690 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006691 }
Mike Stump1eb44332009-09-09 15:08:12 +00006692
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006693 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006694 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006695 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006696 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006697
John McCall3dbd3d52010-02-16 06:53:13 +00006698 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006699 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006700}
6701
Douglas Gregor39957dc2010-05-01 15:04:51 +00006702namespace {
6703 /// \brief Scoped object used to handle the state changes required in Sema
6704 /// to implicitly define the body of a C++ member function;
6705 class ImplicitlyDefinedFunctionScope {
6706 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006707 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006708
6709 public:
6710 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006711 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006712 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006713 S.PushFunctionScope();
6714 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6715 }
6716
6717 ~ImplicitlyDefinedFunctionScope() {
6718 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006719 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006720 }
6721 };
6722}
6723
Sean Hunt001cad92011-05-10 00:49:42 +00006724Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006725Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6726 CXXMethodDecl *MD) {
6727 CXXRecordDecl *ClassDecl = MD->getParent();
6728
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006729 // C++ [except.spec]p14:
6730 // An implicitly declared special member function (Clause 12) shall have an
6731 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006732 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006733 if (ClassDecl->isInvalidDecl())
6734 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006735
Sebastian Redl60618fa2011-03-12 11:50:43 +00006736 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006737 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6738 BEnd = ClassDecl->bases_end();
6739 B != BEnd; ++B) {
6740 if (B->isVirtual()) // Handled below.
6741 continue;
6742
Douglas Gregor18274032010-07-03 00:47:00 +00006743 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6744 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006745 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6746 // If this is a deleted function, add it anyway. This might be conformant
6747 // with the standard. This might not. I'm not sure. It might not matter.
6748 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006749 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006750 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006751 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006752
6753 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006754 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6755 BEnd = ClassDecl->vbases_end();
6756 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006759 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6760 // If this is a deleted function, add it anyway. This might be conformant
6761 // with the standard. This might not. I'm not sure. It might not matter.
6762 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006763 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006764 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006765 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006766
6767 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006768 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6769 FEnd = ClassDecl->field_end();
6770 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006771 if (F->hasInClassInitializer()) {
6772 if (Expr *E = F->getInClassInitializer())
6773 ExceptSpec.CalledExpr(E);
6774 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006775 // DR1351:
6776 // If the brace-or-equal-initializer of a non-static data member
6777 // invokes a defaulted default constructor of its class or of an
6778 // enclosing class in a potentially evaluated subexpression, the
6779 // program is ill-formed.
6780 //
6781 // This resolution is unworkable: the exception specification of the
6782 // default constructor can be needed in an unevaluated context, in
6783 // particular, in the operand of a noexcept-expression, and we can be
6784 // unable to compute an exception specification for an enclosed class.
6785 //
6786 // We do not allow an in-class initializer to require the evaluation
6787 // of the exception specification for any in-class initializer whose
6788 // definition is not lexically complete.
6789 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006790 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006791 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006792 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6793 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6794 // If this is a deleted function, add it anyway. This might be conformant
6795 // with the standard. This might not. I'm not sure. It might not matter.
6796 // In particular, the problem is that this function never gets called. It
6797 // might just be ill-formed because this function attempts to refer to
6798 // a deleted function here.
6799 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006800 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006801 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006802 }
John McCalle23cf432010-12-14 08:05:40 +00006803
Sean Hunt001cad92011-05-10 00:49:42 +00006804 return ExceptSpec;
6805}
6806
6807CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6808 CXXRecordDecl *ClassDecl) {
6809 // C++ [class.ctor]p5:
6810 // A default constructor for a class X is a constructor of class X
6811 // that can be called without an argument. If there is no
6812 // user-declared constructor for class X, a default constructor is
6813 // implicitly declared. An implicitly-declared default constructor
6814 // is an inline public member of its class.
6815 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6816 "Should not build implicit default constructor!");
6817
Richard Smith7756afa2012-06-10 05:43:50 +00006818 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6819 CXXDefaultConstructor,
6820 false);
6821
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006822 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006823 CanQualType ClassType
6824 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006825 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006826 DeclarationName Name
6827 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006828 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006829 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006830 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006831 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006832 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006833 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006834 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006835 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006836 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006837
6838 // Build an exception specification pointing back at this constructor.
6839 FunctionProtoType::ExtProtoInfo EPI;
6840 EPI.ExceptionSpecType = EST_Unevaluated;
6841 EPI.ExceptionSpecDecl = DefaultCon;
6842 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6843
Douglas Gregor18274032010-07-03 00:47:00 +00006844 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006845 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6846
Douglas Gregor23c94db2010-07-02 17:43:08 +00006847 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006848 PushOnScopeChains(DefaultCon, S, false);
6849 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006850
Sean Hunte16da072011-10-10 06:18:57 +00006851 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006852 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006853
Douglas Gregor32df23e2010-07-01 22:02:46 +00006854 return DefaultCon;
6855}
6856
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006857void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6858 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006859 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006860 !Constructor->doesThisDeclarationHaveABody() &&
6861 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006862 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006863
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006864 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006865 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006866
Douglas Gregor39957dc2010-05-01 15:04:51 +00006867 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006868 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006869 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006870 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006871 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006872 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006873 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006874 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006875 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006876
6877 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006878 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006879
6880 Constructor->setUsed();
6881 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006882
6883 if (ASTMutationListener *L = getASTMutationListener()) {
6884 L->CompletedImplicitDefinition(Constructor);
6885 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006886}
6887
Richard Smith7a614d82011-06-11 17:19:42 +00006888void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6889 if (!D) return;
6890 AdjustDeclIfTemplate(D);
6891
6892 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006893
Richard Smithb9d0b762012-07-27 04:22:15 +00006894 if (!ClassDecl->isDependentType())
6895 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006896}
6897
Sebastian Redlf677ea32011-02-05 19:23:19 +00006898void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6899 // We start with an initial pass over the base classes to collect those that
6900 // inherit constructors from. If there are none, we can forgo all further
6901 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006902 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006903 BasesVector BasesToInheritFrom;
6904 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6905 BaseE = ClassDecl->bases_end();
6906 BaseIt != BaseE; ++BaseIt) {
6907 if (BaseIt->getInheritConstructors()) {
6908 QualType Base = BaseIt->getType();
6909 if (Base->isDependentType()) {
6910 // If we inherit constructors from anything that is dependent, just
6911 // abort processing altogether. We'll get another chance for the
6912 // instantiations.
6913 return;
6914 }
6915 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6916 }
6917 }
6918 if (BasesToInheritFrom.empty())
6919 return;
6920
6921 // Now collect the constructors that we already have in the current class.
6922 // Those take precedence over inherited constructors.
6923 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6924 // unless there is a user-declared constructor with the same signature in
6925 // the class where the using-declaration appears.
6926 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6927 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6928 CtorE = ClassDecl->ctor_end();
6929 CtorIt != CtorE; ++CtorIt) {
6930 ExistingConstructors.insert(
6931 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6932 }
6933
Sebastian Redlf677ea32011-02-05 19:23:19 +00006934 DeclarationName CreatedCtorName =
6935 Context.DeclarationNames.getCXXConstructorName(
6936 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6937
6938 // Now comes the true work.
6939 // First, we keep a map from constructor types to the base that introduced
6940 // them. Needed for finding conflicting constructors. We also keep the
6941 // actually inserted declarations in there, for pretty diagnostics.
6942 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6943 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6944 ConstructorToSourceMap InheritedConstructors;
6945 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6946 BaseE = BasesToInheritFrom.end();
6947 BaseIt != BaseE; ++BaseIt) {
6948 const RecordType *Base = *BaseIt;
6949 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6950 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6951 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6952 CtorE = BaseDecl->ctor_end();
6953 CtorIt != CtorE; ++CtorIt) {
6954 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006955 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006956 DeclarationName Name =
6957 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006958 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6959 LookupQualifiedName(Result, CurContext);
6960 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006961 SourceLocation UsingLoc = UD ? UD->getLocation() :
6962 ClassDecl->getLocation();
6963
6964 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6965 // from the class X named in the using-declaration consists of actual
6966 // constructors and notional constructors that result from the
6967 // transformation of defaulted parameters as follows:
6968 // - all non-template default constructors of X, and
6969 // - for each non-template constructor of X that has at least one
6970 // parameter with a default argument, the set of constructors that
6971 // results from omitting any ellipsis parameter specification and
6972 // successively omitting parameters with a default argument from the
6973 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006974 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006975 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6976 const FunctionProtoType *BaseCtorType =
6977 BaseCtor->getType()->getAs<FunctionProtoType>();
6978
6979 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6980 maxParams = BaseCtor->getNumParams();
6981 params <= maxParams; ++params) {
6982 // Skip default constructors. They're never inherited.
6983 if (params == 0)
6984 continue;
6985 // Skip copy and move constructors for the same reason.
6986 if (CanBeCopyOrMove && params == 1)
6987 continue;
6988
6989 // Build up a function type for this particular constructor.
6990 // FIXME: The working paper does not consider that the exception spec
6991 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006992 // source. This code doesn't yet, either. When it does, this code will
6993 // need to be delayed until after exception specifications and in-class
6994 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006995 const Type *NewCtorType;
6996 if (params == maxParams)
6997 NewCtorType = BaseCtorType;
6998 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006999 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007000 for (unsigned i = 0; i < params; ++i) {
7001 Args.push_back(BaseCtorType->getArgType(i));
7002 }
7003 FunctionProtoType::ExtProtoInfo ExtInfo =
7004 BaseCtorType->getExtProtoInfo();
7005 ExtInfo.Variadic = false;
7006 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7007 Args.data(), params, ExtInfo)
7008 .getTypePtr();
7009 }
7010 const Type *CanonicalNewCtorType =
7011 Context.getCanonicalType(NewCtorType);
7012
7013 // Now that we have the type, first check if the class already has a
7014 // constructor with this signature.
7015 if (ExistingConstructors.count(CanonicalNewCtorType))
7016 continue;
7017
7018 // Then we check if we have already declared an inherited constructor
7019 // with this signature.
7020 std::pair<ConstructorToSourceMap::iterator, bool> result =
7021 InheritedConstructors.insert(std::make_pair(
7022 CanonicalNewCtorType,
7023 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7024 if (!result.second) {
7025 // Already in the map. If it came from a different class, that's an
7026 // error. Not if it's from the same.
7027 CanQualType PreviousBase = result.first->second.first;
7028 if (CanonicalBase != PreviousBase) {
7029 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7030 const CXXConstructorDecl *PrevBaseCtor =
7031 PrevCtor->getInheritedConstructor();
7032 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7033
7034 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7035 Diag(BaseCtor->getLocation(),
7036 diag::note_using_decl_constructor_conflict_current_ctor);
7037 Diag(PrevBaseCtor->getLocation(),
7038 diag::note_using_decl_constructor_conflict_previous_ctor);
7039 Diag(PrevCtor->getLocation(),
7040 diag::note_using_decl_constructor_conflict_previous_using);
7041 }
7042 continue;
7043 }
7044
7045 // OK, we're there, now add the constructor.
7046 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007047 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007048 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7049 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007050 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7051 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007052 /*ImplicitlyDeclared=*/true,
7053 // FIXME: Due to a defect in the standard, we treat inherited
7054 // constructors as constexpr even if that makes them ill-formed.
7055 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007056 NewCtor->setAccess(BaseCtor->getAccess());
7057
7058 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007059 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007060 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007061 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7062 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007063 /*IdentifierInfo=*/0,
7064 BaseCtorType->getArgType(i),
7065 /*TInfo=*/0, SC_None,
7066 SC_None, /*DefaultArg=*/0));
7067 }
David Blaikie4278c652011-09-21 18:16:56 +00007068 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007069 NewCtor->setInheritedConstructor(BaseCtor);
7070
Sebastian Redlf677ea32011-02-05 19:23:19 +00007071 ClassDecl->addDecl(NewCtor);
7072 result.first->second.second = NewCtor;
7073 }
7074 }
7075 }
7076}
7077
Sean Huntcb45a0f2011-05-12 22:46:25 +00007078Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007079Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7080 CXXRecordDecl *ClassDecl = MD->getParent();
7081
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007082 // C++ [except.spec]p14:
7083 // An implicitly declared special member function (Clause 12) shall have
7084 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007085 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007086 if (ClassDecl->isInvalidDecl())
7087 return ExceptSpec;
7088
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007089 // Direct base-class destructors.
7090 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7091 BEnd = ClassDecl->bases_end();
7092 B != BEnd; ++B) {
7093 if (B->isVirtual()) // Handled below.
7094 continue;
7095
7096 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007097 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007098 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007099 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007100
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007101 // Virtual base-class destructors.
7102 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7103 BEnd = ClassDecl->vbases_end();
7104 B != BEnd; ++B) {
7105 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007106 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007107 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007108 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007109
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007110 // Field destructors.
7111 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7112 FEnd = ClassDecl->field_end();
7113 F != FEnd; ++F) {
7114 if (const RecordType *RecordTy
7115 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007116 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007117 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007118 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007119
Sean Huntcb45a0f2011-05-12 22:46:25 +00007120 return ExceptSpec;
7121}
7122
7123CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7124 // C++ [class.dtor]p2:
7125 // If a class has no user-declared destructor, a destructor is
7126 // declared implicitly. An implicitly-declared destructor is an
7127 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007128
Douglas Gregor4923aa22010-07-02 20:37:36 +00007129 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007130 CanQualType ClassType
7131 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007132 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007133 DeclarationName Name
7134 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007135 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007136 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007137 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7138 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007139 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007140 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007141 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007142 Destructor->setImplicit();
7143 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007144
7145 // Build an exception specification pointing back at this destructor.
7146 FunctionProtoType::ExtProtoInfo EPI;
7147 EPI.ExceptionSpecType = EST_Unevaluated;
7148 EPI.ExceptionSpecDecl = Destructor;
7149 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7150
Douglas Gregor4923aa22010-07-02 20:37:36 +00007151 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007152 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007153
Douglas Gregor4923aa22010-07-02 20:37:36 +00007154 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007155 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007156 PushOnScopeChains(Destructor, S, false);
7157 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007158
Richard Smith9a561d52012-02-26 09:11:52 +00007159 AddOverriddenMethods(ClassDecl, Destructor);
7160
Richard Smith7d5088a2012-02-18 02:02:13 +00007161 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007162 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007163
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007164 return Destructor;
7165}
7166
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007167void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007168 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007169 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007170 !Destructor->doesThisDeclarationHaveABody() &&
7171 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007172 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007173 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007174 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007175
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007176 if (Destructor->isInvalidDecl())
7177 return;
7178
Douglas Gregor39957dc2010-05-01 15:04:51 +00007179 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007180
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007181 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007182 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7183 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007184
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007185 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007186 Diag(CurrentLocation, diag::note_member_synthesized_at)
7187 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7188
7189 Destructor->setInvalidDecl();
7190 return;
7191 }
7192
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007193 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007194 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007195 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007196 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007197 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007198
7199 if (ASTMutationListener *L = getASTMutationListener()) {
7200 L->CompletedImplicitDefinition(Destructor);
7201 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007202}
7203
Richard Smitha4156b82012-04-21 18:42:51 +00007204/// \brief Perform any semantic analysis which needs to be delayed until all
7205/// pending class member declarations have been parsed.
7206void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007207 // Perform any deferred checking of exception specifications for virtual
7208 // destructors.
7209 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7210 i != e; ++i) {
7211 const CXXDestructorDecl *Dtor =
7212 DelayedDestructorExceptionSpecChecks[i].first;
7213 assert(!Dtor->getParent()->isDependentType() &&
7214 "Should not ever add destructors of templates into the list.");
7215 CheckOverridingFunctionExceptionSpec(Dtor,
7216 DelayedDestructorExceptionSpecChecks[i].second);
7217 }
7218 DelayedDestructorExceptionSpecChecks.clear();
7219}
7220
Richard Smithb9d0b762012-07-27 04:22:15 +00007221void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7222 CXXDestructorDecl *Destructor) {
7223 assert(getLangOpts().CPlusPlus0x &&
7224 "adjusting dtor exception specs was introduced in c++11");
7225
Sebastian Redl0ee33912011-05-19 05:13:44 +00007226 // C++11 [class.dtor]p3:
7227 // A declaration of a destructor that does not have an exception-
7228 // specification is implicitly considered to have the same exception-
7229 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007230 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007231 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007232 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007233 return;
7234
Chandler Carruth3f224b22011-09-20 04:55:26 +00007235 // Replace the destructor's type, building off the existing one. Fortunately,
7236 // the only thing of interest in the destructor type is its extended info.
7237 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007238 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7239 EPI.ExceptionSpecType = EST_Unevaluated;
7240 EPI.ExceptionSpecDecl = Destructor;
7241 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007242
Sebastian Redl0ee33912011-05-19 05:13:44 +00007243 // FIXME: If the destructor has a body that could throw, and the newly created
7244 // spec doesn't allow exceptions, we should emit a warning, because this
7245 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007246 // However, we don't have a body or an exception specification yet, so it
7247 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007248}
7249
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007250/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007251/// \c To.
7252///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007253/// This routine is used to copy/move the members of a class with an
7254/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007255/// copied are arrays, this routine builds for loops to copy them.
7256///
7257/// \param S The Sema object used for type-checking.
7258///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007259/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007260///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007261/// \param T The type of the expressions being copied/moved. Both expressions
7262/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007263///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007264/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007265///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007266/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007267///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007268/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007269/// Otherwise, it's a non-static member subobject.
7270///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007271/// \param Copying Whether we're copying or moving.
7272///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007273/// \param Depth Internal parameter recording the depth of the recursion.
7274///
7275/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007276static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007277BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007278 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007279 bool CopyingBaseSubobject, bool Copying,
7280 unsigned Depth = 0) {
7281 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007282 // Each subobject is assigned in the manner appropriate to its type:
7283 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007284 // - if the subobject is of class type, as if by a call to operator= with
7285 // the subobject as the object expression and the corresponding
7286 // subobject of x as a single function argument (as if by explicit
7287 // qualification; that is, ignoring any possible virtual overriding
7288 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007289 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7290 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7291
7292 // Look for operator=.
7293 DeclarationName Name
7294 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7295 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7296 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7297
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007298 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007299 LookupResult::Filter F = OpLookup.makeFilter();
7300 while (F.hasNext()) {
7301 NamedDecl *D = F.next();
7302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007303 if (Method->isCopyAssignmentOperator() ||
7304 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007305 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007306
Douglas Gregor06a9f362010-05-01 20:49:11 +00007307 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007308 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007309 F.done();
7310
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007311 // Suppress the protected check (C++ [class.protected]) for each of the
7312 // assignment operators we found. This strange dance is required when
7313 // we're assigning via a base classes's copy-assignment operator. To
7314 // ensure that we're getting the right base class subobject (without
7315 // ambiguities), we need to cast "this" to that subobject type; to
7316 // ensure that we don't go through the virtual call mechanism, we need
7317 // to qualify the operator= name with the base class (see below). However,
7318 // this means that if the base class has a protected copy assignment
7319 // operator, the protected member access check will fail. So, we
7320 // rewrite "protected" access to "public" access in this case, since we
7321 // know by construction that we're calling from a derived class.
7322 if (CopyingBaseSubobject) {
7323 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7324 L != LEnd; ++L) {
7325 if (L.getAccess() == AS_protected)
7326 L.setAccess(AS_public);
7327 }
7328 }
7329
Douglas Gregor06a9f362010-05-01 20:49:11 +00007330 // Create the nested-name-specifier that will be used to qualify the
7331 // reference to operator=; this is required to suppress the virtual
7332 // call mechanism.
7333 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007334 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007335 SS.MakeTrivial(S.Context,
7336 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007337 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007338 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007339
7340 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007341 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007342 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007343 /*TemplateKWLoc=*/SourceLocation(),
7344 /*FirstQualifierInScope=*/0,
7345 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007346 /*TemplateArgs=*/0,
7347 /*SuppressQualifierCheck=*/true);
7348 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007349 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007350
7351 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007352
John McCall60d7b3a2010-08-24 06:29:42 +00007353 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007354 OpEqualRef.takeAs<Expr>(),
7355 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007356 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007357 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007358
7359 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007360 }
John McCallb0207482010-03-16 06:11:48 +00007361
Douglas Gregor06a9f362010-05-01 20:49:11 +00007362 // - if the subobject is of scalar type, the built-in assignment
7363 // operator is used.
7364 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7365 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007366 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007367 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007368 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007369
7370 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007371 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007372
7373 // - if the subobject is an array, each element is assigned, in the
7374 // manner appropriate to the element type;
7375
7376 // Construct a loop over the array bounds, e.g.,
7377 //
7378 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7379 //
7380 // that will copy each of the array elements.
7381 QualType SizeType = S.Context.getSizeType();
7382
7383 // Create the iteration variable.
7384 IdentifierInfo *IterationVarName = 0;
7385 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007386 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007387 llvm::raw_svector_ostream OS(Str);
7388 OS << "__i" << Depth;
7389 IterationVarName = &S.Context.Idents.get(OS.str());
7390 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007391 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007392 IterationVarName, SizeType,
7393 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007394 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007395
7396 // Initialize the iteration variable to zero.
7397 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007398 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007399
7400 // Create a reference to the iteration variable; we'll use this several
7401 // times throughout.
7402 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007403 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007404 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007405 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7406 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7407
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408 // Create the DeclStmt that holds the iteration variable.
7409 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7410
7411 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007412 llvm::APInt Upper
7413 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007414 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007415 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007416 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7417 BO_NE, S.Context.BoolTy,
7418 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007419
7420 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007421 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007422 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7423 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007424
7425 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007426 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007427 IterationVarRefRVal,
7428 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007429 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007430 IterationVarRefRVal,
7431 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007432 if (!Copying) // Cast to rvalue
7433 From = CastForMoving(S, From);
7434
7435 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007436 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7437 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007438 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007439 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007440 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007441
7442 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007443 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007444 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007445 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007446 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007447}
7448
Richard Smithb9d0b762012-07-27 04:22:15 +00007449/// Determine whether an implicit copy assignment operator for ClassDecl has a
7450/// const argument.
7451/// FIXME: It ought to be possible to store this on the record.
7452static bool isImplicitCopyAssignmentArgConst(Sema &S,
7453 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007454 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007455 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007456
Douglas Gregord3c35902010-07-01 16:36:15 +00007457 // C++ [class.copy]p10:
7458 // If the class definition does not explicitly declare a copy
7459 // assignment operator, one is declared implicitly.
7460 // The implicitly-defined copy assignment operator for a class X
7461 // will have the form
7462 //
7463 // X& X::operator=(const X&)
7464 //
7465 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007466 // -- each direct base class B of X has a copy assignment operator
7467 // whose parameter is of type const B&, const volatile B& or B,
7468 // and
7469 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7470 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007471 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007472 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007473 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007474 continue;
7475
Douglas Gregord3c35902010-07-01 16:36:15 +00007476 assert(!Base->getType()->isDependentType() &&
7477 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007478 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007479 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7480 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007481 }
7482
Richard Smithebaf0e62011-10-18 20:49:44 +00007483 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007484 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007485 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7486 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007487 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007488 assert(!Base->getType()->isDependentType() &&
7489 "Cannot generate implicit members for class with dependent bases.");
7490 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007491 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7492 false, 0))
7493 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007494 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007495 }
7496
7497 // -- for all the nonstatic data members of X that are of a class
7498 // type M (or array thereof), each such class type has a copy
7499 // assignment operator whose parameter is of type const M&,
7500 // const volatile M& or M.
7501 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7502 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007503 Field != FieldEnd; ++Field) {
7504 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7505 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7506 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7507 false, 0))
7508 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007509 }
7510
7511 // Otherwise, the implicitly declared copy assignment operator will
7512 // have the form
7513 //
7514 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007515
7516 return true;
7517}
7518
7519Sema::ImplicitExceptionSpecification
7520Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7521 CXXRecordDecl *ClassDecl = MD->getParent();
7522
7523 ImplicitExceptionSpecification ExceptSpec(*this);
7524 if (ClassDecl->isInvalidDecl())
7525 return ExceptSpec;
7526
7527 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7528 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7529 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7530
Douglas Gregorb87786f2010-07-01 17:48:08 +00007531 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007532 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007533 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007534
7535 // It is unspecified whether or not an implicit copy assignment operator
7536 // attempts to deduplicate calls to assignment operators of virtual bases are
7537 // made. As such, this exception specification is effectively unspecified.
7538 // Based on a similar decision made for constness in C++0x, we're erring on
7539 // the side of assuming such calls to be made regardless of whether they
7540 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007541 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7542 BaseEnd = ClassDecl->bases_end();
7543 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007544 if (Base->isVirtual())
7545 continue;
7546
Douglas Gregora376d102010-07-02 21:50:04 +00007547 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007548 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007549 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7550 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007551 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007552 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007553
7554 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7555 BaseEnd = ClassDecl->vbases_end();
7556 Base != BaseEnd; ++Base) {
7557 CXXRecordDecl *BaseClassDecl
7558 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7559 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7560 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007561 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007562 }
7563
Douglas Gregorb87786f2010-07-01 17:48:08 +00007564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7565 FieldEnd = ClassDecl->field_end();
7566 Field != FieldEnd;
7567 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007568 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007569 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7570 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007571 LookupCopyingAssignment(FieldClassDecl,
7572 ArgQuals | FieldType.getCVRQualifiers(),
7573 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007574 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007575 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007576 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007577
Richard Smithb9d0b762012-07-27 04:22:15 +00007578 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007579}
7580
7581CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7582 // Note: The following rules are largely analoguous to the copy
7583 // constructor rules. Note that virtual bases are not taken into account
7584 // for determining the argument type of the operator. Note also that
7585 // operators taking an object instead of a reference are allowed.
7586
Sean Hunt30de05c2011-05-14 05:23:20 +00007587 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7588 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007589 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007590 ArgType = ArgType.withConst();
7591 ArgType = Context.getLValueReferenceType(ArgType);
7592
Douglas Gregord3c35902010-07-01 16:36:15 +00007593 // An implicitly-declared copy assignment operator is an inline public
7594 // member of its class.
7595 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007596 SourceLocation ClassLoc = ClassDecl->getLocation();
7597 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007598 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007599 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007600 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007601 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007602 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007603 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007604 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007605 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007606 CopyAssignment->setImplicit();
7607 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007608
7609 // Build an exception specification pointing back at this member.
7610 FunctionProtoType::ExtProtoInfo EPI;
7611 EPI.ExceptionSpecType = EST_Unevaluated;
7612 EPI.ExceptionSpecDecl = CopyAssignment;
7613 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7614
Douglas Gregord3c35902010-07-01 16:36:15 +00007615 // Add the parameter to the operator.
7616 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007617 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007618 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007619 SC_None,
7620 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007621 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007622
Douglas Gregora376d102010-07-02 21:50:04 +00007623 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007624 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007625
Douglas Gregor23c94db2010-07-02 17:43:08 +00007626 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007627 PushOnScopeChains(CopyAssignment, S, false);
7628 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007629
Nico Weberafcc96a2012-01-23 03:19:29 +00007630 // C++0x [class.copy]p19:
7631 // .... If the class definition does not explicitly declare a copy
7632 // assignment operator, there is no user-declared move constructor, and
7633 // there is no user-declared move assignment operator, a copy assignment
7634 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007635 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007636 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007637
Douglas Gregord3c35902010-07-01 16:36:15 +00007638 AddOverriddenMethods(ClassDecl, CopyAssignment);
7639 return CopyAssignment;
7640}
7641
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7643 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007644 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007645 CopyAssignOperator->isOverloadedOperator() &&
7646 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007647 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7648 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007649 "DefineImplicitCopyAssignment called for wrong function");
7650
7651 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7652
7653 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7654 CopyAssignOperator->setInvalidDecl();
7655 return;
7656 }
7657
7658 CopyAssignOperator->setUsed();
7659
7660 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007661 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007662
7663 // C++0x [class.copy]p30:
7664 // The implicitly-defined or explicitly-defaulted copy assignment operator
7665 // for a non-union class X performs memberwise copy assignment of its
7666 // subobjects. The direct base classes of X are assigned first, in the
7667 // order of their declaration in the base-specifier-list, and then the
7668 // immediate non-static data members of X are assigned, in the order in
7669 // which they were declared in the class definition.
7670
7671 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007672 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673
7674 // The parameter for the "other" object, which we are copying from.
7675 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7676 Qualifiers OtherQuals = Other->getType().getQualifiers();
7677 QualType OtherRefType = Other->getType();
7678 if (const LValueReferenceType *OtherRef
7679 = OtherRefType->getAs<LValueReferenceType>()) {
7680 OtherRefType = OtherRef->getPointeeType();
7681 OtherQuals = OtherRefType.getQualifiers();
7682 }
7683
7684 // Our location for everything implicitly-generated.
7685 SourceLocation Loc = CopyAssignOperator->getLocation();
7686
7687 // Construct a reference to the "other" object. We'll be using this
7688 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007689 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007690 assert(OtherRef && "Reference to parameter cannot fail!");
7691
7692 // Construct the "this" pointer. We'll be using this throughout the generated
7693 // ASTs.
7694 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7695 assert(This && "Reference to this cannot fail!");
7696
7697 // Assign base classes.
7698 bool Invalid = false;
7699 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7700 E = ClassDecl->bases_end(); Base != E; ++Base) {
7701 // Form the assignment:
7702 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7703 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007704 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007705 Invalid = true;
7706 continue;
7707 }
7708
John McCallf871d0c2010-08-07 06:22:56 +00007709 CXXCastPath BasePath;
7710 BasePath.push_back(Base);
7711
Douglas Gregor06a9f362010-05-01 20:49:11 +00007712 // Construct the "from" expression, which is an implicit cast to the
7713 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007714 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007715 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7716 CK_UncheckedDerivedToBase,
7717 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007718
7719 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007720 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007721
7722 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007723 To = ImpCastExprToType(To.take(),
7724 Context.getCVRQualifiedType(BaseType,
7725 CopyAssignOperator->getTypeQualifiers()),
7726 CK_UncheckedDerivedToBase,
7727 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007728
7729 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007730 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007731 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007732 /*CopyingBaseSubobject=*/true,
7733 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007734 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007735 Diag(CurrentLocation, diag::note_member_synthesized_at)
7736 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7737 CopyAssignOperator->setInvalidDecl();
7738 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007739 }
7740
7741 // Success! Record the copy.
7742 Statements.push_back(Copy.takeAs<Expr>());
7743 }
7744
7745 // \brief Reference to the __builtin_memcpy function.
7746 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007747 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007748 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007749
7750 // Assign non-static members.
7751 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7752 FieldEnd = ClassDecl->field_end();
7753 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007754 if (Field->isUnnamedBitfield())
7755 continue;
7756
Douglas Gregor06a9f362010-05-01 20:49:11 +00007757 // Check for members of reference type; we can't copy those.
7758 if (Field->getType()->isReferenceType()) {
7759 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7760 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7761 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007762 Diag(CurrentLocation, diag::note_member_synthesized_at)
7763 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007764 Invalid = true;
7765 continue;
7766 }
7767
7768 // Check for members of const-qualified, non-class type.
7769 QualType BaseType = Context.getBaseElementType(Field->getType());
7770 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7771 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7772 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7773 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007774 Diag(CurrentLocation, diag::note_member_synthesized_at)
7775 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007776 Invalid = true;
7777 continue;
7778 }
John McCallb77115d2011-06-17 00:18:42 +00007779
7780 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007781 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7782 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007783
7784 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007785 if (FieldType->isIncompleteArrayType()) {
7786 assert(ClassDecl->hasFlexibleArrayMember() &&
7787 "Incomplete array type is not valid");
7788 continue;
7789 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007790
7791 // Build references to the field in the object we're copying from and to.
7792 CXXScopeSpec SS; // Intentionally empty
7793 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7794 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007795 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007796 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007797 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007798 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007799 SS, SourceLocation(), 0,
7800 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007801 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007802 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007803 SS, SourceLocation(), 0,
7804 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007805 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7806 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7807
7808 // If the field should be copied with __builtin_memcpy rather than via
7809 // explicit assignments, do so. This optimization only applies for arrays
7810 // of scalars and arrays of class type with trivial copy-assignment
7811 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007812 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007813 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007814 // Compute the size of the memory buffer to be copied.
7815 QualType SizeType = Context.getSizeType();
7816 llvm::APInt Size(Context.getTypeSize(SizeType),
7817 Context.getTypeSizeInChars(BaseType).getQuantity());
7818 for (const ConstantArrayType *Array
7819 = Context.getAsConstantArrayType(FieldType);
7820 Array;
7821 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007822 llvm::APInt ArraySize
7823 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007824 Size *= ArraySize;
7825 }
7826
7827 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007828 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7829 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007830
7831 bool NeedsCollectableMemCpy =
7832 (BaseType->isRecordType() &&
7833 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7834
7835 if (NeedsCollectableMemCpy) {
7836 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007837 // Create a reference to the __builtin_objc_memmove_collectable function.
7838 LookupResult R(*this,
7839 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007840 Loc, LookupOrdinaryName);
7841 LookupName(R, TUScope, true);
7842
7843 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7844 if (!CollectableMemCpy) {
7845 // Something went horribly wrong earlier, and we will have
7846 // complained about it.
7847 Invalid = true;
7848 continue;
7849 }
7850
7851 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7852 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007853 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007854 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7855 }
7856 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007857 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007858 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007859 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7860 LookupOrdinaryName);
7861 LookupName(R, TUScope, true);
7862
7863 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7864 if (!BuiltinMemCpy) {
7865 // Something went horribly wrong earlier, and we will have complained
7866 // about it.
7867 Invalid = true;
7868 continue;
7869 }
7870
7871 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7872 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007873 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007874 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7875 }
7876
John McCallca0408f2010-08-23 06:44:23 +00007877 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007878 CallArgs.push_back(To.takeAs<Expr>());
7879 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007880 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007881 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007882 if (NeedsCollectableMemCpy)
7883 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007884 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007885 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007886 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007887 else
7888 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007889 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007890 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007891 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007892
Douglas Gregor06a9f362010-05-01 20:49:11 +00007893 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7894 Statements.push_back(Call.takeAs<Expr>());
7895 continue;
7896 }
7897
7898 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007899 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007900 To.get(), From.get(),
7901 /*CopyingBaseSubobject=*/false,
7902 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007903 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007904 Diag(CurrentLocation, diag::note_member_synthesized_at)
7905 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7906 CopyAssignOperator->setInvalidDecl();
7907 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007908 }
7909
7910 // Success! Record the copy.
7911 Statements.push_back(Copy.takeAs<Stmt>());
7912 }
7913
7914 if (!Invalid) {
7915 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007916 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007917
John McCall60d7b3a2010-08-24 06:29:42 +00007918 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007919 if (Return.isInvalid())
7920 Invalid = true;
7921 else {
7922 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007923
7924 if (Trap.hasErrorOccurred()) {
7925 Diag(CurrentLocation, diag::note_member_synthesized_at)
7926 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7927 Invalid = true;
7928 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007929 }
7930 }
7931
7932 if (Invalid) {
7933 CopyAssignOperator->setInvalidDecl();
7934 return;
7935 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007936
7937 StmtResult Body;
7938 {
7939 CompoundScopeRAII CompoundScope(*this);
7940 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7941 /*isStmtExpr=*/false);
7942 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7943 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007944 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007945
7946 if (ASTMutationListener *L = getASTMutationListener()) {
7947 L->CompletedImplicitDefinition(CopyAssignOperator);
7948 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007949}
7950
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007951Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007952Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7953 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007954
Richard Smithb9d0b762012-07-27 04:22:15 +00007955 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007956 if (ClassDecl->isInvalidDecl())
7957 return ExceptSpec;
7958
7959 // C++0x [except.spec]p14:
7960 // An implicitly declared special member function (Clause 12) shall have an
7961 // exception-specification. [...]
7962
7963 // It is unspecified whether or not an implicit move assignment operator
7964 // attempts to deduplicate calls to assignment operators of virtual bases are
7965 // made. As such, this exception specification is effectively unspecified.
7966 // Based on a similar decision made for constness in C++0x, we're erring on
7967 // the side of assuming such calls to be made regardless of whether they
7968 // actually happen.
7969 // Note that a move constructor is not implicitly declared when there are
7970 // virtual bases, but it can still be user-declared and explicitly defaulted.
7971 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7972 BaseEnd = ClassDecl->bases_end();
7973 Base != BaseEnd; ++Base) {
7974 if (Base->isVirtual())
7975 continue;
7976
7977 CXXRecordDecl *BaseClassDecl
7978 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7979 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007980 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007981 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007982 }
7983
7984 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7985 BaseEnd = ClassDecl->vbases_end();
7986 Base != BaseEnd; ++Base) {
7987 CXXRecordDecl *BaseClassDecl
7988 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7989 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007990 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007991 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007992 }
7993
7994 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7995 FieldEnd = ClassDecl->field_end();
7996 Field != FieldEnd;
7997 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007998 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007999 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008000 if (CXXMethodDecl *MoveAssign =
8001 LookupMovingAssignment(FieldClassDecl,
8002 FieldType.getCVRQualifiers(),
8003 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008004 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008005 }
8006 }
8007
8008 return ExceptSpec;
8009}
8010
Richard Smith1c931be2012-04-02 18:40:40 +00008011/// Determine whether the class type has any direct or indirect virtual base
8012/// classes which have a non-trivial move assignment operator.
8013static bool
8014hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8015 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8016 BaseEnd = ClassDecl->vbases_end();
8017 Base != BaseEnd; ++Base) {
8018 CXXRecordDecl *BaseClass =
8019 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8020
8021 // Try to declare the move assignment. If it would be deleted, then the
8022 // class does not have a non-trivial move assignment.
8023 if (BaseClass->needsImplicitMoveAssignment())
8024 S.DeclareImplicitMoveAssignment(BaseClass);
8025
8026 // If the class has both a trivial move assignment and a non-trivial move
8027 // assignment, hasTrivialMoveAssignment() is false.
8028 if (BaseClass->hasDeclaredMoveAssignment() &&
8029 !BaseClass->hasTrivialMoveAssignment())
8030 return true;
8031 }
8032
8033 return false;
8034}
8035
8036/// Determine whether the given type either has a move constructor or is
8037/// trivially copyable.
8038static bool
8039hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8040 Type = S.Context.getBaseElementType(Type);
8041
8042 // FIXME: Technically, non-trivially-copyable non-class types, such as
8043 // reference types, are supposed to return false here, but that appears
8044 // to be a standard defect.
8045 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008046 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008047 return true;
8048
8049 if (Type.isTriviallyCopyableType(S.Context))
8050 return true;
8051
8052 if (IsConstructor) {
8053 if (ClassDecl->needsImplicitMoveConstructor())
8054 S.DeclareImplicitMoveConstructor(ClassDecl);
8055 return ClassDecl->hasDeclaredMoveConstructor();
8056 }
8057
8058 if (ClassDecl->needsImplicitMoveAssignment())
8059 S.DeclareImplicitMoveAssignment(ClassDecl);
8060 return ClassDecl->hasDeclaredMoveAssignment();
8061}
8062
8063/// Determine whether all non-static data members and direct or virtual bases
8064/// of class \p ClassDecl have either a move operation, or are trivially
8065/// copyable.
8066static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8067 bool IsConstructor) {
8068 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8069 BaseEnd = ClassDecl->bases_end();
8070 Base != BaseEnd; ++Base) {
8071 if (Base->isVirtual())
8072 continue;
8073
8074 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8075 return false;
8076 }
8077
8078 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8079 BaseEnd = ClassDecl->vbases_end();
8080 Base != BaseEnd; ++Base) {
8081 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8082 return false;
8083 }
8084
8085 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8086 FieldEnd = ClassDecl->field_end();
8087 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008088 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008089 return false;
8090 }
8091
8092 return true;
8093}
8094
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008095CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008096 // C++11 [class.copy]p20:
8097 // If the definition of a class X does not explicitly declare a move
8098 // assignment operator, one will be implicitly declared as defaulted
8099 // if and only if:
8100 //
8101 // - [first 4 bullets]
8102 assert(ClassDecl->needsImplicitMoveAssignment());
8103
8104 // [Checked after we build the declaration]
8105 // - the move assignment operator would not be implicitly defined as
8106 // deleted,
8107
8108 // [DR1402]:
8109 // - X has no direct or indirect virtual base class with a non-trivial
8110 // move assignment operator, and
8111 // - each of X's non-static data members and direct or virtual base classes
8112 // has a type that either has a move assignment operator or is trivially
8113 // copyable.
8114 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8115 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8116 ClassDecl->setFailedImplicitMoveAssignment();
8117 return 0;
8118 }
8119
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008120 // Note: The following rules are largely analoguous to the move
8121 // constructor rules.
8122
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008123 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8124 QualType RetType = Context.getLValueReferenceType(ArgType);
8125 ArgType = Context.getRValueReferenceType(ArgType);
8126
8127 // An implicitly-declared move assignment operator is an inline public
8128 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008129 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8130 SourceLocation ClassLoc = ClassDecl->getLocation();
8131 DeclarationNameInfo NameInfo(Name, ClassLoc);
8132 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008133 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008134 /*TInfo=*/0, /*isStatic=*/false,
8135 /*StorageClassAsWritten=*/SC_None,
8136 /*isInline=*/true,
8137 /*isConstexpr=*/false,
8138 SourceLocation());
8139 MoveAssignment->setAccess(AS_public);
8140 MoveAssignment->setDefaulted();
8141 MoveAssignment->setImplicit();
8142 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8143
Richard Smithb9d0b762012-07-27 04:22:15 +00008144 // Build an exception specification pointing back at this member.
8145 FunctionProtoType::ExtProtoInfo EPI;
8146 EPI.ExceptionSpecType = EST_Unevaluated;
8147 EPI.ExceptionSpecDecl = MoveAssignment;
8148 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8149
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008150 // Add the parameter to the operator.
8151 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8152 ClassLoc, ClassLoc, /*Id=*/0,
8153 ArgType, /*TInfo=*/0,
8154 SC_None,
8155 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008156 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008157
8158 // Note that we have added this copy-assignment operator.
8159 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8160
8161 // C++0x [class.copy]p9:
8162 // If the definition of a class X does not explicitly declare a move
8163 // assignment operator, one will be implicitly declared as defaulted if and
8164 // only if:
8165 // [...]
8166 // - the move assignment operator would not be implicitly defined as
8167 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008168 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008169 // Cache this result so that we don't try to generate this over and over
8170 // on every lookup, leaking memory and wasting time.
8171 ClassDecl->setFailedImplicitMoveAssignment();
8172 return 0;
8173 }
8174
8175 if (Scope *S = getScopeForContext(ClassDecl))
8176 PushOnScopeChains(MoveAssignment, S, false);
8177 ClassDecl->addDecl(MoveAssignment);
8178
8179 AddOverriddenMethods(ClassDecl, MoveAssignment);
8180 return MoveAssignment;
8181}
8182
8183void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8184 CXXMethodDecl *MoveAssignOperator) {
8185 assert((MoveAssignOperator->isDefaulted() &&
8186 MoveAssignOperator->isOverloadedOperator() &&
8187 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008188 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8189 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008190 "DefineImplicitMoveAssignment called for wrong function");
8191
8192 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8193
8194 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8195 MoveAssignOperator->setInvalidDecl();
8196 return;
8197 }
8198
8199 MoveAssignOperator->setUsed();
8200
8201 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8202 DiagnosticErrorTrap Trap(Diags);
8203
8204 // C++0x [class.copy]p28:
8205 // The implicitly-defined or move assignment operator for a non-union class
8206 // X performs memberwise move assignment of its subobjects. The direct base
8207 // classes of X are assigned first, in the order of their declaration in the
8208 // base-specifier-list, and then the immediate non-static data members of X
8209 // are assigned, in the order in which they were declared in the class
8210 // definition.
8211
8212 // The statements that form the synthesized function body.
8213 ASTOwningVector<Stmt*> Statements(*this);
8214
8215 // The parameter for the "other" object, which we are move from.
8216 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8217 QualType OtherRefType = Other->getType()->
8218 getAs<RValueReferenceType>()->getPointeeType();
8219 assert(OtherRefType.getQualifiers() == 0 &&
8220 "Bad argument type of defaulted move assignment");
8221
8222 // Our location for everything implicitly-generated.
8223 SourceLocation Loc = MoveAssignOperator->getLocation();
8224
8225 // Construct a reference to the "other" object. We'll be using this
8226 // throughout the generated ASTs.
8227 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8228 assert(OtherRef && "Reference to parameter cannot fail!");
8229 // Cast to rvalue.
8230 OtherRef = CastForMoving(*this, OtherRef);
8231
8232 // Construct the "this" pointer. We'll be using this throughout the generated
8233 // ASTs.
8234 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8235 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008236
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008237 // Assign base classes.
8238 bool Invalid = false;
8239 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8240 E = ClassDecl->bases_end(); Base != E; ++Base) {
8241 // Form the assignment:
8242 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8243 QualType BaseType = Base->getType().getUnqualifiedType();
8244 if (!BaseType->isRecordType()) {
8245 Invalid = true;
8246 continue;
8247 }
8248
8249 CXXCastPath BasePath;
8250 BasePath.push_back(Base);
8251
8252 // Construct the "from" expression, which is an implicit cast to the
8253 // appropriately-qualified base type.
8254 Expr *From = OtherRef;
8255 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008256 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008257
8258 // Dereference "this".
8259 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8260
8261 // Implicitly cast "this" to the appropriately-qualified base type.
8262 To = ImpCastExprToType(To.take(),
8263 Context.getCVRQualifiedType(BaseType,
8264 MoveAssignOperator->getTypeQualifiers()),
8265 CK_UncheckedDerivedToBase,
8266 VK_LValue, &BasePath);
8267
8268 // Build the move.
8269 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8270 To.get(), From,
8271 /*CopyingBaseSubobject=*/true,
8272 /*Copying=*/false);
8273 if (Move.isInvalid()) {
8274 Diag(CurrentLocation, diag::note_member_synthesized_at)
8275 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8276 MoveAssignOperator->setInvalidDecl();
8277 return;
8278 }
8279
8280 // Success! Record the move.
8281 Statements.push_back(Move.takeAs<Expr>());
8282 }
8283
8284 // \brief Reference to the __builtin_memcpy function.
8285 Expr *BuiltinMemCpyRef = 0;
8286 // \brief Reference to the __builtin_objc_memmove_collectable function.
8287 Expr *CollectableMemCpyRef = 0;
8288
8289 // Assign non-static members.
8290 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8291 FieldEnd = ClassDecl->field_end();
8292 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008293 if (Field->isUnnamedBitfield())
8294 continue;
8295
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008296 // Check for members of reference type; we can't move those.
8297 if (Field->getType()->isReferenceType()) {
8298 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8299 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8300 Diag(Field->getLocation(), diag::note_declared_at);
8301 Diag(CurrentLocation, diag::note_member_synthesized_at)
8302 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8303 Invalid = true;
8304 continue;
8305 }
8306
8307 // Check for members of const-qualified, non-class type.
8308 QualType BaseType = Context.getBaseElementType(Field->getType());
8309 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8310 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8311 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8312 Diag(Field->getLocation(), diag::note_declared_at);
8313 Diag(CurrentLocation, diag::note_member_synthesized_at)
8314 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8315 Invalid = true;
8316 continue;
8317 }
8318
8319 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008320 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8321 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008322
8323 QualType FieldType = Field->getType().getNonReferenceType();
8324 if (FieldType->isIncompleteArrayType()) {
8325 assert(ClassDecl->hasFlexibleArrayMember() &&
8326 "Incomplete array type is not valid");
8327 continue;
8328 }
8329
8330 // Build references to the field in the object we're copying from and to.
8331 CXXScopeSpec SS; // Intentionally empty
8332 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8333 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008334 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008335 MemberLookup.resolveKind();
8336 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8337 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008338 SS, SourceLocation(), 0,
8339 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008340 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8341 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008342 SS, SourceLocation(), 0,
8343 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008344 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8345 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8346
8347 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8348 "Member reference with rvalue base must be rvalue except for reference "
8349 "members, which aren't allowed for move assignment.");
8350
8351 // If the field should be copied with __builtin_memcpy rather than via
8352 // explicit assignments, do so. This optimization only applies for arrays
8353 // of scalars and arrays of class type with trivial move-assignment
8354 // operators.
8355 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8356 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8357 // Compute the size of the memory buffer to be copied.
8358 QualType SizeType = Context.getSizeType();
8359 llvm::APInt Size(Context.getTypeSize(SizeType),
8360 Context.getTypeSizeInChars(BaseType).getQuantity());
8361 for (const ConstantArrayType *Array
8362 = Context.getAsConstantArrayType(FieldType);
8363 Array;
8364 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8365 llvm::APInt ArraySize
8366 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8367 Size *= ArraySize;
8368 }
8369
Douglas Gregor45d3d712011-09-01 02:09:07 +00008370 // Take the address of the field references for "from" and "to". We
8371 // directly construct UnaryOperators here because semantic analysis
8372 // does not permit us to take the address of an xvalue.
8373 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8374 Context.getPointerType(From.get()->getType()),
8375 VK_RValue, OK_Ordinary, Loc);
8376 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8377 Context.getPointerType(To.get()->getType()),
8378 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008379
8380 bool NeedsCollectableMemCpy =
8381 (BaseType->isRecordType() &&
8382 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8383
8384 if (NeedsCollectableMemCpy) {
8385 if (!CollectableMemCpyRef) {
8386 // Create a reference to the __builtin_objc_memmove_collectable function.
8387 LookupResult R(*this,
8388 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8389 Loc, LookupOrdinaryName);
8390 LookupName(R, TUScope, true);
8391
8392 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8393 if (!CollectableMemCpy) {
8394 // Something went horribly wrong earlier, and we will have
8395 // complained about it.
8396 Invalid = true;
8397 continue;
8398 }
8399
8400 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8401 CollectableMemCpy->getType(),
8402 VK_LValue, Loc, 0).take();
8403 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8404 }
8405 }
8406 // Create a reference to the __builtin_memcpy builtin function.
8407 else if (!BuiltinMemCpyRef) {
8408 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8409 LookupOrdinaryName);
8410 LookupName(R, TUScope, true);
8411
8412 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8413 if (!BuiltinMemCpy) {
8414 // Something went horribly wrong earlier, and we will have complained
8415 // about it.
8416 Invalid = true;
8417 continue;
8418 }
8419
8420 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8421 BuiltinMemCpy->getType(),
8422 VK_LValue, Loc, 0).take();
8423 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8424 }
8425
8426 ASTOwningVector<Expr*> CallArgs(*this);
8427 CallArgs.push_back(To.takeAs<Expr>());
8428 CallArgs.push_back(From.takeAs<Expr>());
8429 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8430 ExprResult Call = ExprError();
8431 if (NeedsCollectableMemCpy)
8432 Call = ActOnCallExpr(/*Scope=*/0,
8433 CollectableMemCpyRef,
8434 Loc, move_arg(CallArgs),
8435 Loc);
8436 else
8437 Call = ActOnCallExpr(/*Scope=*/0,
8438 BuiltinMemCpyRef,
8439 Loc, move_arg(CallArgs),
8440 Loc);
8441
8442 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8443 Statements.push_back(Call.takeAs<Expr>());
8444 continue;
8445 }
8446
8447 // Build the move of this field.
8448 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8449 To.get(), From.get(),
8450 /*CopyingBaseSubobject=*/false,
8451 /*Copying=*/false);
8452 if (Move.isInvalid()) {
8453 Diag(CurrentLocation, diag::note_member_synthesized_at)
8454 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8455 MoveAssignOperator->setInvalidDecl();
8456 return;
8457 }
8458
8459 // Success! Record the copy.
8460 Statements.push_back(Move.takeAs<Stmt>());
8461 }
8462
8463 if (!Invalid) {
8464 // Add a "return *this;"
8465 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8466
8467 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8468 if (Return.isInvalid())
8469 Invalid = true;
8470 else {
8471 Statements.push_back(Return.takeAs<Stmt>());
8472
8473 if (Trap.hasErrorOccurred()) {
8474 Diag(CurrentLocation, diag::note_member_synthesized_at)
8475 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8476 Invalid = true;
8477 }
8478 }
8479 }
8480
8481 if (Invalid) {
8482 MoveAssignOperator->setInvalidDecl();
8483 return;
8484 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008485
8486 StmtResult Body;
8487 {
8488 CompoundScopeRAII CompoundScope(*this);
8489 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8490 /*isStmtExpr=*/false);
8491 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8492 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008493 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8494
8495 if (ASTMutationListener *L = getASTMutationListener()) {
8496 L->CompletedImplicitDefinition(MoveAssignOperator);
8497 }
8498}
8499
Richard Smithb9d0b762012-07-27 04:22:15 +00008500/// Determine whether an implicit copy constructor for ClassDecl has a const
8501/// argument.
8502/// FIXME: It ought to be possible to store this on the record.
8503static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008504 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008505 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008506
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008507 // C++ [class.copy]p5:
8508 // The implicitly-declared copy constructor for a class X will
8509 // have the form
8510 //
8511 // X::X(const X&)
8512 //
8513 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008514 // -- each direct or virtual base class B of X has a copy
8515 // constructor whose first parameter is of type const B& or
8516 // const volatile B&, and
8517 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8518 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008519 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008520 // Virtual bases are handled below.
8521 if (Base->isVirtual())
8522 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008523
Douglas Gregor22584312010-07-02 23:41:54 +00008524 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008525 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008526 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8527 // ambiguous, we should still produce a constructor with a const-qualified
8528 // parameter.
8529 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8530 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008531 }
8532
8533 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8534 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008535 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008536 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008537 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008538 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8539 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008540 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008541
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008542 // -- for all the nonstatic data members of X that are of a
8543 // class type M (or array thereof), each such class type
8544 // has a copy constructor whose first parameter is of type
8545 // const M& or const volatile M&.
8546 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8547 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008548 Field != FieldEnd; ++Field) {
8549 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008550 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008551 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8552 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008553 }
8554 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008555
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008556 // Otherwise, the implicitly declared copy constructor will have
8557 // the form
8558 //
8559 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008560
8561 return true;
8562}
8563
8564Sema::ImplicitExceptionSpecification
8565Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8566 CXXRecordDecl *ClassDecl = MD->getParent();
8567
8568 ImplicitExceptionSpecification ExceptSpec(*this);
8569 if (ClassDecl->isInvalidDecl())
8570 return ExceptSpec;
8571
8572 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8573 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8574 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8575
Douglas Gregor0d405db2010-07-01 20:59:04 +00008576 // C++ [except.spec]p14:
8577 // An implicitly declared special member function (Clause 12) shall have an
8578 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8580 BaseEnd = ClassDecl->bases_end();
8581 Base != BaseEnd;
8582 ++Base) {
8583 // Virtual bases are handled below.
8584 if (Base->isVirtual())
8585 continue;
8586
Douglas Gregor22584312010-07-02 23:41:54 +00008587 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008588 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008589 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008590 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008591 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008592 }
8593 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8594 BaseEnd = ClassDecl->vbases_end();
8595 Base != BaseEnd;
8596 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008597 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008598 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008599 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008600 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008601 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008602 }
8603 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8604 FieldEnd = ClassDecl->field_end();
8605 Field != FieldEnd;
8606 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008607 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008608 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8609 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008610 LookupCopyingConstructor(FieldClassDecl,
8611 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008612 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008613 }
8614 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008615
Richard Smithb9d0b762012-07-27 04:22:15 +00008616 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008617}
8618
8619CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8620 CXXRecordDecl *ClassDecl) {
8621 // C++ [class.copy]p4:
8622 // If the class definition does not explicitly declare a copy
8623 // constructor, one is declared implicitly.
8624
Sean Hunt49634cf2011-05-13 06:10:58 +00008625 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8626 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008627 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008628 if (Const)
8629 ArgType = ArgType.withConst();
8630 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008631
Richard Smith7756afa2012-06-10 05:43:50 +00008632 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8633 CXXCopyConstructor,
8634 Const);
8635
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008636 DeclarationName Name
8637 = Context.DeclarationNames.getCXXConstructorName(
8638 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008639 SourceLocation ClassLoc = ClassDecl->getLocation();
8640 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008641
8642 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008643 // member of its class.
8644 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008645 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008646 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008647 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008648 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008649 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008650 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008651
Richard Smithb9d0b762012-07-27 04:22:15 +00008652 // Build an exception specification pointing back at this member.
8653 FunctionProtoType::ExtProtoInfo EPI;
8654 EPI.ExceptionSpecType = EST_Unevaluated;
8655 EPI.ExceptionSpecDecl = CopyConstructor;
8656 CopyConstructor->setType(
8657 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8658
Douglas Gregor22584312010-07-02 23:41:54 +00008659 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008660 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8661
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008662 // Add the parameter to the constructor.
8663 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008664 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008665 /*IdentifierInfo=*/0,
8666 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008667 SC_None,
8668 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008669 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008670
Douglas Gregor23c94db2010-07-02 17:43:08 +00008671 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008672 PushOnScopeChains(CopyConstructor, S, false);
8673 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008674
Nico Weberafcc96a2012-01-23 03:19:29 +00008675 // C++11 [class.copy]p8:
8676 // ... If the class definition does not explicitly declare a copy
8677 // constructor, there is no user-declared move constructor, and there is no
8678 // user-declared move assignment operator, a copy constructor is implicitly
8679 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008680 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008681 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008682
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008683 return CopyConstructor;
8684}
8685
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008686void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008687 CXXConstructorDecl *CopyConstructor) {
8688 assert((CopyConstructor->isDefaulted() &&
8689 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008690 !CopyConstructor->doesThisDeclarationHaveABody() &&
8691 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008692 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008693
Anders Carlsson63010a72010-04-23 16:24:12 +00008694 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008695 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008696
Douglas Gregor39957dc2010-05-01 15:04:51 +00008697 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008698 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008699
Sean Huntcbb67482011-01-08 20:30:50 +00008700 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008701 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008702 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008703 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008704 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008705 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008706 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008707 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8708 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008709 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008710 /*isStmtExpr=*/false)
8711 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008712 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008713 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008714
8715 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008716 if (ASTMutationListener *L = getASTMutationListener()) {
8717 L->CompletedImplicitDefinition(CopyConstructor);
8718 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008719}
8720
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008721Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008722Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8723 CXXRecordDecl *ClassDecl = MD->getParent();
8724
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008725 // C++ [except.spec]p14:
8726 // An implicitly declared special member function (Clause 12) shall have an
8727 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008728 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008729 if (ClassDecl->isInvalidDecl())
8730 return ExceptSpec;
8731
8732 // Direct base-class constructors.
8733 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8734 BEnd = ClassDecl->bases_end();
8735 B != BEnd; ++B) {
8736 if (B->isVirtual()) // Handled below.
8737 continue;
8738
8739 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8740 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008741 CXXConstructorDecl *Constructor =
8742 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008743 // If this is a deleted function, add it anyway. This might be conformant
8744 // with the standard. This might not. I'm not sure. It might not matter.
8745 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008746 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008747 }
8748 }
8749
8750 // Virtual base-class constructors.
8751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8752 BEnd = ClassDecl->vbases_end();
8753 B != BEnd; ++B) {
8754 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008756 CXXConstructorDecl *Constructor =
8757 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758 // If this is a deleted function, add it anyway. This might be conformant
8759 // with the standard. This might not. I'm not sure. It might not matter.
8760 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008761 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008762 }
8763 }
8764
8765 // Field constructors.
8766 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8767 FEnd = ClassDecl->field_end();
8768 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008769 QualType FieldType = Context.getBaseElementType(F->getType());
8770 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8771 CXXConstructorDecl *Constructor =
8772 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008773 // If this is a deleted function, add it anyway. This might be conformant
8774 // with the standard. This might not. I'm not sure. It might not matter.
8775 // In particular, the problem is that this function never gets called. It
8776 // might just be ill-formed because this function attempts to refer to
8777 // a deleted function here.
8778 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008779 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008780 }
8781 }
8782
8783 return ExceptSpec;
8784}
8785
8786CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8787 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008788 // C++11 [class.copy]p9:
8789 // If the definition of a class X does not explicitly declare a move
8790 // constructor, one will be implicitly declared as defaulted if and only if:
8791 //
8792 // - [first 4 bullets]
8793 assert(ClassDecl->needsImplicitMoveConstructor());
8794
8795 // [Checked after we build the declaration]
8796 // - the move assignment operator would not be implicitly defined as
8797 // deleted,
8798
8799 // [DR1402]:
8800 // - each of X's non-static data members and direct or virtual base classes
8801 // has a type that either has a move constructor or is trivially copyable.
8802 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8803 ClassDecl->setFailedImplicitMoveConstructor();
8804 return 0;
8805 }
8806
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008807 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8808 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008809
Richard Smith7756afa2012-06-10 05:43:50 +00008810 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8811 CXXMoveConstructor,
8812 false);
8813
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008814 DeclarationName Name
8815 = Context.DeclarationNames.getCXXConstructorName(
8816 Context.getCanonicalType(ClassType));
8817 SourceLocation ClassLoc = ClassDecl->getLocation();
8818 DeclarationNameInfo NameInfo(Name, ClassLoc);
8819
8820 // C++0x [class.copy]p11:
8821 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008822 // member of its class.
8823 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008824 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008825 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008826 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008827 MoveConstructor->setAccess(AS_public);
8828 MoveConstructor->setDefaulted();
8829 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008830
Richard Smithb9d0b762012-07-27 04:22:15 +00008831 // Build an exception specification pointing back at this member.
8832 FunctionProtoType::ExtProtoInfo EPI;
8833 EPI.ExceptionSpecType = EST_Unevaluated;
8834 EPI.ExceptionSpecDecl = MoveConstructor;
8835 MoveConstructor->setType(
8836 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8837
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008838 // Add the parameter to the constructor.
8839 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8840 ClassLoc, ClassLoc,
8841 /*IdentifierInfo=*/0,
8842 ArgType, /*TInfo=*/0,
8843 SC_None,
8844 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008845 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008846
8847 // C++0x [class.copy]p9:
8848 // If the definition of a class X does not explicitly declare a move
8849 // constructor, one will be implicitly declared as defaulted if and only if:
8850 // [...]
8851 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008852 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008853 // Cache this result so that we don't try to generate this over and over
8854 // on every lookup, leaking memory and wasting time.
8855 ClassDecl->setFailedImplicitMoveConstructor();
8856 return 0;
8857 }
8858
8859 // Note that we have declared this constructor.
8860 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8861
8862 if (Scope *S = getScopeForContext(ClassDecl))
8863 PushOnScopeChains(MoveConstructor, S, false);
8864 ClassDecl->addDecl(MoveConstructor);
8865
8866 return MoveConstructor;
8867}
8868
8869void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8870 CXXConstructorDecl *MoveConstructor) {
8871 assert((MoveConstructor->isDefaulted() &&
8872 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008873 !MoveConstructor->doesThisDeclarationHaveABody() &&
8874 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008875 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8876
8877 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8878 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8879
8880 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8881 DiagnosticErrorTrap Trap(Diags);
8882
8883 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8884 Trap.hasErrorOccurred()) {
8885 Diag(CurrentLocation, diag::note_member_synthesized_at)
8886 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8887 MoveConstructor->setInvalidDecl();
8888 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008889 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008890 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8891 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008892 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893 /*isStmtExpr=*/false)
8894 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008895 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008896 }
8897
8898 MoveConstructor->setUsed();
8899
8900 if (ASTMutationListener *L = getASTMutationListener()) {
8901 L->CompletedImplicitDefinition(MoveConstructor);
8902 }
8903}
8904
Douglas Gregore4e68d42012-02-15 19:33:52 +00008905bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8906 return FD->isDeleted() &&
8907 (FD->isDefaulted() || FD->isImplicit()) &&
8908 isa<CXXMethodDecl>(FD);
8909}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008910
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008911/// \brief Mark the call operator of the given lambda closure type as "used".
8912static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8913 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008914 = cast<CXXMethodDecl>(
8915 *Lambda->lookup(
8916 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008917 CallOperator->setReferenced();
8918 CallOperator->setUsed();
8919}
8920
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008921void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8922 SourceLocation CurrentLocation,
8923 CXXConversionDecl *Conv)
8924{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008925 CXXRecordDecl *Lambda = Conv->getParent();
8926
8927 // Make sure that the lambda call operator is marked used.
8928 markLambdaCallOperatorUsed(*this, Lambda);
8929
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008930 Conv->setUsed();
8931
8932 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8933 DiagnosticErrorTrap Trap(Diags);
8934
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008935 // Return the address of the __invoke function.
8936 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8937 CXXMethodDecl *Invoke
8938 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8939 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8940 VK_LValue, Conv->getLocation()).take();
8941 assert(FunctionRef && "Can't refer to __invoke function?");
8942 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8943 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8944 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008945 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008946
8947 // Fill in the __invoke function with a dummy implementation. IR generation
8948 // will fill in the actual details.
8949 Invoke->setUsed();
8950 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008951 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008952
8953 if (ASTMutationListener *L = getASTMutationListener()) {
8954 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008955 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008956 }
8957}
8958
8959void Sema::DefineImplicitLambdaToBlockPointerConversion(
8960 SourceLocation CurrentLocation,
8961 CXXConversionDecl *Conv)
8962{
8963 Conv->setUsed();
8964
8965 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8966 DiagnosticErrorTrap Trap(Diags);
8967
Douglas Gregorac1303e2012-02-22 05:02:47 +00008968 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008969 Expr *This = ActOnCXXThis(CurrentLocation).take();
8970 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008971
Eli Friedman23f02672012-03-01 04:01:32 +00008972 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8973 Conv->getLocation(),
8974 Conv, DerefThis);
8975
8976 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8977 // behavior. Note that only the general conversion function does this
8978 // (since it's unusable otherwise); in the case where we inline the
8979 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008980 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008981 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8982 CK_CopyAndAutoreleaseBlockObject,
8983 BuildBlock.get(), 0, VK_RValue);
8984
8985 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008986 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008987 Conv->setInvalidDecl();
8988 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008989 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008990
Douglas Gregorac1303e2012-02-22 05:02:47 +00008991 // Create the return statement that returns the block from the conversion
8992 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008993 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008994 if (Return.isInvalid()) {
8995 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8996 Conv->setInvalidDecl();
8997 return;
8998 }
8999
9000 // Set the body of the conversion function.
9001 Stmt *ReturnS = Return.take();
9002 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9003 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009004 Conv->getLocation()));
9005
Douglas Gregorac1303e2012-02-22 05:02:47 +00009006 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009007 if (ASTMutationListener *L = getASTMutationListener()) {
9008 L->CompletedImplicitDefinition(Conv);
9009 }
9010}
9011
Douglas Gregorf52757d2012-03-10 06:53:13 +00009012/// \brief Determine whether the given list arguments contains exactly one
9013/// "real" (non-default) argument.
9014static bool hasOneRealArgument(MultiExprArg Args) {
9015 switch (Args.size()) {
9016 case 0:
9017 return false;
9018
9019 default:
9020 if (!Args.get()[1]->isDefaultArgument())
9021 return false;
9022
9023 // fall through
9024 case 1:
9025 return !Args.get()[0]->isDefaultArgument();
9026 }
9027
9028 return false;
9029}
9030
John McCall60d7b3a2010-08-24 06:29:42 +00009031ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009032Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009033 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009034 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009035 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009036 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009037 unsigned ConstructKind,
9038 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009039 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009040
Douglas Gregor2f599792010-04-02 18:24:57 +00009041 // C++0x [class.copy]p34:
9042 // When certain criteria are met, an implementation is allowed to
9043 // omit the copy/move construction of a class object, even if the
9044 // copy/move constructor and/or destructor for the object have
9045 // side effects. [...]
9046 // - when a temporary class object that has not been bound to a
9047 // reference (12.2) would be copied/moved to a class object
9048 // with the same cv-unqualified type, the copy/move operation
9049 // can be omitted by constructing the temporary object
9050 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009051 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009052 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009053 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009054 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009055 }
Mike Stump1eb44332009-09-09 15:08:12 +00009056
9057 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009058 Elidable, move(ExprArgs), HadMultipleCandidates,
9059 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009060}
9061
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009062/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9063/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009064ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009065Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9066 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009067 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009068 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009069 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009070 unsigned ConstructKind,
9071 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009072 unsigned NumExprs = ExprArgs.size();
9073 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009074
Eli Friedman5f2987c2012-02-02 03:46:19 +00009075 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009076 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009077 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009078 HadMultipleCandidates, /*FIXME*/false,
9079 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009080 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9081 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009082}
9083
Mike Stump1eb44332009-09-09 15:08:12 +00009084bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009085 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009086 MultiExprArg Exprs,
9087 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009088 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009089 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009090 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009091 move(Exprs), HadMultipleCandidates, false,
9092 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009093 if (TempResult.isInvalid())
9094 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009095
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009096 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009097 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009098 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009099 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009100 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009101
Anders Carlssonfe2de492009-08-25 05:18:00 +00009102 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009103}
9104
John McCall68c6c9a2010-02-02 09:10:11 +00009105void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009106 if (VD->isInvalidDecl()) return;
9107
John McCall68c6c9a2010-02-02 09:10:11 +00009108 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009109 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009110 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009111 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009112
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009113 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009114 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009115 CheckDestructorAccess(VD->getLocation(), Destructor,
9116 PDiag(diag::err_access_dtor_var)
9117 << VD->getDeclName()
9118 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009119 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009120
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009121 if (!VD->hasGlobalStorage()) return;
9122
9123 // Emit warning for non-trivial dtor in global scope (a real global,
9124 // class-static, function-static).
9125 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9126
9127 // TODO: this should be re-enabled for static locals by !CXAAtExit
9128 if (!VD->isStaticLocal())
9129 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009130}
9131
Douglas Gregor39da0b82009-09-09 23:08:42 +00009132/// \brief Given a constructor and the set of arguments provided for the
9133/// constructor, convert the arguments and add any required default arguments
9134/// to form a proper call to this constructor.
9135///
9136/// \returns true if an error occurred, false otherwise.
9137bool
9138Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9139 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009140 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009141 ASTOwningVector<Expr*> &ConvertedArgs,
9142 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009143 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9144 unsigned NumArgs = ArgsPtr.size();
9145 Expr **Args = (Expr **)ArgsPtr.get();
9146
9147 const FunctionProtoType *Proto
9148 = Constructor->getType()->getAs<FunctionProtoType>();
9149 assert(Proto && "Constructor without a prototype?");
9150 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009151
9152 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009153 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009154 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009155 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009156 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009157
9158 VariadicCallType CallType =
9159 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009160 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009161 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9162 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009163 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009164 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009165
9166 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9167
Richard Smith831421f2012-06-25 20:30:08 +00009168 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9169 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009170
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009171 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009172}
9173
Anders Carlsson20d45d22009-12-12 00:32:00 +00009174static inline bool
9175CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9176 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009177 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009178 if (isa<NamespaceDecl>(DC)) {
9179 return SemaRef.Diag(FnDecl->getLocation(),
9180 diag::err_operator_new_delete_declared_in_namespace)
9181 << FnDecl->getDeclName();
9182 }
9183
9184 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009185 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009186 return SemaRef.Diag(FnDecl->getLocation(),
9187 diag::err_operator_new_delete_declared_static)
9188 << FnDecl->getDeclName();
9189 }
9190
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009191 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009192}
9193
Anders Carlsson156c78e2009-12-13 17:53:43 +00009194static inline bool
9195CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9196 CanQualType ExpectedResultType,
9197 CanQualType ExpectedFirstParamType,
9198 unsigned DependentParamTypeDiag,
9199 unsigned InvalidParamTypeDiag) {
9200 QualType ResultType =
9201 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9202
9203 // Check that the result type is not dependent.
9204 if (ResultType->isDependentType())
9205 return SemaRef.Diag(FnDecl->getLocation(),
9206 diag::err_operator_new_delete_dependent_result_type)
9207 << FnDecl->getDeclName() << ExpectedResultType;
9208
9209 // Check that the result type is what we expect.
9210 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9211 return SemaRef.Diag(FnDecl->getLocation(),
9212 diag::err_operator_new_delete_invalid_result_type)
9213 << FnDecl->getDeclName() << ExpectedResultType;
9214
9215 // A function template must have at least 2 parameters.
9216 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9217 return SemaRef.Diag(FnDecl->getLocation(),
9218 diag::err_operator_new_delete_template_too_few_parameters)
9219 << FnDecl->getDeclName();
9220
9221 // The function decl must have at least 1 parameter.
9222 if (FnDecl->getNumParams() == 0)
9223 return SemaRef.Diag(FnDecl->getLocation(),
9224 diag::err_operator_new_delete_too_few_parameters)
9225 << FnDecl->getDeclName();
9226
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009227 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009228 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9229 if (FirstParamType->isDependentType())
9230 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9231 << FnDecl->getDeclName() << ExpectedFirstParamType;
9232
9233 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009234 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009235 ExpectedFirstParamType)
9236 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9237 << FnDecl->getDeclName() << ExpectedFirstParamType;
9238
9239 return false;
9240}
9241
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009242static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009243CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009244 // C++ [basic.stc.dynamic.allocation]p1:
9245 // A program is ill-formed if an allocation function is declared in a
9246 // namespace scope other than global scope or declared static in global
9247 // scope.
9248 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9249 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009250
9251 CanQualType SizeTy =
9252 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9253
9254 // C++ [basic.stc.dynamic.allocation]p1:
9255 // The return type shall be void*. The first parameter shall have type
9256 // std::size_t.
9257 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9258 SizeTy,
9259 diag::err_operator_new_dependent_param_type,
9260 diag::err_operator_new_param_type))
9261 return true;
9262
9263 // C++ [basic.stc.dynamic.allocation]p1:
9264 // The first parameter shall not have an associated default argument.
9265 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009266 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009267 diag::err_operator_new_default_arg)
9268 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9269
9270 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009271}
9272
9273static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009274CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9275 // C++ [basic.stc.dynamic.deallocation]p1:
9276 // A program is ill-formed if deallocation functions are declared in a
9277 // namespace scope other than global scope or declared static in global
9278 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009279 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9280 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009281
9282 // C++ [basic.stc.dynamic.deallocation]p2:
9283 // Each deallocation function shall return void and its first parameter
9284 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009285 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9286 SemaRef.Context.VoidPtrTy,
9287 diag::err_operator_delete_dependent_param_type,
9288 diag::err_operator_delete_param_type))
9289 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009290
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009291 return false;
9292}
9293
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009294/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9295/// of this overloaded operator is well-formed. If so, returns false;
9296/// otherwise, emits appropriate diagnostics and returns true.
9297bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009298 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009299 "Expected an overloaded operator declaration");
9300
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009301 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9302
Mike Stump1eb44332009-09-09 15:08:12 +00009303 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009304 // The allocation and deallocation functions, operator new,
9305 // operator new[], operator delete and operator delete[], are
9306 // described completely in 3.7.3. The attributes and restrictions
9307 // found in the rest of this subclause do not apply to them unless
9308 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009309 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009310 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009311
Anders Carlssona3ccda52009-12-12 00:26:23 +00009312 if (Op == OO_New || Op == OO_Array_New)
9313 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009314
9315 // C++ [over.oper]p6:
9316 // An operator function shall either be a non-static member
9317 // function or be a non-member function and have at least one
9318 // parameter whose type is a class, a reference to a class, an
9319 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009320 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9321 if (MethodDecl->isStatic())
9322 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009323 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009324 } else {
9325 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009326 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9327 ParamEnd = FnDecl->param_end();
9328 Param != ParamEnd; ++Param) {
9329 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009330 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9331 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009332 ClassOrEnumParam = true;
9333 break;
9334 }
9335 }
9336
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009337 if (!ClassOrEnumParam)
9338 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009339 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009340 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009341 }
9342
9343 // C++ [over.oper]p8:
9344 // An operator function cannot have default arguments (8.3.6),
9345 // except where explicitly stated below.
9346 //
Mike Stump1eb44332009-09-09 15:08:12 +00009347 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009348 // (C++ [over.call]p1).
9349 if (Op != OO_Call) {
9350 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9351 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009352 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009353 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009354 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009355 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009356 }
9357 }
9358
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009359 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9360 { false, false, false }
9361#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9362 , { Unary, Binary, MemberOnly }
9363#include "clang/Basic/OperatorKinds.def"
9364 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009365
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009366 bool CanBeUnaryOperator = OperatorUses[Op][0];
9367 bool CanBeBinaryOperator = OperatorUses[Op][1];
9368 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009369
9370 // C++ [over.oper]p8:
9371 // [...] Operator functions cannot have more or fewer parameters
9372 // than the number required for the corresponding operator, as
9373 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009374 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009375 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009376 if (Op != OO_Call &&
9377 ((NumParams == 1 && !CanBeUnaryOperator) ||
9378 (NumParams == 2 && !CanBeBinaryOperator) ||
9379 (NumParams < 1) || (NumParams > 2))) {
9380 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009381 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009382 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009383 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009384 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009385 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009386 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009387 assert(CanBeBinaryOperator &&
9388 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009389 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009390 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391
Chris Lattner416e46f2008-11-21 07:57:12 +00009392 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009393 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009394 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009395
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009396 // Overloaded operators other than operator() cannot be variadic.
9397 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009398 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009399 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009400 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009401 }
9402
9403 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009404 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9405 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009406 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009407 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009408 }
9409
9410 // C++ [over.inc]p1:
9411 // The user-defined function called operator++ implements the
9412 // prefix and postfix ++ operator. If this function is a member
9413 // function with no parameters, or a non-member function with one
9414 // parameter of class or enumeration type, it defines the prefix
9415 // increment operator ++ for objects of that type. If the function
9416 // is a member function with one parameter (which shall be of type
9417 // int) or a non-member function with two parameters (the second
9418 // of which shall be of type int), it defines the postfix
9419 // increment operator ++ for objects of that type.
9420 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9421 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9422 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009423 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009424 ParamIsInt = BT->getKind() == BuiltinType::Int;
9425
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009426 if (!ParamIsInt)
9427 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009428 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009429 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009430 }
9431
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009432 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009433}
Chris Lattner5a003a42008-12-17 07:09:26 +00009434
Sean Hunta6c058d2010-01-13 09:01:02 +00009435/// CheckLiteralOperatorDeclaration - Check whether the declaration
9436/// of this literal operator function is well-formed. If so, returns
9437/// false; otherwise, emits appropriate diagnostics and returns true.
9438bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009439 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009440 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9441 << FnDecl->getDeclName();
9442 return true;
9443 }
9444
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009445 if (FnDecl->isExternC()) {
9446 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9447 return true;
9448 }
9449
Sean Hunta6c058d2010-01-13 09:01:02 +00009450 bool Valid = false;
9451
Richard Smith36f5cfe2012-03-09 08:00:36 +00009452 // This might be the definition of a literal operator template.
9453 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9454 // This might be a specialization of a literal operator template.
9455 if (!TpDecl)
9456 TpDecl = FnDecl->getPrimaryTemplate();
9457
Sean Hunt216c2782010-04-07 23:11:06 +00009458 // template <char...> type operator "" name() is the only valid template
9459 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009460 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009461 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009462 // Must have only one template parameter
9463 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9464 if (Params->size() == 1) {
9465 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009466 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009467
Sean Hunt216c2782010-04-07 23:11:06 +00009468 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009469 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9470 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9471 Valid = true;
9472 }
9473 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009474 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009475 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009476 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9477
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009478 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009479
Sean Hunt30019c02010-04-07 22:57:35 +00009480 // unsigned long long int, long double, and any character type are allowed
9481 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009482 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9483 Context.hasSameType(T, Context.LongDoubleTy) ||
9484 Context.hasSameType(T, Context.CharTy) ||
9485 Context.hasSameType(T, Context.WCharTy) ||
9486 Context.hasSameType(T, Context.Char16Ty) ||
9487 Context.hasSameType(T, Context.Char32Ty)) {
9488 if (++Param == FnDecl->param_end())
9489 Valid = true;
9490 goto FinishedParams;
9491 }
9492
Sean Hunt30019c02010-04-07 22:57:35 +00009493 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009494 const PointerType *PT = T->getAs<PointerType>();
9495 if (!PT)
9496 goto FinishedParams;
9497 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009498 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009499 goto FinishedParams;
9500 T = T.getUnqualifiedType();
9501
9502 // Move on to the second parameter;
9503 ++Param;
9504
9505 // If there is no second parameter, the first must be a const char *
9506 if (Param == FnDecl->param_end()) {
9507 if (Context.hasSameType(T, Context.CharTy))
9508 Valid = true;
9509 goto FinishedParams;
9510 }
9511
9512 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9513 // are allowed as the first parameter to a two-parameter function
9514 if (!(Context.hasSameType(T, Context.CharTy) ||
9515 Context.hasSameType(T, Context.WCharTy) ||
9516 Context.hasSameType(T, Context.Char16Ty) ||
9517 Context.hasSameType(T, Context.Char32Ty)))
9518 goto FinishedParams;
9519
9520 // The second and final parameter must be an std::size_t
9521 T = (*Param)->getType().getUnqualifiedType();
9522 if (Context.hasSameType(T, Context.getSizeType()) &&
9523 ++Param == FnDecl->param_end())
9524 Valid = true;
9525 }
9526
9527 // FIXME: This diagnostic is absolutely terrible.
9528FinishedParams:
9529 if (!Valid) {
9530 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9531 << FnDecl->getDeclName();
9532 return true;
9533 }
9534
Richard Smitha9e88b22012-03-09 08:16:22 +00009535 // A parameter-declaration-clause containing a default argument is not
9536 // equivalent to any of the permitted forms.
9537 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9538 ParamEnd = FnDecl->param_end();
9539 Param != ParamEnd; ++Param) {
9540 if ((*Param)->hasDefaultArg()) {
9541 Diag((*Param)->getDefaultArgRange().getBegin(),
9542 diag::err_literal_operator_default_argument)
9543 << (*Param)->getDefaultArgRange();
9544 break;
9545 }
9546 }
9547
Richard Smith2fb4ae32012-03-08 02:39:21 +00009548 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009549 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9550 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009551 // C++11 [usrlit.suffix]p1:
9552 // Literal suffix identifiers that do not start with an underscore
9553 // are reserved for future standardization.
9554 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009555 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009556
Sean Hunta6c058d2010-01-13 09:01:02 +00009557 return false;
9558}
9559
Douglas Gregor074149e2009-01-05 19:45:36 +00009560/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9561/// linkage specification, including the language and (if present)
9562/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9563/// the location of the language string literal, which is provided
9564/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9565/// the '{' brace. Otherwise, this linkage specification does not
9566/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009567Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9568 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009569 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009570 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009571 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009572 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009573 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009574 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009575 Language = LinkageSpecDecl::lang_cxx;
9576 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009577 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009578 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009579 }
Mike Stump1eb44332009-09-09 15:08:12 +00009580
Chris Lattnercc98eac2008-12-17 07:13:27 +00009581 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009582
Douglas Gregor074149e2009-01-05 19:45:36 +00009583 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009584 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009585 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009586 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009587 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009588}
9589
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009590/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009591/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9592/// valid, it's the position of the closing '}' brace in a linkage
9593/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009594Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009595 Decl *LinkageSpec,
9596 SourceLocation RBraceLoc) {
9597 if (LinkageSpec) {
9598 if (RBraceLoc.isValid()) {
9599 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9600 LSDecl->setRBraceLoc(RBraceLoc);
9601 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009602 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009603 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009604 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009605}
9606
Douglas Gregord308e622009-05-18 20:51:54 +00009607/// \brief Perform semantic analysis for the variable declaration that
9608/// occurs within a C++ catch clause, returning the newly-created
9609/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009610VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009611 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009612 SourceLocation StartLoc,
9613 SourceLocation Loc,
9614 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009615 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009616 QualType ExDeclType = TInfo->getType();
9617
Sebastian Redl4b07b292008-12-22 19:15:10 +00009618 // Arrays and functions decay.
9619 if (ExDeclType->isArrayType())
9620 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9621 else if (ExDeclType->isFunctionType())
9622 ExDeclType = Context.getPointerType(ExDeclType);
9623
9624 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9625 // The exception-declaration shall not denote a pointer or reference to an
9626 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009627 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009628 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009629 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009630 Invalid = true;
9631 }
Douglas Gregord308e622009-05-18 20:51:54 +00009632
Sebastian Redl4b07b292008-12-22 19:15:10 +00009633 QualType BaseType = ExDeclType;
9634 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009635 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009636 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009637 BaseType = Ptr->getPointeeType();
9638 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009639 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009640 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009641 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009642 BaseType = Ref->getPointeeType();
9643 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009644 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009645 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009646 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009647 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009648 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009649
Mike Stump1eb44332009-09-09 15:08:12 +00009650 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009651 RequireNonAbstractType(Loc, ExDeclType,
9652 diag::err_abstract_type_in_decl,
9653 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009654 Invalid = true;
9655
John McCall5a180392010-07-24 00:37:23 +00009656 // Only the non-fragile NeXT runtime currently supports C++ catches
9657 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009658 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009659 QualType T = ExDeclType;
9660 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9661 T = RT->getPointeeType();
9662
9663 if (T->isObjCObjectType()) {
9664 Diag(Loc, diag::err_objc_object_catch);
9665 Invalid = true;
9666 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009667 // FIXME: should this be a test for macosx-fragile specifically?
9668 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009669 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009670 }
9671 }
9672
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009673 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9674 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009675 ExDecl->setExceptionVariable(true);
9676
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009677 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009678 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009679 Invalid = true;
9680
Douglas Gregorc41b8782011-07-06 18:14:43 +00009681 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009682 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009683 // C++ [except.handle]p16:
9684 // The object declared in an exception-declaration or, if the
9685 // exception-declaration does not specify a name, a temporary (12.2) is
9686 // copy-initialized (8.5) from the exception object. [...]
9687 // The object is destroyed when the handler exits, after the destruction
9688 // of any automatic objects initialized within the handler.
9689 //
9690 // We just pretend to initialize the object with itself, then make sure
9691 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009692 QualType initType = ExDeclType;
9693
9694 InitializedEntity entity =
9695 InitializedEntity::InitializeVariable(ExDecl);
9696 InitializationKind initKind =
9697 InitializationKind::CreateCopy(Loc, SourceLocation());
9698
9699 Expr *opaqueValue =
9700 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9701 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9702 ExprResult result = sequence.Perform(*this, entity, initKind,
9703 MultiExprArg(&opaqueValue, 1));
9704 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009705 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009706 else {
9707 // If the constructor used was non-trivial, set this as the
9708 // "initializer".
9709 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9710 if (!construct->getConstructor()->isTrivial()) {
9711 Expr *init = MaybeCreateExprWithCleanups(construct);
9712 ExDecl->setInit(init);
9713 }
9714
9715 // And make sure it's destructable.
9716 FinalizeVarWithDestructor(ExDecl, recordType);
9717 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009718 }
9719 }
9720
Douglas Gregord308e622009-05-18 20:51:54 +00009721 if (Invalid)
9722 ExDecl->setInvalidDecl();
9723
9724 return ExDecl;
9725}
9726
9727/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9728/// handler.
John McCalld226f652010-08-21 09:40:31 +00009729Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009730 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009731 bool Invalid = D.isInvalidType();
9732
9733 // Check for unexpanded parameter packs.
9734 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9735 UPPC_ExceptionType)) {
9736 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9737 D.getIdentifierLoc());
9738 Invalid = true;
9739 }
9740
Sebastian Redl4b07b292008-12-22 19:15:10 +00009741 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009742 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009743 LookupOrdinaryName,
9744 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009745 // The scope should be freshly made just for us. There is just no way
9746 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009747 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009748 if (PrevDecl->isTemplateParameter()) {
9749 // Maybe we will complain about the shadowed template parameter.
9750 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009751 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009752 }
9753 }
9754
Chris Lattnereaaebc72009-04-25 08:06:05 +00009755 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009756 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9757 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009758 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009759 }
9760
Douglas Gregor83cb9422010-09-09 17:09:21 +00009761 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009762 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009763 D.getIdentifierLoc(),
9764 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009765 if (Invalid)
9766 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009767
Sebastian Redl4b07b292008-12-22 19:15:10 +00009768 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009769 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009770 PushOnScopeChains(ExDecl, S);
9771 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009772 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009773
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009774 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009775 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009776}
Anders Carlssonfb311762009-03-14 00:25:26 +00009777
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009778Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009779 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009780 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009781 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009782 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009783
Richard Smithe3f470a2012-07-11 22:37:56 +00009784 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9785 return 0;
9786
9787 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9788 AssertMessage, RParenLoc, false);
9789}
9790
9791Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9792 Expr *AssertExpr,
9793 StringLiteral *AssertMessage,
9794 SourceLocation RParenLoc,
9795 bool Failed) {
9796 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9797 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009798 // In a static_assert-declaration, the constant-expression shall be a
9799 // constant expression that can be contextually converted to bool.
9800 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9801 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009802 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009803
Richard Smithdaaefc52011-12-14 23:32:26 +00009804 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009805 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009806 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009807 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009808 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009809
Richard Smithe3f470a2012-07-11 22:37:56 +00009810 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009811 llvm::SmallString<256> MsgBuffer;
9812 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +00009813 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009814 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009815 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009816 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009817 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009818 }
Mike Stump1eb44332009-09-09 15:08:12 +00009819
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009820 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009821 AssertExpr, AssertMessage, RParenLoc,
9822 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009823
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009824 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009825 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009826}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009827
Douglas Gregor1d869352010-04-07 16:53:43 +00009828/// \brief Perform semantic analysis of the given friend type declaration.
9829///
9830/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009831FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9832 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009833 TypeSourceInfo *TSInfo) {
9834 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9835
9836 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009837 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009838
Richard Smith6b130222011-10-18 21:39:00 +00009839 // C++03 [class.friend]p2:
9840 // An elaborated-type-specifier shall be used in a friend declaration
9841 // for a class.*
9842 //
9843 // * The class-key of the elaborated-type-specifier is required.
9844 if (!ActiveTemplateInstantiations.empty()) {
9845 // Do not complain about the form of friend template types during
9846 // template instantiation; we will already have complained when the
9847 // template was declared.
9848 } else if (!T->isElaboratedTypeSpecifier()) {
9849 // If we evaluated the type to a record type, suggest putting
9850 // a tag in front.
9851 if (const RecordType *RT = T->getAs<RecordType>()) {
9852 RecordDecl *RD = RT->getDecl();
9853
9854 std::string InsertionText = std::string(" ") + RD->getKindName();
9855
9856 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009857 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009858 diag::warn_cxx98_compat_unelaborated_friend_type :
9859 diag::ext_unelaborated_friend_type)
9860 << (unsigned) RD->getTagKind()
9861 << T
9862 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9863 InsertionText);
9864 } else {
9865 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009866 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009867 diag::warn_cxx98_compat_nonclass_type_friend :
9868 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009869 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009870 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009871 }
Richard Smith6b130222011-10-18 21:39:00 +00009872 } else if (T->getAs<EnumType>()) {
9873 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009874 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009875 diag::warn_cxx98_compat_enum_friend :
9876 diag::ext_enum_friend)
9877 << T
9878 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009879 }
9880
Douglas Gregor06245bf2010-04-07 17:57:12 +00009881 // C++0x [class.friend]p3:
9882 // If the type specifier in a friend declaration designates a (possibly
9883 // cv-qualified) class type, that class is declared as a friend; otherwise,
9884 // the friend declaration is ignored.
9885
9886 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9887 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009888
Abramo Bagnara0216df82011-10-29 20:52:52 +00009889 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009890}
9891
John McCall9a34edb2010-10-19 01:40:49 +00009892/// Handle a friend tag declaration where the scope specifier was
9893/// templated.
9894Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9895 unsigned TagSpec, SourceLocation TagLoc,
9896 CXXScopeSpec &SS,
9897 IdentifierInfo *Name, SourceLocation NameLoc,
9898 AttributeList *Attr,
9899 MultiTemplateParamsArg TempParamLists) {
9900 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9901
9902 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009903 bool Invalid = false;
9904
9905 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009906 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009907 TempParamLists.get(),
9908 TempParamLists.size(),
9909 /*friend*/ true,
9910 isExplicitSpecialization,
9911 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009912 if (TemplateParams->size() > 0) {
9913 // This is a declaration of a class template.
9914 if (Invalid)
9915 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009916
Eric Christopher4110e132011-07-21 05:34:24 +00009917 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9918 SS, Name, NameLoc, Attr,
9919 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009920 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009921 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009922 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009923 } else {
9924 // The "template<>" header is extraneous.
9925 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9926 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9927 isExplicitSpecialization = true;
9928 }
9929 }
9930
9931 if (Invalid) return 0;
9932
John McCall9a34edb2010-10-19 01:40:49 +00009933 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009934 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009935 if (TempParamLists.get()[I]->size()) {
9936 isAllExplicitSpecializations = false;
9937 break;
9938 }
9939 }
9940
9941 // FIXME: don't ignore attributes.
9942
9943 // If it's explicit specializations all the way down, just forget
9944 // about the template header and build an appropriate non-templated
9945 // friend. TODO: for source fidelity, remember the headers.
9946 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009947 if (SS.isEmpty()) {
9948 bool Owned = false;
9949 bool IsDependent = false;
9950 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9951 Attr, AS_public,
9952 /*ModulePrivateLoc=*/SourceLocation(),
9953 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009954 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009955 /*ScopedEnumUsesClassTag=*/false,
9956 /*UnderlyingType=*/TypeResult());
9957 }
9958
Douglas Gregor2494dd02011-03-01 01:34:45 +00009959 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009960 ElaboratedTypeKeyword Keyword
9961 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009962 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009963 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009964 if (T.isNull())
9965 return 0;
9966
9967 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9968 if (isa<DependentNameType>(T)) {
9969 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009970 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009971 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009972 TL.setNameLoc(NameLoc);
9973 } else {
9974 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009975 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009976 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009977 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9978 }
9979
9980 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9981 TSI, FriendLoc);
9982 Friend->setAccess(AS_public);
9983 CurContext->addDecl(Friend);
9984 return Friend;
9985 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009986
9987 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9988
9989
John McCall9a34edb2010-10-19 01:40:49 +00009990
9991 // Handle the case of a templated-scope friend class. e.g.
9992 // template <class T> class A<T>::B;
9993 // FIXME: we don't support these right now.
9994 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9995 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9996 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9997 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009998 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009999 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010000 TL.setNameLoc(NameLoc);
10001
10002 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10003 TSI, FriendLoc);
10004 Friend->setAccess(AS_public);
10005 Friend->setUnsupportedFriend(true);
10006 CurContext->addDecl(Friend);
10007 return Friend;
10008}
10009
10010
John McCalldd4a3b02009-09-16 22:47:08 +000010011/// Handle a friend type declaration. This works in tandem with
10012/// ActOnTag.
10013///
10014/// Notes on friend class templates:
10015///
10016/// We generally treat friend class declarations as if they were
10017/// declaring a class. So, for example, the elaborated type specifier
10018/// in a friend declaration is required to obey the restrictions of a
10019/// class-head (i.e. no typedefs in the scope chain), template
10020/// parameters are required to match up with simple template-ids, &c.
10021/// However, unlike when declaring a template specialization, it's
10022/// okay to refer to a template specialization without an empty
10023/// template parameter declaration, e.g.
10024/// friend class A<T>::B<unsigned>;
10025/// We permit this as a special case; if there are any template
10026/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010027/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010028Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010029 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010030 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010031
10032 assert(DS.isFriendSpecified());
10033 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10034
John McCalldd4a3b02009-09-16 22:47:08 +000010035 // Try to convert the decl specifier to a type. This works for
10036 // friend templates because ActOnTag never produces a ClassTemplateDecl
10037 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010038 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010039 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10040 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010041 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010042 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010043
Douglas Gregor6ccab972010-12-16 01:14:37 +000010044 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10045 return 0;
10046
John McCalldd4a3b02009-09-16 22:47:08 +000010047 // This is definitely an error in C++98. It's probably meant to
10048 // be forbidden in C++0x, too, but the specification is just
10049 // poorly written.
10050 //
10051 // The problem is with declarations like the following:
10052 // template <T> friend A<T>::foo;
10053 // where deciding whether a class C is a friend or not now hinges
10054 // on whether there exists an instantiation of A that causes
10055 // 'foo' to equal C. There are restrictions on class-heads
10056 // (which we declare (by fiat) elaborated friend declarations to
10057 // be) that makes this tractable.
10058 //
10059 // FIXME: handle "template <> friend class A<T>;", which
10060 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010061 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010062 Diag(Loc, diag::err_tagless_friend_type_template)
10063 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010064 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010065 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010066
John McCall02cace72009-08-28 07:59:38 +000010067 // C++98 [class.friend]p1: A friend of a class is a function
10068 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010069 // This is fixed in DR77, which just barely didn't make the C++03
10070 // deadline. It's also a very silly restriction that seriously
10071 // affects inner classes and which nobody else seems to implement;
10072 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010073 //
10074 // But note that we could warn about it: it's always useless to
10075 // friend one of your own members (it's not, however, worthless to
10076 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010077
John McCalldd4a3b02009-09-16 22:47:08 +000010078 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010079 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010080 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010081 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010082 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010083 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010084 DS.getFriendSpecLoc());
10085 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010086 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010087
10088 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010089 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010090
John McCalldd4a3b02009-09-16 22:47:08 +000010091 D->setAccess(AS_public);
10092 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010093
John McCalld226f652010-08-21 09:40:31 +000010094 return D;
John McCall02cace72009-08-28 07:59:38 +000010095}
10096
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010097Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010098 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010099 const DeclSpec &DS = D.getDeclSpec();
10100
10101 assert(DS.isFriendSpecified());
10102 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10103
10104 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010105 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010106
10107 // C++ [class.friend]p1
10108 // A friend of a class is a function or class....
10109 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010110 // It *doesn't* see through dependent types, which is correct
10111 // according to [temp.arg.type]p3:
10112 // If a declaration acquires a function type through a
10113 // type dependent on a template-parameter and this causes
10114 // a declaration that does not use the syntactic form of a
10115 // function declarator to have a function type, the program
10116 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010117 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010118 Diag(Loc, diag::err_unexpected_friend);
10119
10120 // It might be worthwhile to try to recover by creating an
10121 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010122 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010123 }
10124
10125 // C++ [namespace.memdef]p3
10126 // - If a friend declaration in a non-local class first declares a
10127 // class or function, the friend class or function is a member
10128 // of the innermost enclosing namespace.
10129 // - The name of the friend is not found by simple name lookup
10130 // until a matching declaration is provided in that namespace
10131 // scope (either before or after the class declaration granting
10132 // friendship).
10133 // - If a friend function is called, its name may be found by the
10134 // name lookup that considers functions from namespaces and
10135 // classes associated with the types of the function arguments.
10136 // - When looking for a prior declaration of a class or a function
10137 // declared as a friend, scopes outside the innermost enclosing
10138 // namespace scope are not considered.
10139
John McCall337ec3d2010-10-12 23:13:28 +000010140 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010141 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10142 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010143 assert(Name);
10144
Douglas Gregor6ccab972010-12-16 01:14:37 +000010145 // Check for unexpanded parameter packs.
10146 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10147 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10148 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10149 return 0;
10150
John McCall67d1a672009-08-06 02:15:43 +000010151 // The context we found the declaration in, or in which we should
10152 // create the declaration.
10153 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010154 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010155 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010156 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010157
John McCall337ec3d2010-10-12 23:13:28 +000010158 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010159
John McCall337ec3d2010-10-12 23:13:28 +000010160 // There are four cases here.
10161 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010162 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010163 // there as appropriate.
10164 // Recover from invalid scope qualifiers as if they just weren't there.
10165 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010166 // C++0x [namespace.memdef]p3:
10167 // If the name in a friend declaration is neither qualified nor
10168 // a template-id and the declaration is a function or an
10169 // elaborated-type-specifier, the lookup to determine whether
10170 // the entity has been previously declared shall not consider
10171 // any scopes outside the innermost enclosing namespace.
10172 // C++0x [class.friend]p11:
10173 // If a friend declaration appears in a local class and the name
10174 // specified is an unqualified name, a prior declaration is
10175 // looked up without considering scopes that are outside the
10176 // innermost enclosing non-class scope. For a friend function
10177 // declaration, if there is no prior declaration, the program is
10178 // ill-formed.
10179 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010180 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010181
John McCall29ae6e52010-10-13 05:45:15 +000010182 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010183 DC = CurContext;
10184 while (true) {
10185 // Skip class contexts. If someone can cite chapter and verse
10186 // for this behavior, that would be nice --- it's what GCC and
10187 // EDG do, and it seems like a reasonable intent, but the spec
10188 // really only says that checks for unqualified existing
10189 // declarations should stop at the nearest enclosing namespace,
10190 // not that they should only consider the nearest enclosing
10191 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010192 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010193 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010194
John McCall68263142009-11-18 22:49:29 +000010195 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010196
10197 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010198 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010199 break;
John McCall29ae6e52010-10-13 05:45:15 +000010200
John McCall8a407372010-10-14 22:22:28 +000010201 if (isTemplateId) {
10202 if (isa<TranslationUnitDecl>(DC)) break;
10203 } else {
10204 if (DC->isFileContext()) break;
10205 }
John McCall67d1a672009-08-06 02:15:43 +000010206 DC = DC->getParent();
10207 }
10208
10209 // C++ [class.friend]p1: A friend of a class is a function or
10210 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010211 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010212 // Most C++ 98 compilers do seem to give an error here, so
10213 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010214 if (!Previous.empty() && DC->Equals(CurContext))
10215 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010216 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010217 diag::warn_cxx98_compat_friend_is_member :
10218 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010219
John McCall380aaa42010-10-13 06:22:15 +000010220 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010221
Douglas Gregor883af832011-10-10 01:11:59 +000010222 // C++ [class.friend]p6:
10223 // A function can be defined in a friend declaration of a class if and
10224 // only if the class is a non-local class (9.8), the function name is
10225 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010226 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010227 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10228 }
10229
John McCall337ec3d2010-10-12 23:13:28 +000010230 // - There's a non-dependent scope specifier, in which case we
10231 // compute it and do a previous lookup there for a function
10232 // or function template.
10233 } else if (!SS.getScopeRep()->isDependent()) {
10234 DC = computeDeclContext(SS);
10235 if (!DC) return 0;
10236
10237 if (RequireCompleteDeclContext(SS, DC)) return 0;
10238
10239 LookupQualifiedName(Previous, DC);
10240
10241 // Ignore things found implicitly in the wrong scope.
10242 // TODO: better diagnostics for this case. Suggesting the right
10243 // qualified scope would be nice...
10244 LookupResult::Filter F = Previous.makeFilter();
10245 while (F.hasNext()) {
10246 NamedDecl *D = F.next();
10247 if (!DC->InEnclosingNamespaceSetOf(
10248 D->getDeclContext()->getRedeclContext()))
10249 F.erase();
10250 }
10251 F.done();
10252
10253 if (Previous.empty()) {
10254 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010255 Diag(Loc, diag::err_qualified_friend_not_found)
10256 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010257 return 0;
10258 }
10259
10260 // C++ [class.friend]p1: A friend of a class is a function or
10261 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010262 if (DC->Equals(CurContext))
10263 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010264 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010265 diag::warn_cxx98_compat_friend_is_member :
10266 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010267
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010268 if (D.isFunctionDefinition()) {
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.
10273 SemaDiagnosticBuilder DB
10274 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10275
10276 DB << SS.getScopeRep();
10277 if (DC->isFileContext())
10278 DB << FixItHint::CreateRemoval(SS.getRange());
10279 SS.clear();
10280 }
John McCall337ec3d2010-10-12 23:13:28 +000010281
10282 // - There's a scope specifier that does not match any template
10283 // parameter lists, in which case we use some arbitrary context,
10284 // create a method or method template, and wait for instantiation.
10285 // - There's a scope specifier that does match some template
10286 // parameter lists, which we don't handle right now.
10287 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010288 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010289 // C++ [class.friend]p6:
10290 // A function can be defined in a friend declaration of a class if and
10291 // only if the class is a non-local class (9.8), the function name is
10292 // unqualified, and the function has namespace scope.
10293 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10294 << SS.getScopeRep();
10295 }
10296
John McCall337ec3d2010-10-12 23:13:28 +000010297 DC = CurContext;
10298 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010299 }
Douglas Gregor883af832011-10-10 01:11:59 +000010300
John McCall29ae6e52010-10-13 05:45:15 +000010301 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010302 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010303 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10304 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10305 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010306 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010307 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10308 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010309 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010310 }
John McCall67d1a672009-08-06 02:15:43 +000010311 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010312
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010313 // FIXME: This is an egregious hack to cope with cases where the scope stack
10314 // does not contain the declaration context, i.e., in an out-of-line
10315 // definition of a class.
10316 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10317 if (!DCScope) {
10318 FakeDCScope.setEntity(DC);
10319 DCScope = &FakeDCScope;
10320 }
10321
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010322 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010323 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10324 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010325 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010326
Douglas Gregor182ddf02009-09-28 00:08:27 +000010327 assert(ND->getDeclContext() == DC);
10328 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010329
John McCallab88d972009-08-31 22:39:49 +000010330 // Add the function declaration to the appropriate lookup tables,
10331 // adjusting the redeclarations list as necessary. We don't
10332 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010333 //
John McCallab88d972009-08-31 22:39:49 +000010334 // Also update the scope-based lookup if the target context's
10335 // lookup context is in lexical scope.
10336 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010337 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010338 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010339 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010340 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010341 }
John McCall02cace72009-08-28 07:59:38 +000010342
10343 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010344 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010345 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010346 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010347 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010348
John McCall1f2e1a92012-08-10 03:15:35 +000010349 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010350 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010351 } else {
10352 if (DC->isRecord()) CheckFriendAccess(ND);
10353
John McCall6102ca12010-10-16 06:59:13 +000010354 FunctionDecl *FD;
10355 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10356 FD = FTD->getTemplatedDecl();
10357 else
10358 FD = cast<FunctionDecl>(ND);
10359
10360 // Mark templated-scope function declarations as unsupported.
10361 if (FD->getNumTemplateParameterLists())
10362 FrD->setUnsupportedFriend(true);
10363 }
John McCall337ec3d2010-10-12 23:13:28 +000010364
John McCalld226f652010-08-21 09:40:31 +000010365 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010366}
10367
John McCalld226f652010-08-21 09:40:31 +000010368void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10369 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010370
Sebastian Redl50de12f2009-03-24 22:27:57 +000010371 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10372 if (!Fn) {
10373 Diag(DelLoc, diag::err_deleted_non_function);
10374 return;
10375 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010376 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010377 // Don't consider the implicit declaration we generate for explicit
10378 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010379 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10380 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010381 Diag(DelLoc, diag::err_deleted_decl_not_first);
10382 Diag(Prev->getLocation(), diag::note_previous_declaration);
10383 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010384 // If the declaration wasn't the first, we delete the function anyway for
10385 // recovery.
10386 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010387 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010388
10389 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10390 if (!MD)
10391 return;
10392
10393 // A deleted special member function is trivial if the corresponding
10394 // implicitly-declared function would have been.
10395 switch (getSpecialMember(MD)) {
10396 case CXXInvalid:
10397 break;
10398 case CXXDefaultConstructor:
10399 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10400 break;
10401 case CXXCopyConstructor:
10402 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10403 break;
10404 case CXXMoveConstructor:
10405 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10406 break;
10407 case CXXCopyAssignment:
10408 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10409 break;
10410 case CXXMoveAssignment:
10411 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10412 break;
10413 case CXXDestructor:
10414 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10415 break;
10416 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010417}
Sebastian Redl13e88542009-04-27 21:33:24 +000010418
Sean Hunte4246a62011-05-12 06:15:49 +000010419void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10420 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10421
10422 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010423 if (MD->getParent()->isDependentType()) {
10424 MD->setDefaulted();
10425 MD->setExplicitlyDefaulted();
10426 return;
10427 }
10428
Sean Hunte4246a62011-05-12 06:15:49 +000010429 CXXSpecialMember Member = getSpecialMember(MD);
10430 if (Member == CXXInvalid) {
10431 Diag(DefaultLoc, diag::err_default_special_members);
10432 return;
10433 }
10434
10435 MD->setDefaulted();
10436 MD->setExplicitlyDefaulted();
10437
Sean Huntcd10dec2011-05-23 23:14:04 +000010438 // If this definition appears within the record, do the checking when
10439 // the record is complete.
10440 const FunctionDecl *Primary = MD;
10441 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10442 // Find the uninstantiated declaration that actually had the '= default'
10443 // on it.
10444 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10445
10446 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010447 return;
10448
Richard Smithb9d0b762012-07-27 04:22:15 +000010449 CheckExplicitlyDefaultedSpecialMember(MD);
10450
Sean Hunte4246a62011-05-12 06:15:49 +000010451 switch (Member) {
10452 case CXXDefaultConstructor: {
10453 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010454 if (!CD->isInvalidDecl())
10455 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10456 break;
10457 }
10458
10459 case CXXCopyConstructor: {
10460 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010461 if (!CD->isInvalidDecl())
10462 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010463 break;
10464 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010465
Sean Hunt2b188082011-05-14 05:23:28 +000010466 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010467 if (!MD->isInvalidDecl())
10468 DefineImplicitCopyAssignment(DefaultLoc, MD);
10469 break;
10470 }
10471
Sean Huntcb45a0f2011-05-12 22:46:25 +000010472 case CXXDestructor: {
10473 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010474 if (!DD->isInvalidDecl())
10475 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010476 break;
10477 }
10478
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010479 case CXXMoveConstructor: {
10480 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010481 if (!CD->isInvalidDecl())
10482 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010483 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010484 }
Sean Hunt82713172011-05-25 23:16:36 +000010485
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010486 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010487 if (!MD->isInvalidDecl())
10488 DefineImplicitMoveAssignment(DefaultLoc, MD);
10489 break;
10490 }
10491
10492 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010493 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010494 }
10495 } else {
10496 Diag(DefaultLoc, diag::err_default_special_members);
10497 }
10498}
10499
Sebastian Redl13e88542009-04-27 21:33:24 +000010500static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010501 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010502 Stmt *SubStmt = *CI;
10503 if (!SubStmt)
10504 continue;
10505 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010506 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010507 diag::err_return_in_constructor_handler);
10508 if (!isa<Expr>(SubStmt))
10509 SearchForReturnInStmt(Self, SubStmt);
10510 }
10511}
10512
10513void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10514 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10515 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10516 SearchForReturnInStmt(*this, Handler);
10517 }
10518}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010519
Mike Stump1eb44332009-09-09 15:08:12 +000010520bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010521 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010522 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10523 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010524
Chandler Carruth73857792010-02-15 11:53:20 +000010525 if (Context.hasSameType(NewTy, OldTy) ||
10526 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010527 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010528
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010529 // Check if the return types are covariant
10530 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010531
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010532 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010533 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10534 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010535 NewClassTy = NewPT->getPointeeType();
10536 OldClassTy = OldPT->getPointeeType();
10537 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010538 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10539 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10540 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10541 NewClassTy = NewRT->getPointeeType();
10542 OldClassTy = OldRT->getPointeeType();
10543 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010544 }
10545 }
Mike Stump1eb44332009-09-09 15:08:12 +000010546
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 // The return types aren't either both pointers or references to a class type.
10548 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010549 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010550 diag::err_different_return_type_for_overriding_virtual_function)
10551 << New->getDeclName() << NewTy << OldTy;
10552 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010553
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010554 return true;
10555 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010556
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010557 // C++ [class.virtual]p6:
10558 // If the return type of D::f differs from the return type of B::f, the
10559 // class type in the return type of D::f shall be complete at the point of
10560 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010561 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10562 if (!RT->isBeingDefined() &&
10563 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010564 diag::err_covariant_return_incomplete,
10565 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010566 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010567 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010568
Douglas Gregora4923eb2009-11-16 21:35:15 +000010569 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010570 // Check if the new class derives from the old class.
10571 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10572 Diag(New->getLocation(),
10573 diag::err_covariant_return_not_derived)
10574 << New->getDeclName() << NewTy << OldTy;
10575 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10576 return true;
10577 }
Mike Stump1eb44332009-09-09 15:08:12 +000010578
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010579 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010580 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010581 diag::err_covariant_return_inaccessible_base,
10582 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10583 // FIXME: Should this point to the return type?
10584 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010585 // FIXME: this note won't trigger for delayed access control
10586 // diagnostics, and it's impossible to get an undelayed error
10587 // here from access control during the original parse because
10588 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010589 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10590 return true;
10591 }
10592 }
Mike Stump1eb44332009-09-09 15:08:12 +000010593
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010594 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010595 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010596 Diag(New->getLocation(),
10597 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010598 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010599 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10600 return true;
10601 };
Mike Stump1eb44332009-09-09 15:08:12 +000010602
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010603
10604 // The new class type must have the same or less qualifiers as the old type.
10605 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10606 Diag(New->getLocation(),
10607 diag::err_covariant_return_type_class_type_more_qualified)
10608 << New->getDeclName() << NewTy << OldTy;
10609 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10610 return true;
10611 };
Mike Stump1eb44332009-09-09 15:08:12 +000010612
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010613 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010614}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010615
Douglas Gregor4ba31362009-12-01 17:24:26 +000010616/// \brief Mark the given method pure.
10617///
10618/// \param Method the method to be marked pure.
10619///
10620/// \param InitRange the source range that covers the "0" initializer.
10621bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010622 SourceLocation EndLoc = InitRange.getEnd();
10623 if (EndLoc.isValid())
10624 Method->setRangeEnd(EndLoc);
10625
Douglas Gregor4ba31362009-12-01 17:24:26 +000010626 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10627 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010628 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010629 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010630
10631 if (!Method->isInvalidDecl())
10632 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10633 << Method->getDeclName() << InitRange;
10634 return true;
10635}
10636
Douglas Gregor552e2992012-02-21 02:22:07 +000010637/// \brief Determine whether the given declaration is a static data member.
10638static bool isStaticDataMember(Decl *D) {
10639 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10640 if (!Var)
10641 return false;
10642
10643 return Var->isStaticDataMember();
10644}
John McCall731ad842009-12-19 09:28:58 +000010645/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10646/// an initializer for the out-of-line declaration 'Dcl'. The scope
10647/// is a fresh scope pushed for just this purpose.
10648///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010649/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10650/// static data member of class X, names should be looked up in the scope of
10651/// class X.
John McCalld226f652010-08-21 09:40:31 +000010652void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010653 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010654 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010655
John McCall731ad842009-12-19 09:28:58 +000010656 // We should only get called for declarations with scope specifiers, like:
10657 // int foo::bar;
10658 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010659 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010660
10661 // If we are parsing the initializer for a static data member, push a
10662 // new expression evaluation context that is associated with this static
10663 // data member.
10664 if (isStaticDataMember(D))
10665 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010666}
10667
10668/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010669/// initializer for the out-of-line declaration 'D'.
10670void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010671 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010672 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010673
Douglas Gregor552e2992012-02-21 02:22:07 +000010674 if (isStaticDataMember(D))
10675 PopExpressionEvaluationContext();
10676
John McCall731ad842009-12-19 09:28:58 +000010677 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010678 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010679}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010680
10681/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10682/// C++ if/switch/while/for statement.
10683/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010684DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010685 // C++ 6.4p2:
10686 // The declarator shall not specify a function or an array.
10687 // The type-specifier-seq shall not contain typedef and shall not declare a
10688 // new class or enumeration.
10689 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10690 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010691
10692 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010693 if (!Dcl)
10694 return true;
10695
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010696 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10697 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010698 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010699 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010700 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010701
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010702 return Dcl;
10703}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010704
Douglas Gregordfe65432011-07-28 19:11:31 +000010705void Sema::LoadExternalVTableUses() {
10706 if (!ExternalSource)
10707 return;
10708
10709 SmallVector<ExternalVTableUse, 4> VTables;
10710 ExternalSource->ReadUsedVTables(VTables);
10711 SmallVector<VTableUse, 4> NewUses;
10712 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10713 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10714 = VTablesUsed.find(VTables[I].Record);
10715 // Even if a definition wasn't required before, it may be required now.
10716 if (Pos != VTablesUsed.end()) {
10717 if (!Pos->second && VTables[I].DefinitionRequired)
10718 Pos->second = true;
10719 continue;
10720 }
10721
10722 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10723 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10724 }
10725
10726 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10727}
10728
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010729void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10730 bool DefinitionRequired) {
10731 // Ignore any vtable uses in unevaluated operands or for classes that do
10732 // not have a vtable.
10733 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10734 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010735 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010736 return;
10737
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010738 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010739 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010740 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10741 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10742 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10743 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010744 // If we already had an entry, check to see if we are promoting this vtable
10745 // to required a definition. If so, we need to reappend to the VTableUses
10746 // list, since we may have already processed the first entry.
10747 if (DefinitionRequired && !Pos.first->second) {
10748 Pos.first->second = true;
10749 } else {
10750 // Otherwise, we can early exit.
10751 return;
10752 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010753 }
10754
10755 // Local classes need to have their virtual members marked
10756 // immediately. For all other classes, we mark their virtual members
10757 // at the end of the translation unit.
10758 if (Class->isLocalClass())
10759 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010760 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010761 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010762}
10763
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010764bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010765 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010766 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010767 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010768
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010769 // Note: The VTableUses vector could grow as a result of marking
10770 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010771 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010772 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010773 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010774 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010775 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010776 if (!Class)
10777 continue;
10778
10779 SourceLocation Loc = VTableUses[I].second;
10780
Richard Smithb9d0b762012-07-27 04:22:15 +000010781 bool DefineVTable = true;
10782
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010783 // If this class has a key function, but that key function is
10784 // defined in another translation unit, we don't need to emit the
10785 // vtable even though we're using it.
10786 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010787 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010788 switch (KeyFunction->getTemplateSpecializationKind()) {
10789 case TSK_Undeclared:
10790 case TSK_ExplicitSpecialization:
10791 case TSK_ExplicitInstantiationDeclaration:
10792 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010793 DefineVTable = false;
10794 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010795
10796 case TSK_ExplicitInstantiationDefinition:
10797 case TSK_ImplicitInstantiation:
10798 // We will be instantiating the key function.
10799 break;
10800 }
10801 } else if (!KeyFunction) {
10802 // If we have a class with no key function that is the subject
10803 // of an explicit instantiation declaration, suppress the
10804 // vtable; it will live with the explicit instantiation
10805 // definition.
10806 bool IsExplicitInstantiationDeclaration
10807 = Class->getTemplateSpecializationKind()
10808 == TSK_ExplicitInstantiationDeclaration;
10809 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10810 REnd = Class->redecls_end();
10811 R != REnd; ++R) {
10812 TemplateSpecializationKind TSK
10813 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10814 if (TSK == TSK_ExplicitInstantiationDeclaration)
10815 IsExplicitInstantiationDeclaration = true;
10816 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10817 IsExplicitInstantiationDeclaration = false;
10818 break;
10819 }
10820 }
10821
10822 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010823 DefineVTable = false;
10824 }
10825
10826 // The exception specifications for all virtual members may be needed even
10827 // if we are not providing an authoritative form of the vtable in this TU.
10828 // We may choose to emit it available_externally anyway.
10829 if (!DefineVTable) {
10830 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10831 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010832 }
10833
10834 // Mark all of the virtual members of this class as referenced, so
10835 // that we can build a vtable. Then, tell the AST consumer that a
10836 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010837 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010838 MarkVirtualMembersReferenced(Loc, Class);
10839 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10840 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10841
10842 // Optionally warn if we're emitting a weak vtable.
10843 if (Class->getLinkage() == ExternalLinkage &&
10844 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010845 const FunctionDecl *KeyFunctionDef = 0;
10846 if (!KeyFunction ||
10847 (KeyFunction->hasBody(KeyFunctionDef) &&
10848 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010849 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10850 TSK_ExplicitInstantiationDefinition
10851 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10852 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010853 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010854 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010855 VTableUses.clear();
10856
Douglas Gregor78844032011-04-22 22:25:37 +000010857 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010858}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010859
Richard Smithb9d0b762012-07-27 04:22:15 +000010860void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10861 const CXXRecordDecl *RD) {
10862 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10863 E = RD->method_end(); I != E; ++I)
10864 if ((*I)->isVirtual() && !(*I)->isPure())
10865 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10866}
10867
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010868void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10869 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010870 // Mark all functions which will appear in RD's vtable as used.
10871 CXXFinalOverriderMap FinalOverriders;
10872 RD->getFinalOverriders(FinalOverriders);
10873 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10874 E = FinalOverriders.end();
10875 I != E; ++I) {
10876 for (OverridingMethods::const_iterator OI = I->second.begin(),
10877 OE = I->second.end();
10878 OI != OE; ++OI) {
10879 assert(OI->second.size() > 0 && "no final overrider");
10880 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010881
Richard Smithff817f72012-07-07 06:59:51 +000010882 // C++ [basic.def.odr]p2:
10883 // [...] A virtual member function is used if it is not pure. [...]
10884 if (!Overrider->isPure())
10885 MarkFunctionReferenced(Loc, Overrider);
10886 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010887 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010888
10889 // Only classes that have virtual bases need a VTT.
10890 if (RD->getNumVBases() == 0)
10891 return;
10892
10893 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10894 e = RD->bases_end(); i != e; ++i) {
10895 const CXXRecordDecl *Base =
10896 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010897 if (Base->getNumVBases() == 0)
10898 continue;
10899 MarkVirtualMembersReferenced(Loc, Base);
10900 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010901}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010902
10903/// SetIvarInitializers - This routine builds initialization ASTs for the
10904/// Objective-C implementation whose ivars need be initialized.
10905void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010906 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010907 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010908 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010909 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010910 CollectIvarsToConstructOrDestruct(OID, ivars);
10911 if (ivars.empty())
10912 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010913 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010914 for (unsigned i = 0; i < ivars.size(); i++) {
10915 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010916 if (Field->isInvalidDecl())
10917 continue;
10918
Sean Huntcbb67482011-01-08 20:30:50 +000010919 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010920 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10921 InitializationKind InitKind =
10922 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10923
10924 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010925 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010926 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010927 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010928 // Note, MemberInit could actually come back empty if no initialization
10929 // is required (e.g., because it would call a trivial default constructor)
10930 if (!MemberInit.get() || MemberInit.isInvalid())
10931 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010932
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010933 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010934 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10935 SourceLocation(),
10936 MemberInit.takeAs<Expr>(),
10937 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010938 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010939
10940 // Be sure that the destructor is accessible and is marked as referenced.
10941 if (const RecordType *RecordTy
10942 = Context.getBaseElementType(Field->getType())
10943 ->getAs<RecordType>()) {
10944 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010945 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010946 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010947 CheckDestructorAccess(Field->getLocation(), Destructor,
10948 PDiag(diag::err_access_dtor_ivar)
10949 << Context.getBaseElementType(Field->getType()));
10950 }
10951 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010952 }
10953 ObjCImplementation->setIvarInitializers(Context,
10954 AllToInit.data(), AllToInit.size());
10955 }
10956}
Sean Huntfe57eef2011-05-04 05:57:24 +000010957
Sean Huntebcbe1d2011-05-04 23:29:54 +000010958static
10959void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10960 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10961 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10962 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10963 Sema &S) {
10964 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10965 CE = Current.end();
10966 if (Ctor->isInvalidDecl())
10967 return;
10968
10969 const FunctionDecl *FNTarget = 0;
10970 CXXConstructorDecl *Target;
10971
10972 // We ignore the result here since if we don't have a body, Target will be
10973 // null below.
10974 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10975 Target
10976= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10977
10978 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10979 // Avoid dereferencing a null pointer here.
10980 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10981
10982 if (!Current.insert(Canonical))
10983 return;
10984
10985 // We know that beyond here, we aren't chaining into a cycle.
10986 if (!Target || !Target->isDelegatingConstructor() ||
10987 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10988 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10989 Valid.insert(*CI);
10990 Current.clear();
10991 // We've hit a cycle.
10992 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10993 Current.count(TCanonical)) {
10994 // If we haven't diagnosed this cycle yet, do so now.
10995 if (!Invalid.count(TCanonical)) {
10996 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010997 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010998 << Ctor;
10999
11000 // Don't add a note for a function delegating directo to itself.
11001 if (TCanonical != Canonical)
11002 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11003
11004 CXXConstructorDecl *C = Target;
11005 while (C->getCanonicalDecl() != Canonical) {
11006 (void)C->getTargetConstructor()->hasBody(FNTarget);
11007 assert(FNTarget && "Ctor cycle through bodiless function");
11008
11009 C
11010 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11011 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11012 }
11013 }
11014
11015 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11016 Invalid.insert(*CI);
11017 Current.clear();
11018 } else {
11019 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11020 }
11021}
11022
11023
Sean Huntfe57eef2011-05-04 05:57:24 +000011024void Sema::CheckDelegatingCtorCycles() {
11025 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11026
Sean Huntebcbe1d2011-05-04 23:29:54 +000011027 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11028 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011029
Douglas Gregor0129b562011-07-27 21:57:17 +000011030 for (DelegatingCtorDeclsType::iterator
11031 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011032 E = DelegatingCtorDecls.end();
11033 I != E; ++I) {
11034 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011035 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011036
11037 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11038 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011039}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011040
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011041namespace {
11042 /// \brief AST visitor that finds references to the 'this' expression.
11043 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11044 Sema &S;
11045
11046 public:
11047 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11048
11049 bool VisitCXXThisExpr(CXXThisExpr *E) {
11050 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11051 << E->isImplicit();
11052 return false;
11053 }
11054 };
11055}
11056
11057bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11058 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11059 if (!TSInfo)
11060 return false;
11061
11062 TypeLoc TL = TSInfo->getTypeLoc();
11063 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11064 if (!ProtoTL)
11065 return false;
11066
11067 // C++11 [expr.prim.general]p3:
11068 // [The expression this] shall not appear before the optional
11069 // cv-qualifier-seq and it shall not appear within the declaration of a
11070 // static member function (although its type and value category are defined
11071 // within a static member function as they are within a non-static member
11072 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011073 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011074 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11075 FindCXXThisExpr Finder(*this);
11076
11077 // If the return type came after the cv-qualifier-seq, check it now.
11078 if (Proto->hasTrailingReturn() &&
11079 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11080 return true;
11081
11082 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011083 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11084 return true;
11085
11086 return checkThisInStaticMemberFunctionAttributes(Method);
11087}
11088
11089bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11090 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11091 if (!TSInfo)
11092 return false;
11093
11094 TypeLoc TL = TSInfo->getTypeLoc();
11095 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11096 if (!ProtoTL)
11097 return false;
11098
11099 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11100 FindCXXThisExpr Finder(*this);
11101
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011102 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011103 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011104 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011105 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011106 case EST_DynamicNone:
11107 case EST_MSAny:
11108 case EST_None:
11109 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011110
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011111 case EST_ComputedNoexcept:
11112 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11113 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011114
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011115 case EST_Dynamic:
11116 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011117 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011118 E != EEnd; ++E) {
11119 if (!Finder.TraverseType(*E))
11120 return true;
11121 }
11122 break;
11123 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011124
11125 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011126}
11127
11128bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11129 FindCXXThisExpr Finder(*this);
11130
11131 // Check attributes.
11132 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11133 A != AEnd; ++A) {
11134 // FIXME: This should be emitted by tblgen.
11135 Expr *Arg = 0;
11136 ArrayRef<Expr *> Args;
11137 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11138 Arg = G->getArg();
11139 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11140 Arg = G->getArg();
11141 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11142 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11143 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11144 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11145 else if (ExclusiveLockFunctionAttr *ELF
11146 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11147 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11148 else if (SharedLockFunctionAttr *SLF
11149 = dyn_cast<SharedLockFunctionAttr>(*A))
11150 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11151 else if (ExclusiveTrylockFunctionAttr *ETLF
11152 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11153 Arg = ETLF->getSuccessValue();
11154 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11155 } else if (SharedTrylockFunctionAttr *STLF
11156 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11157 Arg = STLF->getSuccessValue();
11158 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11159 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11160 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11161 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11162 Arg = LR->getArg();
11163 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11164 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11165 else if (ExclusiveLocksRequiredAttr *ELR
11166 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11167 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11168 else if (SharedLocksRequiredAttr *SLR
11169 = dyn_cast<SharedLocksRequiredAttr>(*A))
11170 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11171
11172 if (Arg && !Finder.TraverseStmt(Arg))
11173 return true;
11174
11175 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11176 if (!Finder.TraverseStmt(Args[I]))
11177 return true;
11178 }
11179 }
11180
11181 return false;
11182}
11183
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011184void
11185Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11186 ArrayRef<ParsedType> DynamicExceptions,
11187 ArrayRef<SourceRange> DynamicExceptionRanges,
11188 Expr *NoexceptExpr,
11189 llvm::SmallVectorImpl<QualType> &Exceptions,
11190 FunctionProtoType::ExtProtoInfo &EPI) {
11191 Exceptions.clear();
11192 EPI.ExceptionSpecType = EST;
11193 if (EST == EST_Dynamic) {
11194 Exceptions.reserve(DynamicExceptions.size());
11195 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11196 // FIXME: Preserve type source info.
11197 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11198
11199 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11200 collectUnexpandedParameterPacks(ET, Unexpanded);
11201 if (!Unexpanded.empty()) {
11202 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11203 UPPC_ExceptionType,
11204 Unexpanded);
11205 continue;
11206 }
11207
11208 // Check that the type is valid for an exception spec, and
11209 // drop it if not.
11210 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11211 Exceptions.push_back(ET);
11212 }
11213 EPI.NumExceptions = Exceptions.size();
11214 EPI.Exceptions = Exceptions.data();
11215 return;
11216 }
11217
11218 if (EST == EST_ComputedNoexcept) {
11219 // If an error occurred, there's no expression here.
11220 if (NoexceptExpr) {
11221 assert((NoexceptExpr->isTypeDependent() ||
11222 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11223 Context.BoolTy) &&
11224 "Parser should have made sure that the expression is boolean");
11225 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11226 EPI.ExceptionSpecType = EST_BasicNoexcept;
11227 return;
11228 }
11229
11230 if (!NoexceptExpr->isValueDependent())
11231 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011232 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011233 /*AllowFold*/ false).take();
11234 EPI.NoexceptExpr = NoexceptExpr;
11235 }
11236 return;
11237 }
11238}
11239
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011240/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11241Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11242 // Implicitly declared functions (e.g. copy constructors) are
11243 // __host__ __device__
11244 if (D->isImplicit())
11245 return CFT_HostDevice;
11246
11247 if (D->hasAttr<CUDAGlobalAttr>())
11248 return CFT_Global;
11249
11250 if (D->hasAttr<CUDADeviceAttr>()) {
11251 if (D->hasAttr<CUDAHostAttr>())
11252 return CFT_HostDevice;
11253 else
11254 return CFT_Device;
11255 }
11256
11257 return CFT_Host;
11258}
11259
11260bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11261 CUDAFunctionTarget CalleeTarget) {
11262 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11263 // Callable from the device only."
11264 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11265 return true;
11266
11267 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11268 // Callable from the host only."
11269 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11270 // Callable from the host only."
11271 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11272 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11273 return true;
11274
11275 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11276 return true;
11277
11278 return false;
11279}