blob: c59e97af72a7de5588e1204dac85846293a778bf [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000029#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000030#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000034#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000037#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000038#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000039
40using namespace clang;
41
Chris Lattner8123a952008-04-10 02:22:51 +000042//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
Chris Lattner9e979552008-04-12 23:52:44 +000046namespace {
47 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48 /// the default argument of a parameter to determine whether it
49 /// contains any ill-formed subexpressions. For example, this will
50 /// diagnose the use of local variables or parameters within the
51 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000052 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000053 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000054 Expr *DefaultArg;
55 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000056
Chris Lattner9e979552008-04-12 23:52:44 +000057 public:
Mike Stump1eb44332009-09-09 15:08:12 +000058 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000059 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 bool VisitExpr(Expr *Node);
62 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000063 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000064 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000065 };
Chris Lattner8123a952008-04-10 02:22:51 +000066
Chris Lattner9e979552008-04-12 23:52:44 +000067 /// VisitExpr - Visit all of the children of this expression.
68 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
69 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000070 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000071 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000072 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000073 }
74
Chris Lattner9e979552008-04-12 23:52:44 +000075 /// VisitDeclRefExpr - Visit a reference to a declaration, to
76 /// determine whether this declaration can be used in the default
77 /// argument expression.
78 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000080 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
81 // C++ [dcl.fct.default]p9
82 // Default arguments are evaluated each time the function is
83 // called. The order of evaluation of function arguments is
84 // unspecified. Consequently, parameters of a function shall not
85 // be used in default argument expressions, even if they are not
86 // evaluated. Parameters of a function declared before a default
87 // argument expression are in scope and can hide namespace and
88 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000089 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000091 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000092 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000093 // C++ [dcl.fct.default]p7
94 // Local variables shall not be used in default argument
95 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000096 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000097 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000099 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-04-10 02:22:51 +0000101
Douglas Gregor3996f232008-11-04 13:41:56 +0000102 return false;
103 }
Chris Lattner9e979552008-04-12 23:52:44 +0000104
Douglas Gregor796da182008-11-04 14:32:21 +0000105 /// VisitCXXThisExpr - Visit a C++ "this" expression.
106 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
107 // C++ [dcl.fct.default]p8:
108 // The keyword this shall not be used in a default argument of a
109 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000110 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000111 diag::err_param_default_argument_references_this)
112 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000113 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000114
115 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
116 // C++11 [expr.lambda.prim]p13:
117 // A lambda-expression appearing in a default argument shall not
118 // implicitly or explicitly capture any entity.
119 if (Lambda->capture_begin() == Lambda->capture_end())
120 return false;
121
122 return S->Diag(Lambda->getLocStart(),
123 diag::err_lambda_capture_default_arg);
124 }
Chris Lattner8123a952008-04-10 02:22:51 +0000125}
126
Sean Hunt001cad92011-05-10 00:49:42 +0000127void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000128 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000129 // If we have an MSAny or unknown spec already, don't bother.
130 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000131 return;
132
133 const FunctionProtoType *Proto
134 = Method->getType()->getAs<FunctionProtoType>();
135
136 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
137
138 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000139 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000140 ClearExceptions();
141 ComputedEST = EST;
142 return;
143 }
144
Richard Smith7a614d82011-06-11 17:19:42 +0000145 // FIXME: If the call to this decl is using any of its default arguments, we
146 // need to search them for potentially-throwing calls.
147
Sean Hunt001cad92011-05-10 00:49:42 +0000148 // If this function has a basic noexcept, it doesn't affect the outcome.
149 if (EST == EST_BasicNoexcept)
150 return;
151
152 // If we have a throw-all spec at this point, ignore the function.
153 if (ComputedEST == EST_None)
154 return;
155
156 // If we're still at noexcept(true) and there's a nothrow() callee,
157 // change to that specification.
158 if (EST == EST_DynamicNone) {
159 if (ComputedEST == EST_BasicNoexcept)
160 ComputedEST = EST_DynamicNone;
161 return;
162 }
163
164 // Check out noexcept specs.
165 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000166 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000167 assert(NR != FunctionProtoType::NR_NoNoexcept &&
168 "Must have noexcept result for EST_ComputedNoexcept.");
169 assert(NR != FunctionProtoType::NR_Dependent &&
170 "Should not generate implicit declarations for dependent cases, "
171 "and don't know how to handle them anyway.");
172
173 // noexcept(false) -> no spec on the new function
174 if (NR == FunctionProtoType::NR_Throw) {
175 ClearExceptions();
176 ComputedEST = EST_None;
177 }
178 // noexcept(true) won't change anything either.
179 return;
180 }
181
182 assert(EST == EST_Dynamic && "EST case not considered earlier.");
183 assert(ComputedEST != EST_None &&
184 "Shouldn't collect exceptions when throw-all is guaranteed.");
185 ComputedEST = EST_Dynamic;
186 // Record the exceptions in this function's exception specification.
187 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
188 EEnd = Proto->exception_end();
189 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000190 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000191 Exceptions.push_back(*E);
192}
193
Richard Smith7a614d82011-06-11 17:19:42 +0000194void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
195 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
196 return;
197
198 // FIXME:
199 //
200 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000201 // [An] implicit exception-specification specifies the type-id T if and
202 // only if T is allowed by the exception-specification of a function directly
203 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000204 // function it directly invokes allows all exceptions, and f shall allow no
205 // exceptions if every function it directly invokes allows no exceptions.
206 //
207 // Note in particular that if an implicit exception-specification is generated
208 // for a function containing a throw-expression, that specification can still
209 // be noexcept(true).
210 //
211 // Note also that 'directly invoked' is not defined in the standard, and there
212 // is no indication that we should only consider potentially-evaluated calls.
213 //
214 // Ultimately we should implement the intent of the standard: the exception
215 // specification should be the set of exceptions which can be thrown by the
216 // implicit definition. For now, we assume that any non-nothrow expression can
217 // throw any exception.
218
219 if (E->CanThrow(*Context))
220 ComputedEST = EST_None;
221}
222
Anders Carlssoned961f92009-08-25 02:29:20 +0000223bool
John McCall9ae2f072010-08-23 23:25:46 +0000224Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000226 if (RequireCompleteType(Param->getLocation(), Param->getType(),
227 diag::err_typecheck_decl_incomplete_type)) {
228 Param->setInvalidDecl();
229 return true;
230 }
231
Anders Carlssoned961f92009-08-25 02:29:20 +0000232 // C++ [dcl.fct.default]p5
233 // A default argument expression is implicitly converted (clause
234 // 4) to the parameter type. The default argument expression has
235 // the same semantic constraints as the initializer expression in
236 // a declaration of a variable of the parameter type, using the
237 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000238 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
239 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000240 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
241 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000242 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000243 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000244 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000245 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000246 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000247 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000248
John McCallb4eb64d2010-10-08 02:01:28 +0000249 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000250 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Anders Carlssoned961f92009-08-25 02:29:20 +0000252 // Okay: add the default argument to the parameter
253 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000255 // We have already instantiated this parameter; provide each of the
256 // instantiations with the uninstantiated default argument.
257 UnparsedDefaultArgInstantiationsMap::iterator InstPos
258 = UnparsedDefaultArgInstantiations.find(Param);
259 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
260 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
261 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
262
263 // We're done tracking this parameter's instantiations.
264 UnparsedDefaultArgInstantiations.erase(InstPos);
265 }
266
Anders Carlsson9351c172009-08-25 03:18:48 +0000267 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000268}
269
Chris Lattner8123a952008-04-10 02:22:51 +0000270/// ActOnParamDefaultArgument - Check whether the default argument
271/// provided for a function parameter is well-formed. If so, attach it
272/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000273void
John McCalld226f652010-08-21 09:40:31 +0000274Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000275 Expr *DefaultArg) {
276 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000277 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
John McCalld226f652010-08-21 09:40:31 +0000279 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000280 UnparsedDefaultArgLocs.erase(Param);
281
Chris Lattner3d1cee32008-04-08 05:04:30 +0000282 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000283 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 Diag(EqualLoc, diag::err_param_default_argument)
285 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000286 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 return;
288 }
289
Douglas Gregor6f526752010-12-16 08:48:57 +0000290 // Check for unexpanded parameter packs.
291 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
292 Param->setInvalidDecl();
293 return;
294 }
295
Anders Carlsson66e30672009-08-25 01:02:06 +0000296 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000297 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
298 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000299 Param->setInvalidDecl();
300 return;
301 }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCall9ae2f072010-08-23 23:25:46 +0000303 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000304}
305
Douglas Gregor61366e92008-12-24 00:01:03 +0000306/// ActOnParamUnparsedDefaultArgument - We've seen a default
307/// argument for a function parameter, but we can't parse it yet
308/// because we're inside a class definition. Note that this default
309/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000310void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000311 SourceLocation EqualLoc,
312 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000317 if (Param)
318 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000321}
322
Douglas Gregor72b505b2008-12-16 21:30:33 +0000323/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
324/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000325void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000326 if (!param)
327 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCalld226f652010-08-21 09:40:31 +0000329 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Anders Carlsson5e300d12009-06-12 16:51:40 +0000331 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Anders Carlsson5e300d12009-06-12 16:51:40 +0000333 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000334}
335
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000336/// CheckExtraCXXDefaultArguments - Check for any extra default
337/// arguments in the declarator, which is not a function declaration
338/// or definition and therefore is not permitted to have default
339/// arguments. This routine should be invoked for every declarator
340/// that is not a function declaration or definition.
341void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
342 // C++ [dcl.fct.default]p3
343 // A default argument expression shall be specified only in the
344 // parameter-declaration-clause of a function declaration or in a
345 // template-parameter (14.1). It shall not be specified for a
346 // parameter pack. If it is specified in a
347 // parameter-declaration-clause, it shall not occur within a
348 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000349 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000350 DeclaratorChunk &chunk = D.getTypeObject(i);
351 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000352 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
353 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000354 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000355 if (Param->hasUnparsedDefaultArg()) {
356 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000357 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
358 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
359 delete Toks;
360 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 } else if (Param->getDefaultArg()) {
362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << Param->getDefaultArg()->getSourceRange();
364 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000365 }
366 }
367 }
368 }
369}
370
Chris Lattner3d1cee32008-04-08 05:04:30 +0000371// MergeCXXFunctionDecl - Merge two declarations of the same C++
372// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000373// type. Subroutine of MergeFunctionDecl. Returns true if there was an
374// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000375bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
376 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000377 bool Invalid = false;
378
Chris Lattner3d1cee32008-04-08 05:04:30 +0000379 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 // For non-template functions, default arguments can be added in
381 // later declarations of a function in the same
382 // scope. Declarations in different scopes have completely
383 // distinct sets of default arguments. That is, declarations in
384 // inner scopes do not acquire default arguments from
385 // declarations in outer scopes, and vice versa. In a given
386 // function declaration, all parameters subsequent to a
387 // parameter with a default argument shall have default
388 // arguments supplied in this or previous declarations. A
389 // default argument shall not be redefined by a later
390 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000391 //
392 // C++ [dcl.fct.default]p6:
393 // Except for member functions of class templates, the default arguments
394 // in a member function definition that appears outside of the class
395 // definition are added to the set of default arguments provided by the
396 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
398 ParmVarDecl *OldParam = Old->getParamDecl(p);
399 ParmVarDecl *NewParam = New->getParamDecl(p);
400
James Molloy9cda03f2012-03-13 08:55:35 +0000401 bool OldParamHasDfl = OldParam->hasDefaultArg();
402 bool NewParamHasDfl = NewParam->hasDefaultArg();
403
404 NamedDecl *ND = Old;
405 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
406 // Ignore default parameters of old decl if they are not in
407 // the same scope.
408 OldParamHasDfl = false;
409
410 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000411
Francois Pichet8d051e02011-04-10 03:03:52 +0000412 unsigned DiagDefaultParamID =
413 diag::err_param_default_argument_redefinition;
414
415 // MSVC accepts that default parameters be redefined for member functions
416 // of template class. The new default parameter's value is ignored.
417 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000418 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000419 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
420 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000421 // Merge the old default argument into the new parameter.
422 NewParam->setHasInheritedDefaultArg();
423 if (OldParam->hasUninstantiatedDefaultArg())
424 NewParam->setUninstantiatedDefaultArg(
425 OldParam->getUninstantiatedDefaultArg());
426 else
427 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000428 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000429 Invalid = false;
430 }
431 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000432
Francois Pichet8cf90492011-04-10 04:58:30 +0000433 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
434 // hint here. Alternatively, we could walk the type-source information
435 // for NewParam to find the last source location in the type... but it
436 // isn't worth the effort right now. This is the kind of test case that
437 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438 // int f(int);
439 // void g(int (*fp)(int) = f);
440 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000441 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000442 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443
444 // Look for the function declaration where the default argument was
445 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000446 for (FunctionDecl *Older = Old->getPreviousDecl();
447 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448 if (!Older->getParamDecl(p)->hasDefaultArg())
449 break;
450
451 OldParam = Older->getParamDecl(p);
452 }
453
454 Diag(OldParam->getLocation(), diag::note_previous_definition)
455 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000456 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000457 // Merge the old default argument into the new parameter.
458 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000459 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000460 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000461 if (OldParam->hasUninstantiatedDefaultArg())
462 NewParam->setUninstantiatedDefaultArg(
463 OldParam->getUninstantiatedDefaultArg());
464 else
John McCall3d6c1782010-05-04 01:53:42 +0000465 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000466 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 if (New->getDescribedFunctionTemplate()) {
468 // Paragraph 4, quoted above, only applies to non-template functions.
469 Diag(NewParam->getLocation(),
470 diag::err_param_default_argument_template_redecl)
471 << NewParam->getDefaultArgRange();
472 Diag(Old->getLocation(), diag::note_template_prev_declaration)
473 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000474 } else if (New->getTemplateSpecializationKind()
475 != TSK_ImplicitInstantiation &&
476 New->getTemplateSpecializationKind() != TSK_Undeclared) {
477 // C++ [temp.expr.spec]p21:
478 // Default function arguments shall not be specified in a declaration
479 // or a definition for one of the following explicit specializations:
480 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000481 // - the explicit specialization of a member function template;
482 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000483 // template where the class template specialization to which the
484 // member function specialization belongs is implicitly
485 // instantiated.
486 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
487 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
488 << New->getDeclName()
489 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000490 } else if (New->getDeclContext()->isDependentContext()) {
491 // C++ [dcl.fct.default]p6 (DR217):
492 // Default arguments for a member function of a class template shall
493 // be specified on the initial declaration of the member function
494 // within the class template.
495 //
496 // Reading the tea leaves a bit in DR217 and its reference to DR205
497 // leads me to the conclusion that one cannot add default function
498 // arguments for an out-of-line definition of a member function of a
499 // dependent type.
500 int WhichKind = 2;
501 if (CXXRecordDecl *Record
502 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
503 if (Record->getDescribedClassTemplate())
504 WhichKind = 0;
505 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
506 WhichKind = 1;
507 else
508 WhichKind = 2;
509 }
510
511 Diag(NewParam->getLocation(),
512 diag::err_param_default_argument_member_template_redecl)
513 << WhichKind
514 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000515 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
516 CXXSpecialMember NewSM = getSpecialMember(Ctor),
517 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
518 if (NewSM != OldSM) {
519 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
520 << NewParam->getDefaultArgRange() << NewSM;
521 Diag(Old->getLocation(), diag::note_previous_declaration_special)
522 << OldSM;
523 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000524 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000525 }
526 }
527
Richard Smithff234882012-02-20 23:28:05 +0000528 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000529 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000530 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000531 if (New->isConstexpr() != Old->isConstexpr()) {
532 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
533 << New << New->isConstexpr();
534 Diag(Old->getLocation(), diag::note_previous_declaration);
535 Invalid = true;
536 }
537
Douglas Gregore13ad832010-02-12 07:32:17 +0000538 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000539 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000540
Douglas Gregorcda9c672009-02-16 17:45:42 +0000541 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000542}
543
Sebastian Redl60618fa2011-03-12 11:50:43 +0000544/// \brief Merge the exception specifications of two variable declarations.
545///
546/// This is called when there's a redeclaration of a VarDecl. The function
547/// checks if the redeclaration might have an exception specification and
548/// validates compatibility and merges the specs if necessary.
549void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
550 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000551 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000552 return;
553
554 assert(Context.hasSameType(New->getType(), Old->getType()) &&
555 "Should only be called if types are otherwise the same.");
556
557 QualType NewType = New->getType();
558 QualType OldType = Old->getType();
559
560 // We're only interested in pointers and references to functions, as well
561 // as pointers to member functions.
562 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
563 NewType = R->getPointeeType();
564 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
565 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
566 NewType = P->getPointeeType();
567 OldType = OldType->getAs<PointerType>()->getPointeeType();
568 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
569 NewType = M->getPointeeType();
570 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
571 }
572
573 if (!NewType->isFunctionProtoType())
574 return;
575
576 // There's lots of special cases for functions. For function pointers, system
577 // libraries are hopefully not as broken so that we don't need these
578 // workarounds.
579 if (CheckEquivalentExceptionSpec(
580 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
581 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
582 New->setInvalidDecl();
583 }
584}
585
Chris Lattner3d1cee32008-04-08 05:04:30 +0000586/// CheckCXXDefaultArguments - Verify that the default arguments for a
587/// function declaration are well-formed according to C++
588/// [dcl.fct.default].
589void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
590 unsigned NumParams = FD->getNumParams();
591 unsigned p;
592
Douglas Gregorc6889e72012-02-14 22:28:59 +0000593 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
594 isa<CXXMethodDecl>(FD) &&
595 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
596
Chris Lattner3d1cee32008-04-08 05:04:30 +0000597 // Find first parameter with a default argument
598 for (p = 0; p < NumParams; ++p) {
599 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000600 if (Param->hasDefaultArg()) {
601 // C++11 [expr.prim.lambda]p5:
602 // [...] Default arguments (8.3.6) shall not be specified in the
603 // parameter-declaration-clause of a lambda-declarator.
604 //
605 // FIXME: Core issue 974 strikes this sentence, we only provide an
606 // extension warning.
607 if (IsLambda)
608 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
609 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000611 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000612 }
613
614 // C++ [dcl.fct.default]p4:
615 // In a given function declaration, all parameters
616 // subsequent to a parameter with a default argument shall
617 // have default arguments supplied in this or previous
618 // declarations. A default argument shall not be redefined
619 // by a later declaration (not even to the same value).
620 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000621 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000622 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000623 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000624 if (Param->isInvalidDecl())
625 /* We already complained about this parameter. */;
626 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000627 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000629 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000630 else
Mike Stump1eb44332009-09-09 15:08:12 +0000631 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000632 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 LastMissingDefaultArg = p;
635 }
636 }
637
638 if (LastMissingDefaultArg > 0) {
639 // Some default arguments were missing. Clear out all of the
640 // default arguments up to (and including) the last missing
641 // default argument, so that we leave the function parameters
642 // in a semantically valid state.
643 for (p = 0; p <= LastMissingDefaultArg; ++p) {
644 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000645 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 Param->setDefaultArg(0);
647 }
648 }
649 }
650}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000651
Richard Smith9f569cc2011-10-01 02:31:28 +0000652// CheckConstexprParameterTypes - Check whether a function's parameter types
653// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000654// diagnostic and return false.
655static bool CheckConstexprParameterTypes(Sema &SemaRef,
656 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000657 unsigned ArgIndex = 0;
658 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
659 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
660 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
661 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
662 SourceLocation ParamLoc = PD->getLocation();
663 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000664 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smith9f569cc2011-10-01 02:31:28 +0000665 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
666 << ArgIndex+1 << PD->getSourceRange()
Richard Smith86c3ae42012-02-13 03:54:03 +0000667 << isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000668 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000669 }
670 return true;
671}
672
673// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000674// the requirements of a constexpr function definition or a constexpr
675// constructor definition. If so, return true. If not, produce appropriate
676// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000677//
Richard Smith86c3ae42012-02-13 03:54:03 +0000678// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
679bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000680 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
681 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000682 // C++11 [dcl.constexpr]p4:
683 // The definition of a constexpr constructor shall satisfy the following
684 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000685 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000686 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000687 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
689 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
690 << RD->getNumVBases();
691 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
692 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000693 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000694 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000695 return false;
696 }
Richard Smith35340502012-01-13 04:54:00 +0000697 }
698
699 if (!isa<CXXConstructorDecl>(NewFD)) {
700 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 // The definition of a constexpr function shall satisfy the following
702 // constraints:
703 // - it shall not be virtual;
704 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
705 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000706 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000707
Richard Smith86c3ae42012-02-13 03:54:03 +0000708 // If it's not obvious why this function is virtual, find an overridden
709 // function which uses the 'virtual' keyword.
710 const CXXMethodDecl *WrittenVirtual = Method;
711 while (!WrittenVirtual->isVirtualAsWritten())
712 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
713 if (WrittenVirtual != Method)
714 Diag(WrittenVirtual->getLocation(),
715 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000716 return false;
717 }
718
719 // - its return type shall be a literal type;
720 QualType RT = NewFD->getResultType();
721 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000722 RequireLiteralType(NewFD->getLocation(), RT,
723 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000724 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 }
726
Richard Smith35340502012-01-13 04:54:00 +0000727 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000729 return false;
730
Richard Smith9f569cc2011-10-01 02:31:28 +0000731 return true;
732}
733
734/// Check the given declaration statement is legal within a constexpr function
735/// body. C++0x [dcl.constexpr]p3,p4.
736///
737/// \return true if the body is OK, false if we have diagnosed a problem.
738static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
739 DeclStmt *DS) {
740 // C++0x [dcl.constexpr]p3 and p4:
741 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
742 // contain only
743 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
744 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
745 switch ((*DclIt)->getKind()) {
746 case Decl::StaticAssert:
747 case Decl::Using:
748 case Decl::UsingShadow:
749 case Decl::UsingDirective:
750 case Decl::UnresolvedUsingTypename:
751 // - static_assert-declarations
752 // - using-declarations,
753 // - using-directives,
754 continue;
755
756 case Decl::Typedef:
757 case Decl::TypeAlias: {
758 // - typedef declarations and alias-declarations that do not define
759 // classes or enumerations,
760 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
761 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
762 // Don't allow variably-modified types in constexpr functions.
763 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
764 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
765 << TL.getSourceRange() << TL.getType()
766 << isa<CXXConstructorDecl>(Dcl);
767 return false;
768 }
769 continue;
770 }
771
772 case Decl::Enum:
773 case Decl::CXXRecord:
774 // As an extension, we allow the declaration (but not the definition) of
775 // classes and enumerations in all declarations, not just in typedef and
776 // alias declarations.
777 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
778 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
779 << isa<CXXConstructorDecl>(Dcl);
780 return false;
781 }
782 continue;
783
784 case Decl::Var:
785 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
786 << isa<CXXConstructorDecl>(Dcl);
787 return false;
788
789 default:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793 }
794 }
795
796 return true;
797}
798
799/// Check that the given field is initialized within a constexpr constructor.
800///
801/// \param Dcl The constexpr constructor being checked.
802/// \param Field The field being checked. This may be a member of an anonymous
803/// struct or union nested within the class being checked.
804/// \param Inits All declarations, including anonymous struct/union members and
805/// indirect members, for which any initialization was provided.
806/// \param Diagnosed Set to true if an error is produced.
807static void CheckConstexprCtorInitializer(Sema &SemaRef,
808 const FunctionDecl *Dcl,
809 FieldDecl *Field,
810 llvm::SmallSet<Decl*, 16> &Inits,
811 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000812 if (Field->isUnnamedBitfield())
813 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000814
815 if (Field->isAnonymousStructOrUnion() &&
816 Field->getType()->getAsCXXRecordDecl()->isEmpty())
817 return;
818
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 if (!Inits.count(Field)) {
820 if (!Diagnosed) {
821 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
822 Diagnosed = true;
823 }
824 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
825 } else if (Field->isAnonymousStructOrUnion()) {
826 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
827 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
828 I != E; ++I)
829 // If an anonymous union contains an anonymous struct of which any member
830 // is initialized, all members must be initialized.
831 if (!RD->isUnion() || Inits.count(*I))
832 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
833 }
834}
835
836/// Check the body for the given constexpr function declaration only contains
837/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
838///
839/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000841 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000842 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000843 // The definition of a constexpr function shall satisfy the following
844 // constraints: [...]
845 // - its function-body shall be = delete, = default, or a
846 // compound-statement
847 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // In the definition of a constexpr constructor, [...]
850 // - its function-body shall not be a function-try-block;
851 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
852 << isa<CXXConstructorDecl>(Dcl);
853 return false;
854 }
855
856 // - its function-body shall be [...] a compound-statement that contains only
857 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
858
859 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
860 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
861 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
862 switch ((*BodyIt)->getStmtClass()) {
863 case Stmt::NullStmtClass:
864 // - null statements,
865 continue;
866
867 case Stmt::DeclStmtClass:
868 // - static_assert-declarations
869 // - using-declarations,
870 // - using-directives,
871 // - typedef declarations and alias-declarations that do not define
872 // classes or enumerations,
873 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
874 return false;
875 continue;
876
877 case Stmt::ReturnStmtClass:
878 // - and exactly one return statement;
879 if (isa<CXXConstructorDecl>(Dcl))
880 break;
881
882 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000883 continue;
884
885 default:
886 break;
887 }
888
889 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 if (const CXXConstructorDecl *Constructor
895 = dyn_cast<CXXConstructorDecl>(Dcl)) {
896 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000897 // DR1359:
898 // - every non-variant non-static data member and base class sub-object
899 // shall be initialized;
900 // - if the class is a non-empty union, or for each non-empty anonymous
901 // union member of a non-union class, exactly one non-static data member
902 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000903 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000904 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000905 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
906 return false;
907 }
Richard Smith6e433752011-10-10 16:38:04 +0000908 } else if (!Constructor->isDependentContext() &&
909 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
911
912 // Skip detailed checking if we have enough initializers, and we would
913 // allow at most one initializer per member.
914 bool AnyAnonStructUnionMembers = false;
915 unsigned Fields = 0;
916 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
917 E = RD->field_end(); I != E; ++I, ++Fields) {
918 if ((*I)->isAnonymousStructOrUnion()) {
919 AnyAnonStructUnionMembers = true;
920 break;
921 }
922 }
923 if (AnyAnonStructUnionMembers ||
924 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
925 // Check initialization of non-static data members. Base classes are
926 // always initialized so do not need to be checked. Dependent bases
927 // might not have initializers in the member initializer list.
928 llvm::SmallSet<Decl*, 16> Inits;
929 for (CXXConstructorDecl::init_const_iterator
930 I = Constructor->init_begin(), E = Constructor->init_end();
931 I != E; ++I) {
932 if (FieldDecl *FD = (*I)->getMember())
933 Inits.insert(FD);
934 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
935 Inits.insert(ID->chain_begin(), ID->chain_end());
936 }
937
938 bool Diagnosed = false;
939 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
940 E = RD->field_end(); I != E; ++I)
941 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
942 if (Diagnosed)
943 return false;
944 }
945 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 } else {
947 if (ReturnStmts.empty()) {
948 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
949 return false;
950 }
951 if (ReturnStmts.size() > 1) {
952 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
953 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
954 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
955 return false;
956 }
957 }
958
Richard Smith5ba73e12012-02-04 00:33:54 +0000959 // C++11 [dcl.constexpr]p5:
960 // if no function argument values exist such that the function invocation
961 // substitution would produce a constant expression, the program is
962 // ill-formed; no diagnostic required.
963 // C++11 [dcl.constexpr]p3:
964 // - every constructor call and implicit conversion used in initializing the
965 // return value shall be one of those allowed in a constant expression.
966 // C++11 [dcl.constexpr]p4:
967 // - every constructor involved in initializing non-static data members and
968 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000969 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000970 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000971 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
972 << isa<CXXConstructorDecl>(Dcl);
973 for (size_t I = 0, N = Diags.size(); I != N; ++I)
974 Diag(Diags[I].first, Diags[I].second);
975 return false;
976 }
977
Richard Smith9f569cc2011-10-01 02:31:28 +0000978 return true;
979}
980
Douglas Gregorb48fe382008-10-31 09:07:45 +0000981/// isCurrentClassName - Determine whether the identifier II is the
982/// name of the class type currently being defined. In the case of
983/// nested classes, this will only return true if II is the name of
984/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000985bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
986 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000987 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000988
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000989 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000990 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000991 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000992 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
993 } else
994 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
995
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000996 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000997 return &II == CurDecl->getIdentifier();
998 else
999 return false;
1000}
1001
Mike Stump1eb44332009-09-09 15:08:12 +00001002/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001003///
1004/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1005/// and returns NULL otherwise.
1006CXXBaseSpecifier *
1007Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1008 SourceRange SpecifierRange,
1009 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001010 TypeSourceInfo *TInfo,
1011 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001012 QualType BaseType = TInfo->getType();
1013
Douglas Gregor2943aed2009-03-03 04:44:36 +00001014 // C++ [class.union]p1:
1015 // A union shall not have base classes.
1016 if (Class->isUnion()) {
1017 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1018 << SpecifierRange;
1019 return 0;
1020 }
1021
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001022 if (EllipsisLoc.isValid() &&
1023 !TInfo->getType()->containsUnexpandedParameterPack()) {
1024 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1025 << TInfo->getTypeLoc().getSourceRange();
1026 EllipsisLoc = SourceLocation();
1027 }
1028
Douglas Gregor2943aed2009-03-03 04:44:36 +00001029 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001030 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001031 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001032 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001033
1034 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035
1036 // Base specifiers must be record types.
1037 if (!BaseType->isRecordType()) {
1038 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1039 return 0;
1040 }
1041
1042 // C++ [class.union]p1:
1043 // A union shall not be used as a base class.
1044 if (BaseType->isUnionType()) {
1045 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1046 return 0;
1047 }
1048
1049 // C++ [class.derived]p2:
1050 // The class-name in a base-specifier shall not be an incompletely
1051 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001052 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001053 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001054 << SpecifierRange)) {
1055 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001056 return 0;
John McCall572fc622010-08-17 07:23:57 +00001057 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001058
Eli Friedman1d954f62009-08-15 21:55:26 +00001059 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001062 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001063 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001064 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1065 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001066
Anders Carlsson1d209272011-03-25 14:55:14 +00001067 // C++ [class]p3:
1068 // If a class is marked final and it appears as a base-type-specifier in
1069 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001070 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001071 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1072 << CXXBaseDecl->getDeclName();
1073 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1074 << CXXBaseDecl->getDeclName();
1075 return 0;
1076 }
1077
John McCall572fc622010-08-17 07:23:57 +00001078 if (BaseDecl->isInvalidDecl())
1079 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001080
1081 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001082 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001083 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001085}
1086
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001087/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1088/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001089/// example:
1090/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001091/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001092BaseResult
John McCalld226f652010-08-21 09:40:31 +00001093Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001094 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001095 ParsedType basetype, SourceLocation BaseLoc,
1096 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001097 if (!classdecl)
1098 return true;
1099
Douglas Gregor40808ce2009-03-09 23:48:35 +00001100 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001101 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001102 if (!Class)
1103 return true;
1104
Nick Lewycky56062202010-07-26 16:56:01 +00001105 TypeSourceInfo *TInfo = 0;
1106 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001107
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001108 if (EllipsisLoc.isInvalid() &&
1109 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001110 UPPC_BaseType))
1111 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001112
Douglas Gregor2943aed2009-03-03 04:44:36 +00001113 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001114 Virtual, Access, TInfo,
1115 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001116 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001119}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001120
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121/// \brief Performs the actual work of attaching the given base class
1122/// specifiers to a C++ class.
1123bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1124 unsigned NumBases) {
1125 if (NumBases == 0)
1126 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001127
1128 // Used to keep track of which base types we have already seen, so
1129 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001130 // that the key is always the unqualified canonical type of the base
1131 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1133
1134 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001135 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001137 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001138 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001140 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001141
1142 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1143 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001144 // C++ [class.mi]p3:
1145 // A class shall not be specified as a direct base class of a
1146 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001147 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001148 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001149 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001151
1152 // Delete the duplicate base class specifier; we're going to
1153 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001154 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155
1156 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001157 } else {
1158 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001159 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001161 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001162 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1163 if (RD->hasAttr<WeakAttr>())
1164 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001165 }
1166 }
1167
1168 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001169 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001170
1171 // Delete the remaining (good) base class specifiers, since their
1172 // data has been copied into the CXXRecordDecl.
1173 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001174 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001175
1176 return Invalid;
1177}
1178
1179/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1180/// class, after checking whether there are any duplicate base
1181/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001182void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001183 unsigned NumBases) {
1184 if (!ClassDecl || !Bases || !NumBases)
1185 return;
1186
1187 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001188 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001189 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001190}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001191
John McCall3cb0ebd2010-03-10 03:28:59 +00001192static CXXRecordDecl *GetClassForType(QualType T) {
1193 if (const RecordType *RT = T->getAs<RecordType>())
1194 return cast<CXXRecordDecl>(RT->getDecl());
1195 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1196 return ICT->getDecl();
1197 else
1198 return 0;
1199}
1200
Douglas Gregora8f32e02009-10-06 17:59:45 +00001201/// \brief Determine whether the type \p Derived is a C++ class that is
1202/// derived from the type \p Base.
1203bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001204 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001205 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001206
1207 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1208 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001209 return false;
1210
John McCall3cb0ebd2010-03-10 03:28:59 +00001211 CXXRecordDecl *BaseRD = GetClassForType(Base);
1212 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001213 return false;
1214
John McCall86ff3082010-02-04 22:26:26 +00001215 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1216 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217}
1218
1219/// \brief Determine whether the type \p Derived is a C++ class that is
1220/// derived from the type \p Base.
1221bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001222 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223 return false;
1224
John McCall3cb0ebd2010-03-10 03:28:59 +00001225 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1226 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001227 return false;
1228
John McCall3cb0ebd2010-03-10 03:28:59 +00001229 CXXRecordDecl *BaseRD = GetClassForType(Base);
1230 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1234}
1235
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001236void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001237 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001238 assert(BasePathArray.empty() && "Base path array must be empty!");
1239 assert(Paths.isRecordingPaths() && "Must record paths!");
1240
1241 const CXXBasePath &Path = Paths.front();
1242
1243 // We first go backward and check if we have a virtual base.
1244 // FIXME: It would be better if CXXBasePath had the base specifier for
1245 // the nearest virtual base.
1246 unsigned Start = 0;
1247 for (unsigned I = Path.size(); I != 0; --I) {
1248 if (Path[I - 1].Base->isVirtual()) {
1249 Start = I - 1;
1250 break;
1251 }
1252 }
1253
1254 // Now add all bases.
1255 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001256 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001257}
1258
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001259/// \brief Determine whether the given base path includes a virtual
1260/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001261bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1262 for (CXXCastPath::const_iterator B = BasePath.begin(),
1263 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001264 B != BEnd; ++B)
1265 if ((*B)->isVirtual())
1266 return true;
1267
1268 return false;
1269}
1270
Douglas Gregora8f32e02009-10-06 17:59:45 +00001271/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1272/// conversion (where Derived and Base are class types) is
1273/// well-formed, meaning that the conversion is unambiguous (and
1274/// that all of the base classes are accessible). Returns true
1275/// and emits a diagnostic if the code is ill-formed, returns false
1276/// otherwise. Loc is the location where this routine should point to
1277/// if there is an error, and Range is the source range to highlight
1278/// if there is an error.
1279bool
1280Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001281 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001282 unsigned AmbigiousBaseConvID,
1283 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001284 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001285 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001286 // First, determine whether the path from Derived to Base is
1287 // ambiguous. This is slightly more expensive than checking whether
1288 // the Derived to Base conversion exists, because here we need to
1289 // explore multiple paths to determine if there is an ambiguity.
1290 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1291 /*DetectVirtual=*/false);
1292 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1293 assert(DerivationOkay &&
1294 "Can only be used with a derived-to-base conversion");
1295 (void)DerivationOkay;
1296
1297 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001298 if (InaccessibleBaseID) {
1299 // Check that the base class can be accessed.
1300 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1301 InaccessibleBaseID)) {
1302 case AR_inaccessible:
1303 return true;
1304 case AR_accessible:
1305 case AR_dependent:
1306 case AR_delayed:
1307 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001308 }
John McCall6b2accb2010-02-10 09:31:12 +00001309 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001310
1311 // Build a base path if necessary.
1312 if (BasePath)
1313 BuildBasePathArray(Paths, *BasePath);
1314 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001315 }
1316
1317 // We know that the derived-to-base conversion is ambiguous, and
1318 // we're going to produce a diagnostic. Perform the derived-to-base
1319 // search just one more time to compute all of the possible paths so
1320 // that we can print them out. This is more expensive than any of
1321 // the previous derived-to-base checks we've done, but at this point
1322 // performance isn't as much of an issue.
1323 Paths.clear();
1324 Paths.setRecordingPaths(true);
1325 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1326 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1327 (void)StillOkay;
1328
1329 // Build up a textual representation of the ambiguous paths, e.g.,
1330 // D -> B -> A, that will be used to illustrate the ambiguous
1331 // conversions in the diagnostic. We only print one of the paths
1332 // to each base class subobject.
1333 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1334
1335 Diag(Loc, AmbigiousBaseConvID)
1336 << Derived << Base << PathDisplayStr << Range << Name;
1337 return true;
1338}
1339
1340bool
1341Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001342 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001343 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001344 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001346 IgnoreAccess ? 0
1347 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001348 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001349 Loc, Range, DeclarationName(),
1350 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351}
1352
1353
1354/// @brief Builds a string representing ambiguous paths from a
1355/// specific derived class to different subobjects of the same base
1356/// class.
1357///
1358/// This function builds a string that can be used in error messages
1359/// to show the different paths that one can take through the
1360/// inheritance hierarchy to go from the derived class to different
1361/// subobjects of a base class. The result looks something like this:
1362/// @code
1363/// struct D -> struct B -> struct A
1364/// struct D -> struct C -> struct A
1365/// @endcode
1366std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1367 std::string PathDisplayStr;
1368 std::set<unsigned> DisplayedPaths;
1369 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1370 Path != Paths.end(); ++Path) {
1371 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1372 // We haven't displayed a path to this particular base
1373 // class subobject yet.
1374 PathDisplayStr += "\n ";
1375 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1376 for (CXXBasePath::const_iterator Element = Path->begin();
1377 Element != Path->end(); ++Element)
1378 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1379 }
1380 }
1381
1382 return PathDisplayStr;
1383}
1384
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001385//===----------------------------------------------------------------------===//
1386// C++ class member Handling
1387//===----------------------------------------------------------------------===//
1388
Abramo Bagnara6206d532010-06-05 05:09:32 +00001389/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001390bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1391 SourceLocation ASLoc,
1392 SourceLocation ColonLoc,
1393 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001394 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001395 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001396 ASLoc, ColonLoc);
1397 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001398 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001399}
1400
Anders Carlsson9e682d92011-01-20 05:57:14 +00001401/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001402void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001403 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001404 if (!MD || !MD->isVirtual())
1405 return;
1406
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001407 if (MD->isDependentContext())
1408 return;
1409
Anders Carlsson9e682d92011-01-20 05:57:14 +00001410 // C++0x [class.virtual]p3:
1411 // If a virtual function is marked with the virt-specifier override and does
1412 // not override a member function of a base class,
1413 // the program is ill-formed.
1414 bool HasOverriddenMethods =
1415 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001416 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001417 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001418 diag::err_function_marked_override_not_overriding)
1419 << MD->getDeclName();
1420 return;
1421 }
1422}
1423
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001424/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1425/// function overrides a virtual member function marked 'final', according to
1426/// C++0x [class.virtual]p3.
1427bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1428 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001429 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001430 return false;
1431
1432 Diag(New->getLocation(), diag::err_final_function_overridden)
1433 << New->getDeclName();
1434 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1435 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001436}
1437
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001438/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1439/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001440/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1441/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1442/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001443Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001444Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001445 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001446 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001447 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001449 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1450 DeclarationName Name = NameInfo.getName();
1451 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001452
1453 // For anonymous bitfields, the location should point to the type.
1454 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001455 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001456
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001457 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001458
John McCall4bde1e12010-06-04 08:34:12 +00001459 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001460 assert(!DS.isFriendSpecified());
1461
Richard Smith1ab0d902011-06-25 02:28:38 +00001462 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001463
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 // C++ 9.2p6: A member shall not be declared to have automatic storage
1465 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001466 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1467 // data members and cannot be applied to names declared const or static,
1468 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001469 switch (DS.getStorageClassSpec()) {
1470 case DeclSpec::SCS_unspecified:
1471 case DeclSpec::SCS_typedef:
1472 case DeclSpec::SCS_static:
1473 // FALL THROUGH.
1474 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001475 case DeclSpec::SCS_mutable:
1476 if (isFunc) {
1477 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001478 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001480 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Sebastian Redla11f42f2008-11-17 23:24:37 +00001482 // FIXME: It would be nicer if the keyword was ignored only for this
1483 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001484 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001485 }
1486 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001487 default:
1488 if (DS.getStorageClassSpecLoc().isValid())
1489 Diag(DS.getStorageClassSpecLoc(),
1490 diag::err_storageclass_invalid_for_member);
1491 else
1492 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1493 D.getMutableDeclSpec().ClearStorageClassSpecs();
1494 }
1495
Sebastian Redl669d5d72008-11-14 23:42:31 +00001496 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1497 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001498 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001499
1500 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001501 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001502 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001503
1504 // Data members must have identifiers for names.
1505 if (Name.getNameKind() != DeclarationName::Identifier) {
1506 Diag(Loc, diag::err_bad_variable_name)
1507 << Name;
1508 return 0;
1509 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001510
Douglas Gregorf2503652011-09-21 14:40:46 +00001511 IdentifierInfo *II = Name.getAsIdentifierInfo();
1512
1513 // Member field could not be with "template" keyword.
1514 // So TemplateParameterLists should be empty in this case.
1515 if (TemplateParameterLists.size()) {
1516 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1517 if (TemplateParams->size()) {
1518 // There is no such thing as a member field template.
1519 Diag(D.getIdentifierLoc(), diag::err_template_member)
1520 << II
1521 << SourceRange(TemplateParams->getTemplateLoc(),
1522 TemplateParams->getRAngleLoc());
1523 } else {
1524 // There is an extraneous 'template<>' for this member.
1525 Diag(TemplateParams->getTemplateLoc(),
1526 diag::err_template_member_noparams)
1527 << II
1528 << SourceRange(TemplateParams->getTemplateLoc(),
1529 TemplateParams->getRAngleLoc());
1530 }
1531 return 0;
1532 }
1533
Douglas Gregor922fff22010-10-13 22:19:53 +00001534 if (SS.isSet() && !SS.isInvalid()) {
1535 // The user provided a superfluous scope specifier inside a class
1536 // definition:
1537 //
1538 // class X {
1539 // int X::member;
1540 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001541 if (DeclContext *DC = computeDeclContext(SS, false))
1542 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001543 else
1544 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1545 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001546
Douglas Gregor922fff22010-10-13 22:19:53 +00001547 SS.clear();
1548 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001549
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001551 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001552 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001553 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001554 assert(!HasDeferredInit);
1555
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001556 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001557 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001558 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001559 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001560
1561 // Non-instance-fields can't have a bitfield.
1562 if (BitWidth) {
1563 if (Member->isInvalidDecl()) {
1564 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001565 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001566 // C++ 9.6p3: A bit-field shall not be a static member.
1567 // "static member 'A' cannot be a bit-field"
1568 Diag(Loc, diag::err_static_not_bitfield)
1569 << Name << BitWidth->getSourceRange();
1570 } else if (isa<TypedefDecl>(Member)) {
1571 // "typedef member 'x' cannot be a bit-field"
1572 Diag(Loc, diag::err_typedef_not_bitfield)
1573 << Name << BitWidth->getSourceRange();
1574 } else {
1575 // A function typedef ("typedef int f(); f a;").
1576 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1577 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001578 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001579 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001580 }
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Chris Lattner8b963ef2009-03-05 23:01:03 +00001582 BitWidth = 0;
1583 Member->setInvalidDecl();
1584 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001585
1586 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Douglas Gregor37b372b2009-08-20 22:52:58 +00001588 // If we have declared a member function template, set the access of the
1589 // templated declaration as well.
1590 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1591 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001592 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001593
Anders Carlssonaae5af22011-01-20 04:34:22 +00001594 if (VS.isOverrideSpecified()) {
1595 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1596 if (!MD || !MD->isVirtual()) {
1597 Diag(Member->getLocStart(),
1598 diag::override_keyword_only_allowed_on_virtual_member_functions)
1599 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001600 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001601 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001602 }
1603 if (VS.isFinalSpecified()) {
1604 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1605 if (!MD || !MD->isVirtual()) {
1606 Diag(Member->getLocStart(),
1607 diag::override_keyword_only_allowed_on_virtual_member_functions)
1608 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001609 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001610 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001611 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001612
Douglas Gregorf5251602011-03-08 17:10:18 +00001613 if (VS.getLastLocation().isValid()) {
1614 // Update the end location of a method that has a virt-specifiers.
1615 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1616 MD->setRangeEnd(VS.getLastLocation());
1617 }
1618
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001619 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001620
Douglas Gregor10bd3682008-11-17 22:58:34 +00001621 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001622
John McCallb25b2952011-02-15 07:12:36 +00001623 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001624 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001625 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001626}
1627
Richard Smith7a614d82011-06-11 17:19:42 +00001628/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001629/// in-class initializer for a non-static C++ class member, and after
1630/// instantiating an in-class initializer in a class template. Such actions
1631/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001632void
1633Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1634 Expr *InitExpr) {
1635 FieldDecl *FD = cast<FieldDecl>(D);
1636
1637 if (!InitExpr) {
1638 FD->setInvalidDecl();
1639 FD->removeInClassInitializer();
1640 return;
1641 }
1642
Peter Collingbournefef21892011-10-23 18:59:44 +00001643 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1644 FD->setInvalidDecl();
1645 FD->removeInClassInitializer();
1646 return;
1647 }
1648
Richard Smith7a614d82011-06-11 17:19:42 +00001649 ExprResult Init = InitExpr;
1650 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001651 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001652 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001653 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1654 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001655 Expr **Inits = &InitExpr;
1656 unsigned NumInits = 1;
1657 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1658 InitializationKind Kind = EqualLoc.isInvalid()
1659 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1660 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1661 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1662 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001663 if (Init.isInvalid()) {
1664 FD->setInvalidDecl();
1665 return;
1666 }
1667
1668 CheckImplicitConversions(Init.get(), EqualLoc);
1669 }
1670
1671 // C++0x [class.base.init]p7:
1672 // The initialization of each base and member constitutes a
1673 // full-expression.
1674 Init = MaybeCreateExprWithCleanups(Init);
1675 if (Init.isInvalid()) {
1676 FD->setInvalidDecl();
1677 return;
1678 }
1679
1680 InitExpr = Init.release();
1681
1682 FD->setInClassInitializer(InitExpr);
1683}
1684
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001685/// \brief Find the direct and/or virtual base specifiers that
1686/// correspond to the given base type, for use in base initialization
1687/// within a constructor.
1688static bool FindBaseInitializer(Sema &SemaRef,
1689 CXXRecordDecl *ClassDecl,
1690 QualType BaseType,
1691 const CXXBaseSpecifier *&DirectBaseSpec,
1692 const CXXBaseSpecifier *&VirtualBaseSpec) {
1693 // First, check for a direct base class.
1694 DirectBaseSpec = 0;
1695 for (CXXRecordDecl::base_class_const_iterator Base
1696 = ClassDecl->bases_begin();
1697 Base != ClassDecl->bases_end(); ++Base) {
1698 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1699 // We found a direct base of this type. That's what we're
1700 // initializing.
1701 DirectBaseSpec = &*Base;
1702 break;
1703 }
1704 }
1705
1706 // Check for a virtual base class.
1707 // FIXME: We might be able to short-circuit this if we know in advance that
1708 // there are no virtual bases.
1709 VirtualBaseSpec = 0;
1710 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1711 // We haven't found a base yet; search the class hierarchy for a
1712 // virtual base class.
1713 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1714 /*DetectVirtual=*/false);
1715 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1716 BaseType, Paths)) {
1717 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1718 Path != Paths.end(); ++Path) {
1719 if (Path->back().Base->isVirtual()) {
1720 VirtualBaseSpec = Path->back().Base;
1721 break;
1722 }
1723 }
1724 }
1725 }
1726
1727 return DirectBaseSpec || VirtualBaseSpec;
1728}
1729
Sebastian Redl6df65482011-09-24 17:48:25 +00001730/// \brief Handle a C++ member initializer using braced-init-list syntax.
1731MemInitResult
1732Sema::ActOnMemInitializer(Decl *ConstructorD,
1733 Scope *S,
1734 CXXScopeSpec &SS,
1735 IdentifierInfo *MemberOrBase,
1736 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001737 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001738 SourceLocation IdLoc,
1739 Expr *InitList,
1740 SourceLocation EllipsisLoc) {
1741 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001742 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001743 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001744}
1745
1746/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001747MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001748Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001749 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001750 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001751 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001752 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001753 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001754 SourceLocation IdLoc,
1755 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001756 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001757 SourceLocation RParenLoc,
1758 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001759 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1760 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001761 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001762 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001763}
1764
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001765namespace {
1766
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001767// Callback to only accept typo corrections that can be a valid C++ member
1768// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001769class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1770 public:
1771 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1772 : ClassDecl(ClassDecl) {}
1773
1774 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1775 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1776 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1777 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1778 else
1779 return isa<TypeDecl>(ND);
1780 }
1781 return false;
1782 }
1783
1784 private:
1785 CXXRecordDecl *ClassDecl;
1786};
1787
1788}
1789
Sebastian Redl6df65482011-09-24 17:48:25 +00001790/// \brief Handle a C++ member initializer.
1791MemInitResult
1792Sema::BuildMemInitializer(Decl *ConstructorD,
1793 Scope *S,
1794 CXXScopeSpec &SS,
1795 IdentifierInfo *MemberOrBase,
1796 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001797 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001798 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001799 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001801 if (!ConstructorD)
1802 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001804 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001805
1806 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001807 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001808 if (!Constructor) {
1809 // The user wrote a constructor initializer on a function that is
1810 // not a C++ constructor. Ignore the error for now, because we may
1811 // have more member initializers coming; we'll diagnose it just
1812 // once in ActOnMemInitializers.
1813 return true;
1814 }
1815
1816 CXXRecordDecl *ClassDecl = Constructor->getParent();
1817
1818 // C++ [class.base.init]p2:
1819 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001820 // constructor's class and, if not found in that scope, are looked
1821 // up in the scope containing the constructor's definition.
1822 // [Note: if the constructor's class contains a member with the
1823 // same name as a direct or virtual base class of the class, a
1824 // mem-initializer-id naming the member or base class and composed
1825 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001826 // mem-initializer-id for the hidden base class may be specified
1827 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001828 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001829 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001830 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001831 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001832 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001833 ValueDecl *Member;
1834 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1835 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001836 if (EllipsisLoc.isValid())
1837 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001838 << MemberOrBase
1839 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001840
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001841 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001842 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001843 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001844 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001845 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001846 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001847 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001848
1849 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001850 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001851 } else if (DS.getTypeSpecType() == TST_decltype) {
1852 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001853 } else {
1854 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1855 LookupParsedName(R, S, &SS);
1856
1857 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1858 if (!TyD) {
1859 if (R.isAmbiguous()) return true;
1860
John McCallfd225442010-04-09 19:01:14 +00001861 // We don't want access-control diagnostics here.
1862 R.suppressDiagnostics();
1863
Douglas Gregor7a886e12010-01-19 06:46:48 +00001864 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1865 bool NotUnknownSpecialization = false;
1866 DeclContext *DC = computeDeclContext(SS, false);
1867 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1868 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1869
1870 if (!NotUnknownSpecialization) {
1871 // When the scope specifier can refer to a member of an unknown
1872 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001873 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1874 SS.getWithLocInContext(Context),
1875 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001876 if (BaseType.isNull())
1877 return true;
1878
Douglas Gregor7a886e12010-01-19 06:46:48 +00001879 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001880 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001881 }
1882 }
1883
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001884 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001885 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001886 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001887 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001888 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001889 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001890 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1891 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001892 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001893 // We have found a non-static data member with a similar
1894 // name to what was typed; complain and initialize that
1895 // member.
1896 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1897 << MemberOrBase << true << CorrectedQuotedStr
1898 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1899 Diag(Member->getLocation(), diag::note_previous_decl)
1900 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001901
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001902 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001903 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001904 const CXXBaseSpecifier *DirectBaseSpec;
1905 const CXXBaseSpecifier *VirtualBaseSpec;
1906 if (FindBaseInitializer(*this, ClassDecl,
1907 Context.getTypeDeclType(Type),
1908 DirectBaseSpec, VirtualBaseSpec)) {
1909 // We have found a direct or virtual base class with a
1910 // similar name to what was typed; complain and initialize
1911 // that base class.
1912 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001913 << MemberOrBase << false << CorrectedQuotedStr
1914 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001915
1916 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1917 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001918 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001919 diag::note_base_class_specified_here)
1920 << BaseSpec->getType()
1921 << BaseSpec->getSourceRange();
1922
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 TyD = Type;
1924 }
1925 }
1926 }
1927
Douglas Gregor7a886e12010-01-19 06:46:48 +00001928 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001929 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001930 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001931 return true;
1932 }
John McCall2b194412009-12-21 10:41:20 +00001933 }
1934
Douglas Gregor7a886e12010-01-19 06:46:48 +00001935 if (BaseType.isNull()) {
1936 BaseType = Context.getTypeDeclType(TyD);
1937 if (SS.isSet()) {
1938 NestedNameSpecifier *Qualifier =
1939 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001940
Douglas Gregor7a886e12010-01-19 06:46:48 +00001941 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001942 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001943 }
John McCall2b194412009-12-21 10:41:20 +00001944 }
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
John McCalla93c9342009-12-07 02:54:59 +00001947 if (!TInfo)
1948 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001949
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001950 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001951}
1952
Chandler Carruth81c64772011-09-03 01:14:15 +00001953/// Checks a member initializer expression for cases where reference (or
1954/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001955static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1956 Expr *Init,
1957 SourceLocation IdLoc) {
1958 QualType MemberTy = Member->getType();
1959
1960 // We only handle pointers and references currently.
1961 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1962 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1963 return;
1964
1965 const bool IsPointer = MemberTy->isPointerType();
1966 if (IsPointer) {
1967 if (const UnaryOperator *Op
1968 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1969 // The only case we're worried about with pointers requires taking the
1970 // address.
1971 if (Op->getOpcode() != UO_AddrOf)
1972 return;
1973
1974 Init = Op->getSubExpr();
1975 } else {
1976 // We only handle address-of expression initializers for pointers.
1977 return;
1978 }
1979 }
1980
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001981 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1982 // Taking the address of a temporary will be diagnosed as a hard error.
1983 if (IsPointer)
1984 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001985
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001986 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1987 << Member << Init->getSourceRange();
1988 } else if (const DeclRefExpr *DRE
1989 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1990 // We only warn when referring to a non-reference parameter declaration.
1991 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1992 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001993 return;
1994
1995 S.Diag(Init->getExprLoc(),
1996 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1997 : diag::warn_bind_ref_member_to_parameter)
1998 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001999 } else {
2000 // Other initializers are fine.
2001 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002002 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002003
2004 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2005 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002006}
2007
John McCallb4190042009-11-04 23:02:40 +00002008/// Checks an initializer expression for use of uninitialized fields, such as
2009/// containing the field that is being initialized. Returns true if there is an
2010/// uninitialized field was used an updates the SourceLocation parameter; false
2011/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002012static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002013 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002014 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002015 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2016
Nick Lewycky43ad1822010-06-15 07:32:55 +00002017 if (isa<CallExpr>(S)) {
2018 // Do not descend into function calls or constructors, as the use
2019 // of an uninitialized field may be valid. One would have to inspect
2020 // the contents of the function/ctor to determine if it is safe or not.
2021 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2022 // may be safe, depending on what the function/ctor does.
2023 return false;
2024 }
2025 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2026 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002027
2028 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2029 // The member expression points to a static data member.
2030 assert(VD->isStaticDataMember() &&
2031 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002032 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002033 return false;
2034 }
2035
2036 if (isa<EnumConstantDecl>(RhsField)) {
2037 // The member expression points to an enum.
2038 return false;
2039 }
2040
John McCallb4190042009-11-04 23:02:40 +00002041 if (RhsField == LhsField) {
2042 // Initializing a field with itself. Throw a warning.
2043 // But wait; there are exceptions!
2044 // Exception #1: The field may not belong to this record.
2045 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002046 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002047 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2048 // Even though the field matches, it does not belong to this record.
2049 return false;
2050 }
2051 // None of the exceptions triggered; return true to indicate an
2052 // uninitialized field was used.
2053 *L = ME->getMemberLoc();
2054 return true;
2055 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002056 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002057 // sizeof/alignof doesn't reference contents, do not warn.
2058 return false;
2059 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2060 // address-of doesn't reference contents (the pointer may be dereferenced
2061 // in the same expression but it would be rare; and weird).
2062 if (UOE->getOpcode() == UO_AddrOf)
2063 return false;
John McCallb4190042009-11-04 23:02:40 +00002064 }
John McCall7502c1d2011-02-13 04:07:26 +00002065 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002066 if (!*it) {
2067 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002068 continue;
2069 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002070 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2071 return true;
John McCallb4190042009-11-04 23:02:40 +00002072 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002073 return false;
John McCallb4190042009-11-04 23:02:40 +00002074}
2075
John McCallf312b1e2010-08-26 23:41:50 +00002076MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002077Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002078 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002079 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2080 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2081 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002082 "Member must be a FieldDecl or IndirectFieldDecl");
2083
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002084 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002085 return true;
2086
Douglas Gregor464b2f02010-11-05 22:21:31 +00002087 if (Member->isInvalidDecl())
2088 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002089
John McCallb4190042009-11-04 23:02:40 +00002090 // Diagnose value-uses of fields to initialize themselves, e.g.
2091 // foo(foo)
2092 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002093 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002094 Expr **Args;
2095 unsigned NumArgs;
2096 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2097 Args = ParenList->getExprs();
2098 NumArgs = ParenList->getNumExprs();
2099 } else {
2100 InitListExpr *InitList = cast<InitListExpr>(Init);
2101 Args = InitList->getInits();
2102 NumArgs = InitList->getNumInits();
2103 }
2104 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002105 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002106 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002107 // FIXME: Return true in the case when other fields are used before being
2108 // uninitialized. For example, let this field be the i'th field. When
2109 // initializing the i'th field, throw a warning if any of the >= i'th
2110 // fields are used, as they are not yet initialized.
2111 // Right now we are only handling the case where the i'th field uses
2112 // itself in its initializer.
2113 Diag(L, diag::warn_field_is_uninit);
2114 }
2115 }
2116
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002117 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002118
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002119 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002120 // Can't check initialization for a member of dependent type or when
2121 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002122 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002123 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002124 bool InitList = false;
2125 if (isa<InitListExpr>(Init)) {
2126 InitList = true;
2127 Args = &Init;
2128 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002129
2130 if (isStdInitializerList(Member->getType(), 0)) {
2131 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2132 << /*at end of ctor*/1 << InitRange;
2133 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002134 }
2135
Chandler Carruth894aed92010-12-06 09:23:57 +00002136 // Initialize the member.
2137 InitializedEntity MemberEntity =
2138 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2139 : InitializedEntity::InitializeMember(IndirectMember, 0);
2140 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002141 InitList ? InitializationKind::CreateDirectList(IdLoc)
2142 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2143 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002144
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002145 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2146 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2147 MultiExprArg(*this, Args, NumArgs),
2148 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002149 if (MemberInit.isInvalid())
2150 return true;
2151
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002152 CheckImplicitConversions(MemberInit.get(),
2153 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002154
2155 // C++0x [class.base.init]p7:
2156 // The initialization of each base and member constitutes a
2157 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002158 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 if (MemberInit.isInvalid())
2160 return true;
2161
2162 // If we are in a dependent context, template instantiation will
2163 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002164 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002165 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2166 // of the information that we have about the member
2167 // initializer. However, deconstructing the ASTs is a dicey process,
2168 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002169 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002170 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002171 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002172 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002173 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2174 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002175 }
2176
Chandler Carruth894aed92010-12-06 09:23:57 +00002177 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002178 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2179 InitRange.getBegin(), Init,
2180 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002181 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2183 InitRange.getBegin(), Init,
2184 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002185 }
Eli Friedman59c04372009-07-29 19:44:27 +00002186}
2187
John McCallf312b1e2010-08-26 23:41:50 +00002188MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002189Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002190 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002191 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002192 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002193 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002194 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002195 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002196
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002197 bool InitList = true;
2198 Expr **Args = &Init;
2199 unsigned NumArgs = 1;
2200 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2201 InitList = false;
2202 Args = ParenList->getExprs();
2203 NumArgs = ParenList->getNumExprs();
2204 }
2205
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002207 // Initialize the object.
2208 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2209 QualType(ClassDecl->getTypeForDecl(), 0));
2210 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002211 InitList ? InitializationKind::CreateDirectList(NameLoc)
2212 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2213 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002214 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2215 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2216 MultiExprArg(*this, Args,NumArgs),
2217 0);
Sean Hunt41717662011-02-26 19:13:13 +00002218 if (DelegationInit.isInvalid())
2219 return true;
2220
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002221 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2222 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002223
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002224 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002225
2226 // C++0x [class.base.init]p7:
2227 // The initialization of each base and member constitutes a
2228 // full-expression.
2229 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2230 if (DelegationInit.isInvalid())
2231 return true;
2232
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002233 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002234 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002235 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002236}
2237
2238MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002239Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002240 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002241 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002242 SourceLocation BaseLoc
2243 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002244
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002245 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2246 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2247 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2248
2249 // C++ [class.base.init]p2:
2250 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002251 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002252 // of that class, the mem-initializer is ill-formed. A
2253 // mem-initializer-list can initialize a base class using any
2254 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002255 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002256
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 if (EllipsisLoc.isValid()) {
2259 // This is a pack expansion.
2260 if (!BaseType->containsUnexpandedParameterPack()) {
2261 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002262 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002263
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002264 EllipsisLoc = SourceLocation();
2265 }
2266 } else {
2267 // Check for any unexpanded parameter packs.
2268 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2269 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002270
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002271 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002272 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002273 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002274
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002275 // Check for direct and virtual base classes.
2276 const CXXBaseSpecifier *DirectBaseSpec = 0;
2277 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2278 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002279 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2280 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002281 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002282
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002283 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2284 VirtualBaseSpec);
2285
2286 // C++ [base.class.init]p2:
2287 // Unless the mem-initializer-id names a nonstatic data member of the
2288 // constructor's class or a direct or virtual base of that class, the
2289 // mem-initializer is ill-formed.
2290 if (!DirectBaseSpec && !VirtualBaseSpec) {
2291 // If the class has any dependent bases, then it's possible that
2292 // one of those types will resolve to the same type as
2293 // BaseType. Therefore, just treat this as a dependent base
2294 // class initialization. FIXME: Should we try to check the
2295 // initialization anyway? It seems odd.
2296 if (ClassDecl->hasAnyDependentBases())
2297 Dependent = true;
2298 else
2299 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2300 << BaseType << Context.getTypeDeclType(ClassDecl)
2301 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2302 }
2303 }
2304
2305 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002306 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Sebastian Redl6df65482011-09-24 17:48:25 +00002308 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2309 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002310 InitRange.getBegin(), Init,
2311 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002312 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313
2314 // C++ [base.class.init]p2:
2315 // If a mem-initializer-id is ambiguous because it designates both
2316 // a direct non-virtual base class and an inherited virtual base
2317 // class, the mem-initializer is ill-formed.
2318 if (DirectBaseSpec && VirtualBaseSpec)
2319 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002320 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002321
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002322 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002323 if (!BaseSpec)
2324 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2325
2326 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002327 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002328 Expr **Args = &Init;
2329 unsigned NumArgs = 1;
2330 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002331 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002332 Args = ParenList->getExprs();
2333 NumArgs = ParenList->getNumExprs();
2334 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002335
2336 InitializedEntity BaseEntity =
2337 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2338 InitializationKind Kind =
2339 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2340 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2341 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2343 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2344 MultiExprArg(*this, Args, NumArgs),
2345 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002346 if (BaseInit.isInvalid())
2347 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002348
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002349 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002350
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002351 // C++0x [class.base.init]p7:
2352 // The initialization of each base and member constitutes a
2353 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002354 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002355 if (BaseInit.isInvalid())
2356 return true;
2357
2358 // If we are in a dependent context, template instantiation will
2359 // perform this type-checking again. Just save the arguments that we
2360 // received in a ParenListExpr.
2361 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2362 // of the information that we have about the base
2363 // initializer. However, deconstructing the ASTs is a dicey process,
2364 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002365 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002367
Sean Huntcbb67482011-01-08 20:30:50 +00002368 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002369 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002370 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002371 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002372 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002373}
2374
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002375// Create a static_cast\<T&&>(expr).
2376static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2377 QualType ExprType = E->getType();
2378 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2379 SourceLocation ExprLoc = E->getLocStart();
2380 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2381 TargetType, ExprLoc);
2382
2383 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2384 SourceRange(ExprLoc, ExprLoc),
2385 E->getSourceRange()).take();
2386}
2387
Anders Carlssone5ef7402010-04-23 03:10:23 +00002388/// ImplicitInitializerKind - How an implicit base or member initializer should
2389/// initialize its base or member.
2390enum ImplicitInitializerKind {
2391 IIK_Default,
2392 IIK_Copy,
2393 IIK_Move
2394};
2395
Anders Carlssondefefd22010-04-23 02:00:02 +00002396static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002397BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002398 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002399 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002400 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002401 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002402 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002403 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2404 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002405
John McCall60d7b3a2010-08-24 06:29:42 +00002406 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002407
2408 switch (ImplicitInitKind) {
2409 case IIK_Default: {
2410 InitializationKind InitKind
2411 = InitializationKind::CreateDefault(Constructor->getLocation());
2412 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2413 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002414 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002415 break;
2416 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002417
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002418 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002419 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002420 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002421 ParmVarDecl *Param = Constructor->getParamDecl(0);
2422 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002423
Anders Carlssone5ef7402010-04-23 03:10:23 +00002424 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002425 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002426 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002427 Constructor->getLocation(), ParamType,
2428 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002429
Eli Friedman5f2987c2012-02-02 03:46:19 +00002430 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2431
Anders Carlssonc7957502010-04-24 22:02:54 +00002432 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002433 QualType ArgTy =
2434 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2435 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002437 if (Moving) {
2438 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2439 }
2440
John McCallf871d0c2010-08-07 06:22:56 +00002441 CXXCastPath BasePath;
2442 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002443 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2444 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002445 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002446 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002447
Anders Carlssone5ef7402010-04-23 03:10:23 +00002448 InitializationKind InitKind
2449 = InitializationKind::CreateDirect(Constructor->getLocation(),
2450 SourceLocation(), SourceLocation());
2451 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2452 &CopyCtorArg, 1);
2453 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002454 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002455 break;
2456 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002457 }
John McCall9ae2f072010-08-23 23:25:46 +00002458
Douglas Gregor53c374f2010-12-07 00:41:46 +00002459 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002460 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002461 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002462
Anders Carlssondefefd22010-04-23 02:00:02 +00002463 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002464 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002465 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2466 SourceLocation()),
2467 BaseSpec->isVirtual(),
2468 SourceLocation(),
2469 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002470 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002471 SourceLocation());
2472
Anders Carlssondefefd22010-04-23 02:00:02 +00002473 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002474}
2475
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002476static bool RefersToRValueRef(Expr *MemRef) {
2477 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2478 return Referenced->getType()->isRValueReferenceType();
2479}
2480
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002481static bool
2482BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002483 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002484 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002485 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002486 if (Field->isInvalidDecl())
2487 return true;
2488
Chandler Carruthf186b542010-06-29 23:50:44 +00002489 SourceLocation Loc = Constructor->getLocation();
2490
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002491 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2492 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002493 ParmVarDecl *Param = Constructor->getParamDecl(0);
2494 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002495
2496 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002497 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2498 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002499
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002500 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002501 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002502 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002503 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002504
Eli Friedman5f2987c2012-02-02 03:46:19 +00002505 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2506
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 if (Moving) {
2508 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2509 }
2510
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002511 // Build a reference to this field within the parameter.
2512 CXXScopeSpec SS;
2513 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2514 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002515 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2516 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002517 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002518 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002519 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002520 ParamType, Loc,
2521 /*IsArrow=*/false,
2522 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002523 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002524 /*FirstQualifierInScope=*/0,
2525 MemberLookup,
2526 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002527 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002528 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002529
2530 // C++11 [class.copy]p15:
2531 // - if a member m has rvalue reference type T&&, it is direct-initialized
2532 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002533 if (RefersToRValueRef(CtorArg.get())) {
2534 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002535 }
2536
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002537 // When the field we are copying is an array, create index variables for
2538 // each dimension of the array. We use these index variables to subscript
2539 // the source array, and other clients (e.g., CodeGen) will perform the
2540 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002542 QualType BaseType = Field->getType();
2543 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002544 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 while (const ConstantArrayType *Array
2546 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002547 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 // Create the iteration variable for this array index.
2549 IdentifierInfo *IterationVarName = 0;
2550 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002551 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002552 llvm::raw_svector_ostream OS(Str);
2553 OS << "__i" << IndexVariables.size();
2554 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2555 }
2556 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002557 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002558 IterationVarName, SizeType,
2559 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002560 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002561 IndexVariables.push_back(IterationVar);
2562
2563 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002564 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002565 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 assert(!IterationVarRef.isInvalid() &&
2567 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002568 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2569 assert(!IterationVarRef.isInvalid() &&
2570 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002571
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002573 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002574 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002575 Loc);
2576 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002577 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002578
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002579 BaseType = Array->getElementType();
2580 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002581
2582 // The array subscript expression is an lvalue, which is wrong for moving.
2583 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002584 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002585
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002586 // Construct the entity that we will be initializing. For an array, this
2587 // will be first element in the array, which may require several levels
2588 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002589 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002591 if (Indirect)
2592 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2593 else
2594 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002595 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2596 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2597 0,
2598 Entities.back()));
2599
2600 // Direct-initialize to use the copy constructor.
2601 InitializationKind InitKind =
2602 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2603
Sebastian Redl74e611a2011-09-04 18:14:28 +00002604 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002605 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002606 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607
John McCall60d7b3a2010-08-24 06:29:42 +00002608 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002609 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002610 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002611 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 if (MemberInit.isInvalid())
2613 return true;
2614
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002615 if (Indirect) {
2616 assert(IndexVariables.size() == 0 &&
2617 "Indirect field improperly initialized");
2618 CXXMemberInit
2619 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2620 Loc, Loc,
2621 MemberInit.takeAs<Expr>(),
2622 Loc);
2623 } else
2624 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2625 Loc, MemberInit.takeAs<Expr>(),
2626 Loc,
2627 IndexVariables.data(),
2628 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002629 return false;
2630 }
2631
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002632 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2633
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002634 QualType FieldBaseElementType =
2635 SemaRef.Context.getBaseElementType(Field->getType());
2636
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002637 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002638 InitializedEntity InitEntity
2639 = Indirect? InitializedEntity::InitializeMember(Indirect)
2640 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002641 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002642 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002643
2644 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002645 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002646 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002647
Douglas Gregor53c374f2010-12-07 00:41:46 +00002648 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002649 if (MemberInit.isInvalid())
2650 return true;
2651
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002652 if (Indirect)
2653 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2654 Indirect, Loc,
2655 Loc,
2656 MemberInit.get(),
2657 Loc);
2658 else
2659 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2660 Field, Loc, Loc,
2661 MemberInit.get(),
2662 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002663 return false;
2664 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002665
Sean Hunt1f2f3842011-05-17 00:19:05 +00002666 if (!Field->getParent()->isUnion()) {
2667 if (FieldBaseElementType->isReferenceType()) {
2668 SemaRef.Diag(Constructor->getLocation(),
2669 diag::err_uninitialized_member_in_ctor)
2670 << (int)Constructor->isImplicit()
2671 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2672 << 0 << Field->getDeclName();
2673 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2674 return true;
2675 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002676
Sean Hunt1f2f3842011-05-17 00:19:05 +00002677 if (FieldBaseElementType.isConstQualified()) {
2678 SemaRef.Diag(Constructor->getLocation(),
2679 diag::err_uninitialized_member_in_ctor)
2680 << (int)Constructor->isImplicit()
2681 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2682 << 1 << Field->getDeclName();
2683 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2684 return true;
2685 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002686 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002687
David Blaikie4e4d0842012-03-11 07:00:24 +00002688 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002689 FieldBaseElementType->isObjCRetainableType() &&
2690 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2692 // Instant objects:
2693 // Default-initialize Objective-C pointers to NULL.
2694 CXXMemberInit
2695 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2696 Loc, Loc,
2697 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2698 Loc);
2699 return false;
2700 }
2701
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002702 // Nothing to initialize.
2703 CXXMemberInit = 0;
2704 return false;
2705}
John McCallf1860e52010-05-20 23:23:51 +00002706
2707namespace {
2708struct BaseAndFieldInfo {
2709 Sema &S;
2710 CXXConstructorDecl *Ctor;
2711 bool AnyErrorsInInits;
2712 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002713 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002714 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002715
2716 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2717 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002718 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2719 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002720 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002721 else if (Generated && Ctor->isMoveConstructor())
2722 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002723 else
2724 IIK = IIK_Default;
2725 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002726
2727 bool isImplicitCopyOrMove() const {
2728 switch (IIK) {
2729 case IIK_Copy:
2730 case IIK_Move:
2731 return true;
2732
2733 case IIK_Default:
2734 return false;
2735 }
David Blaikie30263482012-01-20 21:50:17 +00002736
2737 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002738 }
John McCallf1860e52010-05-20 23:23:51 +00002739};
2740}
2741
Richard Smitha4950662011-09-19 13:34:43 +00002742/// \brief Determine whether the given indirect field declaration is somewhere
2743/// within an anonymous union.
2744static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2745 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2746 CEnd = F->chain_end();
2747 C != CEnd; ++C)
2748 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2749 if (Record->isUnion())
2750 return true;
2751
2752 return false;
2753}
2754
Douglas Gregorddb21472011-11-02 23:04:16 +00002755/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2756/// array type.
2757static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2758 if (T->isIncompleteArrayType())
2759 return true;
2760
2761 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2762 if (!ArrayT->getSize())
2763 return true;
2764
2765 T = ArrayT->getElementType();
2766 }
2767
2768 return false;
2769}
2770
Richard Smith7a614d82011-06-11 17:19:42 +00002771static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002772 FieldDecl *Field,
2773 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002774
Chandler Carruthe861c602010-06-30 02:59:29 +00002775 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002776 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002777 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002778 return false;
2779 }
2780
Richard Smith7a614d82011-06-11 17:19:42 +00002781 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2782 // has a brace-or-equal-initializer, the entity is initialized as specified
2783 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002784 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002785 CXXCtorInitializer *Init;
2786 if (Indirect)
2787 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2788 SourceLocation(),
2789 SourceLocation(), 0,
2790 SourceLocation());
2791 else
2792 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2793 SourceLocation(),
2794 SourceLocation(), 0,
2795 SourceLocation());
2796 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002797 return false;
2798 }
2799
Richard Smithc115f632011-09-18 11:14:50 +00002800 // Don't build an implicit initializer for union members if none was
2801 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002802 if (Field->getParent()->isUnion() ||
2803 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002804 return false;
2805
Douglas Gregorddb21472011-11-02 23:04:16 +00002806 // Don't initialize incomplete or zero-length arrays.
2807 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2808 return false;
2809
John McCallf1860e52010-05-20 23:23:51 +00002810 // Don't try to build an implicit initializer if there were semantic
2811 // errors in any of the initializers (and therefore we might be
2812 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002813 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002814 return false;
2815
Sean Huntcbb67482011-01-08 20:30:50 +00002816 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002817 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2818 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002819 return true;
John McCallf1860e52010-05-20 23:23:51 +00002820
Francois Pichet00eb3f92010-12-04 09:14:42 +00002821 if (Init)
2822 Info.AllToInit.push_back(Init);
2823
John McCallf1860e52010-05-20 23:23:51 +00002824 return false;
2825}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002826
2827bool
2828Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2829 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002830 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002831 Constructor->setNumCtorInitializers(1);
2832 CXXCtorInitializer **initializer =
2833 new (Context) CXXCtorInitializer*[1];
2834 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2835 Constructor->setCtorInitializers(initializer);
2836
Sean Huntb76af9c2011-05-03 23:05:34 +00002837 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002838 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002839 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2840 }
2841
Sean Huntc1598702011-05-05 00:05:47 +00002842 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002843
Sean Hunt059ce0d2011-05-01 07:04:31 +00002844 return false;
2845}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002846
John McCallb77115d2011-06-17 00:18:42 +00002847bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2848 CXXCtorInitializer **Initializers,
2849 unsigned NumInitializers,
2850 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002851 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002852 // Just store the initializers as written, they will be checked during
2853 // instantiation.
2854 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002855 Constructor->setNumCtorInitializers(NumInitializers);
2856 CXXCtorInitializer **baseOrMemberInitializers =
2857 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002858 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002859 NumInitializers * sizeof(CXXCtorInitializer*));
2860 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002861 }
2862
2863 return false;
2864 }
2865
John McCallf1860e52010-05-20 23:23:51 +00002866 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002867
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002868 // We need to build the initializer AST according to order of construction
2869 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002870 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002871 if (!ClassDecl)
2872 return true;
2873
Eli Friedman80c30da2009-11-09 19:20:36 +00002874 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002876 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002877 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002878
2879 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002880 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002881 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002882 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002883 }
2884
Anders Carlsson711f34a2010-04-21 19:52:01 +00002885 // Keep track of the direct virtual bases.
2886 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2887 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2888 E = ClassDecl->bases_end(); I != E; ++I) {
2889 if (I->isVirtual())
2890 DirectVBases.insert(I);
2891 }
2892
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002893 // Push virtual bases before others.
2894 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2895 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2896
Sean Huntcbb67482011-01-08 20:30:50 +00002897 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002898 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2899 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002900 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002901 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002902 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002903 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002904 VBase, IsInheritedVirtualBase,
2905 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002906 HadError = true;
2907 continue;
2908 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002909
John McCallf1860e52010-05-20 23:23:51 +00002910 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002911 }
2912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCallf1860e52010-05-20 23:23:51 +00002914 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2916 E = ClassDecl->bases_end(); Base != E; ++Base) {
2917 // Virtuals are in the virtual base list and already constructed.
2918 if (Base->isVirtual())
2919 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Sean Huntcbb67482011-01-08 20:30:50 +00002921 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002922 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2923 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002925 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002926 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002927 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002928 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002929 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002930 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002931 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002932
John McCallf1860e52010-05-20 23:23:51 +00002933 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002934 }
2935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
John McCallf1860e52010-05-20 23:23:51 +00002937 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002938 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2939 MemEnd = ClassDecl->decls_end();
2940 Mem != MemEnd; ++Mem) {
2941 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002942 // C++ [class.bit]p2:
2943 // A declaration for a bit-field that omits the identifier declares an
2944 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2945 // initialized.
2946 if (F->isUnnamedBitfield())
2947 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002948
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002949 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002950 // handle anonymous struct/union fields based on their individual
2951 // indirect fields.
2952 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2953 continue;
2954
2955 if (CollectFieldInitializer(*this, Info, F))
2956 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002957 continue;
2958 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002959
2960 // Beyond this point, we only consider default initialization.
2961 if (Info.IIK != IIK_Default)
2962 continue;
2963
2964 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2965 if (F->getType()->isIncompleteArrayType()) {
2966 assert(ClassDecl->hasFlexibleArrayMember() &&
2967 "Incomplete array type is not valid");
2968 continue;
2969 }
2970
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002971 // Initialize each field of an anonymous struct individually.
2972 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2973 HadError = true;
2974
2975 continue;
2976 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002977 }
Mike Stump1eb44332009-09-09 15:08:12 +00002978
John McCallf1860e52010-05-20 23:23:51 +00002979 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002980 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002981 Constructor->setNumCtorInitializers(NumInitializers);
2982 CXXCtorInitializer **baseOrMemberInitializers =
2983 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002984 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002985 NumInitializers * sizeof(CXXCtorInitializer*));
2986 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002987
John McCallef027fe2010-03-16 21:39:52 +00002988 // Constructors implicitly reference the base and member
2989 // destructors.
2990 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2991 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002992 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002993
2994 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002995}
2996
Eli Friedman6347f422009-07-21 19:28:10 +00002997static void *GetKeyForTopLevelField(FieldDecl *Field) {
2998 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002999 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003000 if (RT->getDecl()->isAnonymousStructOrUnion())
3001 return static_cast<void *>(RT->getDecl());
3002 }
3003 return static_cast<void *>(Field);
3004}
3005
Anders Carlssonea356fb2010-04-02 05:42:15 +00003006static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003007 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003008}
3009
Anders Carlssonea356fb2010-04-02 05:42:15 +00003010static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003011 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003012 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003013 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003014
Eli Friedman6347f422009-07-21 19:28:10 +00003015 // For fields injected into the class via declaration of an anonymous union,
3016 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003017 FieldDecl *Field = Member->getAnyMember();
3018
John McCall3c3ccdb2010-04-10 09:28:51 +00003019 // If the field is a member of an anonymous struct or union, our key
3020 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003021 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003022 if (RD->isAnonymousStructOrUnion()) {
3023 while (true) {
3024 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3025 if (Parent->isAnonymousStructOrUnion())
3026 RD = Parent;
3027 else
3028 break;
3029 }
3030
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003031 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003032 }
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003034 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003035}
3036
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003037static void
3038DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003039 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003040 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003041 unsigned NumInits) {
3042 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003045 // Don't check initializers order unless the warning is enabled at the
3046 // location of at least one initializer.
3047 bool ShouldCheckOrder = false;
3048 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003049 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003050 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3051 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003052 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003053 ShouldCheckOrder = true;
3054 break;
3055 }
3056 }
3057 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003058 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003059
John McCalld6ca8da2010-04-10 07:37:23 +00003060 // Build the list of bases and members in the order that they'll
3061 // actually be initialized. The explicit initializers should be in
3062 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003063 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Anders Carlsson071d6102010-04-02 03:38:04 +00003065 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3066
John McCalld6ca8da2010-04-10 07:37:23 +00003067 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003068 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003069 ClassDecl->vbases_begin(),
3070 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003071 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003072
John McCalld6ca8da2010-04-10 07:37:23 +00003073 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003074 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003075 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003076 if (Base->isVirtual())
3077 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003078 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003079 }
Mike Stump1eb44332009-09-09 15:08:12 +00003080
John McCalld6ca8da2010-04-10 07:37:23 +00003081 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003083 E = ClassDecl->field_end(); Field != E; ++Field) {
3084 if (Field->isUnnamedBitfield())
3085 continue;
3086
John McCalld6ca8da2010-04-10 07:37:23 +00003087 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003088 }
3089
John McCalld6ca8da2010-04-10 07:37:23 +00003090 unsigned NumIdealInits = IdealInitKeys.size();
3091 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003092
Sean Huntcbb67482011-01-08 20:30:50 +00003093 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003094 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003095 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003096 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003097
3098 // Scan forward to try to find this initializer in the idealized
3099 // initializers list.
3100 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3101 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003102 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003103
3104 // If we didn't find this initializer, it must be because we
3105 // scanned past it on a previous iteration. That can only
3106 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003107 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003108 Sema::SemaDiagnosticBuilder D =
3109 SemaRef.Diag(PrevInit->getSourceLocation(),
3110 diag::warn_initializer_out_of_order);
3111
Francois Pichet00eb3f92010-12-04 09:14:42 +00003112 if (PrevInit->isAnyMemberInitializer())
3113 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003114 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003115 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003116
Francois Pichet00eb3f92010-12-04 09:14:42 +00003117 if (Init->isAnyMemberInitializer())
3118 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003119 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003120 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003121
3122 // Move back to the initializer's location in the ideal list.
3123 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3124 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003125 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003126
3127 assert(IdealIndex != NumIdealInits &&
3128 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003129 }
John McCalld6ca8da2010-04-10 07:37:23 +00003130
3131 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003132 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003133}
3134
John McCall3c3ccdb2010-04-10 09:28:51 +00003135namespace {
3136bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003137 CXXCtorInitializer *Init,
3138 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003139 if (!PrevInit) {
3140 PrevInit = Init;
3141 return false;
3142 }
3143
3144 if (FieldDecl *Field = Init->getMember())
3145 S.Diag(Init->getSourceLocation(),
3146 diag::err_multiple_mem_initialization)
3147 << Field->getDeclName()
3148 << Init->getSourceRange();
3149 else {
John McCallf4c73712011-01-19 06:33:43 +00003150 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003151 assert(BaseClass && "neither field nor base");
3152 S.Diag(Init->getSourceLocation(),
3153 diag::err_multiple_base_initialization)
3154 << QualType(BaseClass, 0)
3155 << Init->getSourceRange();
3156 }
3157 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3158 << 0 << PrevInit->getSourceRange();
3159
3160 return true;
3161}
3162
Sean Huntcbb67482011-01-08 20:30:50 +00003163typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003164typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3165
3166bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003167 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003168 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003169 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003170 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003171 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003172
3173 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003174 if (Parent->isUnion()) {
3175 UnionEntry &En = Unions[Parent];
3176 if (En.first && En.first != Child) {
3177 S.Diag(Init->getSourceLocation(),
3178 diag::err_multiple_mem_union_initialization)
3179 << Field->getDeclName()
3180 << Init->getSourceRange();
3181 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3182 << 0 << En.second->getSourceRange();
3183 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003184 }
3185 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003186 En.first = Child;
3187 En.second = Init;
3188 }
David Blaikie6fe29652011-11-17 06:01:57 +00003189 if (!Parent->isAnonymousStructOrUnion())
3190 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003191 }
3192
3193 Child = Parent;
3194 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003195 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003196
3197 return false;
3198}
3199}
3200
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003201/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003202void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003203 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003204 CXXCtorInitializer **meminits,
3205 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003206 bool AnyErrors) {
3207 if (!ConstructorDecl)
3208 return;
3209
3210 AdjustDeclIfTemplate(ConstructorDecl);
3211
3212 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003213 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003214
3215 if (!Constructor) {
3216 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3217 return;
3218 }
3219
Sean Huntcbb67482011-01-08 20:30:50 +00003220 CXXCtorInitializer **MemInits =
3221 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003222
3223 // Mapping for the duplicate initializers check.
3224 // For member initializers, this is keyed with a FieldDecl*.
3225 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003226 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003227
3228 // Mapping for the inconsistent anonymous-union initializers check.
3229 RedundantUnionMap MemberUnions;
3230
Anders Carlssonea356fb2010-04-02 05:42:15 +00003231 bool HadError = false;
3232 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003233 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003234
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003235 // Set the source order index.
3236 Init->setSourceOrder(i);
3237
Francois Pichet00eb3f92010-12-04 09:14:42 +00003238 if (Init->isAnyMemberInitializer()) {
3239 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003240 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3241 CheckRedundantUnionInit(*this, Init, MemberUnions))
3242 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003243 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003244 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3245 if (CheckRedundantInit(*this, Init, Members[Key]))
3246 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003247 } else {
3248 assert(Init->isDelegatingInitializer());
3249 // This must be the only initializer
3250 if (i != 0 || NumMemInits > 1) {
3251 Diag(MemInits[0]->getSourceLocation(),
3252 diag::err_delegating_initializer_alone)
3253 << MemInits[0]->getSourceRange();
3254 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003255 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003256 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003257 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003258 // Return immediately as the initializer is set.
3259 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003260 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003261 }
3262
Anders Carlssonea356fb2010-04-02 05:42:15 +00003263 if (HadError)
3264 return;
3265
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003266 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003267
Sean Huntcbb67482011-01-08 20:30:50 +00003268 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003269}
3270
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003271void
John McCallef027fe2010-03-16 21:39:52 +00003272Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3273 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003274 // Ignore dependent contexts. Also ignore unions, since their members never
3275 // have destructors implicitly called.
3276 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003277 return;
John McCall58e6f342010-03-16 05:22:47 +00003278
3279 // FIXME: all the access-control diagnostics are positioned on the
3280 // field/base declaration. That's probably good; that said, the
3281 // user might reasonably want to know why the destructor is being
3282 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003283
Anders Carlsson9f853df2009-11-17 04:44:12 +00003284 // Non-static data members.
3285 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3286 E = ClassDecl->field_end(); I != E; ++I) {
3287 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003288 if (Field->isInvalidDecl())
3289 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003290
3291 // Don't destroy incomplete or zero-length arrays.
3292 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3293 continue;
3294
Anders Carlsson9f853df2009-11-17 04:44:12 +00003295 QualType FieldType = Context.getBaseElementType(Field->getType());
3296
3297 const RecordType* RT = FieldType->getAs<RecordType>();
3298 if (!RT)
3299 continue;
3300
3301 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003302 if (FieldClassDecl->isInvalidDecl())
3303 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003304 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003305 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003306 // The destructor for an implicit anonymous union member is never invoked.
3307 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3308 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003309
Douglas Gregordb89f282010-07-01 22:47:18 +00003310 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003311 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003312 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003313 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003314 << Field->getDeclName()
3315 << FieldType);
3316
Eli Friedman5f2987c2012-02-02 03:46:19 +00003317 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003318 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003319 }
3320
John McCall58e6f342010-03-16 05:22:47 +00003321 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3322
Anders Carlsson9f853df2009-11-17 04:44:12 +00003323 // Bases.
3324 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3325 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003326 // Bases are always records in a well-formed non-dependent class.
3327 const RecordType *RT = Base->getType()->getAs<RecordType>();
3328
3329 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003330 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003331 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003332
John McCall58e6f342010-03-16 05:22:47 +00003333 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003334 // If our base class is invalid, we probably can't get its dtor anyway.
3335 if (BaseClassDecl->isInvalidDecl())
3336 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003337 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003338 continue;
John McCall58e6f342010-03-16 05:22:47 +00003339
Douglas Gregordb89f282010-07-01 22:47:18 +00003340 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003341 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003342
3343 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003344 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003345 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003346 << Base->getType()
3347 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003348
Eli Friedman5f2987c2012-02-02 03:46:19 +00003349 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003350 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003351 }
3352
3353 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003354 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3355 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003356
3357 // Bases are always records in a well-formed non-dependent class.
3358 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3359
3360 // Ignore direct virtual bases.
3361 if (DirectVirtualBases.count(RT))
3362 continue;
3363
John McCall58e6f342010-03-16 05:22:47 +00003364 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003365 // If our base class is invalid, we probably can't get its dtor anyway.
3366 if (BaseClassDecl->isInvalidDecl())
3367 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003368 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003369 continue;
John McCall58e6f342010-03-16 05:22:47 +00003370
Douglas Gregordb89f282010-07-01 22:47:18 +00003371 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003372 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003373 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003374 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003375 << VBase->getType());
3376
Eli Friedman5f2987c2012-02-02 03:46:19 +00003377 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003378 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003379 }
3380}
3381
John McCalld226f652010-08-21 09:40:31 +00003382void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003383 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003384 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Mike Stump1eb44332009-09-09 15:08:12 +00003386 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003387 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003388 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003389}
3390
Mike Stump1eb44332009-09-09 15:08:12 +00003391bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003392 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003393 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003394 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003395 else
John McCall94c3b562010-08-18 09:41:07 +00003396 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003397}
3398
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003399bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003400 const PartialDiagnostic &PD) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003401 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003402 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Anders Carlsson11f21a02009-03-23 19:10:31 +00003404 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003405 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Ted Kremenek6217b802009-07-29 21:53:49 +00003407 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003408 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003409 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003410 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003412 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003413 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003414 }
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Ted Kremenek6217b802009-07-29 21:53:49 +00003416 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003417 if (!RT)
3418 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003419
John McCall86ff3082010-02-04 22:26:26 +00003420 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003421
John McCall94c3b562010-08-18 09:41:07 +00003422 // We can't answer whether something is abstract until it has a
3423 // definition. If it's currently being defined, we'll walk back
3424 // over all the declarations when we have a full definition.
3425 const CXXRecordDecl *Def = RD->getDefinition();
3426 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003427 return false;
3428
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003429 if (!RD->isAbstract())
3430 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003432 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003433 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003434
John McCall94c3b562010-08-18 09:41:07 +00003435 return true;
3436}
3437
3438void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3439 // Check if we've already emitted the list of pure virtual functions
3440 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003441 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003442 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003444 CXXFinalOverriderMap FinalOverriders;
3445 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003447 // Keep a set of seen pure methods so we won't diagnose the same method
3448 // more than once.
3449 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3450
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003451 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3452 MEnd = FinalOverriders.end();
3453 M != MEnd;
3454 ++M) {
3455 for (OverridingMethods::iterator SO = M->second.begin(),
3456 SOEnd = M->second.end();
3457 SO != SOEnd; ++SO) {
3458 // C++ [class.abstract]p4:
3459 // A class is abstract if it contains or inherits at least one
3460 // pure virtual function for which the final overrider is pure
3461 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003463 //
3464 if (SO->second.size() != 1)
3465 continue;
3466
3467 if (!SO->second.front().Method->isPure())
3468 continue;
3469
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003470 if (!SeenPureMethods.insert(SO->second.front().Method))
3471 continue;
3472
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003473 Diag(SO->second.front().Method->getLocation(),
3474 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003475 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003476 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003477 }
3478
3479 if (!PureVirtualClassDiagSet)
3480 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3481 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003482}
3483
Anders Carlsson8211eff2009-03-24 01:19:16 +00003484namespace {
John McCall94c3b562010-08-18 09:41:07 +00003485struct AbstractUsageInfo {
3486 Sema &S;
3487 CXXRecordDecl *Record;
3488 CanQualType AbstractType;
3489 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003490
John McCall94c3b562010-08-18 09:41:07 +00003491 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3492 : S(S), Record(Record),
3493 AbstractType(S.Context.getCanonicalType(
3494 S.Context.getTypeDeclType(Record))),
3495 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003496
John McCall94c3b562010-08-18 09:41:07 +00003497 void DiagnoseAbstractType() {
3498 if (Invalid) return;
3499 S.DiagnoseAbstractType(Record);
3500 Invalid = true;
3501 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003502
John McCall94c3b562010-08-18 09:41:07 +00003503 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3504};
3505
3506struct CheckAbstractUsage {
3507 AbstractUsageInfo &Info;
3508 const NamedDecl *Ctx;
3509
3510 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3511 : Info(Info), Ctx(Ctx) {}
3512
3513 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3514 switch (TL.getTypeLocClass()) {
3515#define ABSTRACT_TYPELOC(CLASS, PARENT)
3516#define TYPELOC(CLASS, PARENT) \
3517 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3518#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003519 }
John McCall94c3b562010-08-18 09:41:07 +00003520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCall94c3b562010-08-18 09:41:07 +00003522 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3523 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3524 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003525 if (!TL.getArg(I))
3526 continue;
3527
John McCall94c3b562010-08-18 09:41:07 +00003528 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3529 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003530 }
John McCall94c3b562010-08-18 09:41:07 +00003531 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003532
John McCall94c3b562010-08-18 09:41:07 +00003533 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3534 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3535 }
Mike Stump1eb44332009-09-09 15:08:12 +00003536
John McCall94c3b562010-08-18 09:41:07 +00003537 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3538 // Visit the type parameters from a permissive context.
3539 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3540 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3541 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3542 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3543 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3544 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003545 }
John McCall94c3b562010-08-18 09:41:07 +00003546 }
Mike Stump1eb44332009-09-09 15:08:12 +00003547
John McCall94c3b562010-08-18 09:41:07 +00003548 // Visit pointee types from a permissive context.
3549#define CheckPolymorphic(Type) \
3550 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3551 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3552 }
3553 CheckPolymorphic(PointerTypeLoc)
3554 CheckPolymorphic(ReferenceTypeLoc)
3555 CheckPolymorphic(MemberPointerTypeLoc)
3556 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003557 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003558
John McCall94c3b562010-08-18 09:41:07 +00003559 /// Handle all the types we haven't given a more specific
3560 /// implementation for above.
3561 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3562 // Every other kind of type that we haven't called out already
3563 // that has an inner type is either (1) sugar or (2) contains that
3564 // inner type in some way as a subobject.
3565 if (TypeLoc Next = TL.getNextTypeLoc())
3566 return Visit(Next, Sel);
3567
3568 // If there's no inner type and we're in a permissive context,
3569 // don't diagnose.
3570 if (Sel == Sema::AbstractNone) return;
3571
3572 // Check whether the type matches the abstract type.
3573 QualType T = TL.getType();
3574 if (T->isArrayType()) {
3575 Sel = Sema::AbstractArrayType;
3576 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003577 }
John McCall94c3b562010-08-18 09:41:07 +00003578 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3579 if (CT != Info.AbstractType) return;
3580
3581 // It matched; do some magic.
3582 if (Sel == Sema::AbstractArrayType) {
3583 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3584 << T << TL.getSourceRange();
3585 } else {
3586 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3587 << Sel << T << TL.getSourceRange();
3588 }
3589 Info.DiagnoseAbstractType();
3590 }
3591};
3592
3593void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3594 Sema::AbstractDiagSelID Sel) {
3595 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3596}
3597
3598}
3599
3600/// Check for invalid uses of an abstract type in a method declaration.
3601static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3602 CXXMethodDecl *MD) {
3603 // No need to do the check on definitions, which require that
3604 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003605 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003606 return;
3607
3608 // For safety's sake, just ignore it if we don't have type source
3609 // information. This should never happen for non-implicit methods,
3610 // but...
3611 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3612 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3613}
3614
3615/// Check for invalid uses of an abstract type within a class definition.
3616static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3617 CXXRecordDecl *RD) {
3618 for (CXXRecordDecl::decl_iterator
3619 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3620 Decl *D = *I;
3621 if (D->isImplicit()) continue;
3622
3623 // Methods and method templates.
3624 if (isa<CXXMethodDecl>(D)) {
3625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3626 } else if (isa<FunctionTemplateDecl>(D)) {
3627 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3628 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3629
3630 // Fields and static variables.
3631 } else if (isa<FieldDecl>(D)) {
3632 FieldDecl *FD = cast<FieldDecl>(D);
3633 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3634 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3635 } else if (isa<VarDecl>(D)) {
3636 VarDecl *VD = cast<VarDecl>(D);
3637 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3638 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3639
3640 // Nested classes and class templates.
3641 } else if (isa<CXXRecordDecl>(D)) {
3642 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3643 } else if (isa<ClassTemplateDecl>(D)) {
3644 CheckAbstractClassUsage(Info,
3645 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3646 }
3647 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003648}
3649
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003650/// \brief Perform semantic checks on a class definition that has been
3651/// completing, introducing implicitly-declared members, checking for
3652/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003653void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003654 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003655 return;
3656
John McCall94c3b562010-08-18 09:41:07 +00003657 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3658 AbstractUsageInfo Info(*this, Record);
3659 CheckAbstractClassUsage(Info, Record);
3660 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003661
3662 // If this is not an aggregate type and has no user-declared constructor,
3663 // complain about any non-static data members of reference or const scalar
3664 // type, since they will never get initializers.
3665 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003666 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3667 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003668 bool Complained = false;
3669 for (RecordDecl::field_iterator F = Record->field_begin(),
3670 FEnd = Record->field_end();
3671 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003672 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003673 continue;
3674
Douglas Gregor325e5932010-04-15 00:00:53 +00003675 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003676 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003677 if (!Complained) {
3678 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3679 << Record->getTagKind() << Record;
3680 Complained = true;
3681 }
3682
3683 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3684 << F->getType()->isReferenceType()
3685 << F->getDeclName();
3686 }
3687 }
3688 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003689
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003690 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003691 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003692
3693 if (Record->getIdentifier()) {
3694 // C++ [class.mem]p13:
3695 // If T is the name of a class, then each of the following shall have a
3696 // name different from T:
3697 // - every member of every anonymous union that is a member of class T.
3698 //
3699 // C++ [class.mem]p14:
3700 // In addition, if class T has a user-declared constructor (12.1), every
3701 // non-static data member of class T shall have a name different from T.
3702 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003703 R.first != R.second; ++R.first) {
3704 NamedDecl *D = *R.first;
3705 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3706 isa<IndirectFieldDecl>(D)) {
3707 Diag(D->getLocation(), diag::err_member_name_of_class)
3708 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003709 break;
3710 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003711 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003712 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003713
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003714 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003715 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003716 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003717 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003718 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3719 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3720 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003721
3722 // See if a method overloads virtual methods in a base
3723 /// class without overriding any.
3724 if (!Record->isDependentType()) {
3725 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3726 MEnd = Record->method_end();
3727 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003728 if (!(*M)->isStatic())
3729 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003730 }
3731 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003732
Richard Smith9f569cc2011-10-01 02:31:28 +00003733 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3734 // function that is not a constructor declares that member function to be
3735 // const. [...] The class of which that function is a member shall be
3736 // a literal type.
3737 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003738 // If the class has virtual bases, any constexpr members will already have
3739 // been diagnosed by the checks performed on the member declaration, so
3740 // suppress this (less useful) diagnostic.
3741 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3742 !Record->isLiteral() && !Record->getNumVBases()) {
3743 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3744 MEnd = Record->method_end();
3745 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003746 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003747 switch (Record->getTemplateSpecializationKind()) {
3748 case TSK_ImplicitInstantiation:
3749 case TSK_ExplicitInstantiationDeclaration:
3750 case TSK_ExplicitInstantiationDefinition:
3751 // If a template instantiates to a non-literal type, but its members
3752 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003753 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003754 continue;
3755
3756 case TSK_Undeclared:
3757 case TSK_ExplicitSpecialization:
3758 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3759 PDiag(diag::err_constexpr_method_non_literal));
3760 break;
3761 }
3762
3763 // Only produce one error per class.
3764 break;
3765 }
3766 }
3767 }
3768
Sebastian Redlf677ea32011-02-05 19:23:19 +00003769 // Declare inherited constructors. We do this eagerly here because:
3770 // - The standard requires an eager diagnostic for conflicting inherited
3771 // constructors from different classes.
3772 // - The lazy declaration of the other implicit constructors is so as to not
3773 // waste space and performance on classes that are not meant to be
3774 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3775 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003776 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003777
Sean Hunteb88ae52011-05-23 21:07:59 +00003778 if (!Record->isDependentType())
3779 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003780}
3781
3782void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003783 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3784 ME = Record->method_end();
3785 MI != ME; ++MI) {
3786 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3787 switch (getSpecialMember(*MI)) {
3788 case CXXDefaultConstructor:
3789 CheckExplicitlyDefaultedDefaultConstructor(
3790 cast<CXXConstructorDecl>(*MI));
3791 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003792
Sean Huntcb45a0f2011-05-12 22:46:25 +00003793 case CXXDestructor:
3794 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3795 break;
3796
3797 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003798 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3799 break;
3800
Sean Huntcb45a0f2011-05-12 22:46:25 +00003801 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003802 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003803 break;
3804
Sean Hunt82713172011-05-25 23:16:36 +00003805 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003806 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003807 break;
3808
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003809 case CXXMoveAssignment:
3810 CheckExplicitlyDefaultedMoveAssignment(*MI);
3811 break;
3812
3813 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003814 llvm_unreachable("non-special member explicitly defaulted!");
3815 }
Sean Hunt001cad92011-05-10 00:49:42 +00003816 }
3817 }
3818
Sean Hunt001cad92011-05-10 00:49:42 +00003819}
3820
3821void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3822 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3823
3824 // Whether this was the first-declared instance of the constructor.
3825 // This affects whether we implicitly add an exception spec (and, eventually,
3826 // constexpr). It is also ill-formed to explicitly default a constructor such
3827 // that it would be deleted. (C++0x [decl.fct.def.default])
3828 bool First = CD == CD->getCanonicalDecl();
3829
Sean Hunt49634cf2011-05-13 06:10:58 +00003830 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003831 if (CD->getNumParams() != 0) {
3832 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3833 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003834 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003835 }
3836
3837 ImplicitExceptionSpecification Spec
3838 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3839 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003840 if (EPI.ExceptionSpecType == EST_Delayed) {
3841 // Exception specification depends on some deferred part of the class. We'll
3842 // try again when the class's definition has been fully processed.
3843 return;
3844 }
Sean Hunt001cad92011-05-10 00:49:42 +00003845 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3846 *ExceptionType = Context.getFunctionType(
3847 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3848
Richard Smith61802452011-12-22 02:22:31 +00003849 // C++11 [dcl.fct.def.default]p2:
3850 // An explicitly-defaulted function may be declared constexpr only if it
3851 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003852 // Do not apply this rule to templates, since core issue 1358 makes such
3853 // functions always instantiate to constexpr functions.
3854 if (CD->isConstexpr() &&
3855 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003856 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3857 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3858 << CXXDefaultConstructor;
3859 HadError = true;
3860 }
3861 }
3862 // and may have an explicit exception-specification only if it is compatible
3863 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003864 if (CtorType->hasExceptionSpec()) {
3865 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003866 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003867 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003868 PDiag(),
3869 ExceptionType, SourceLocation(),
3870 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003871 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003872 }
Richard Smith61802452011-12-22 02:22:31 +00003873 }
3874
3875 // If a function is explicitly defaulted on its first declaration,
3876 if (First) {
3877 // -- it is implicitly considered to be constexpr if the implicit
3878 // definition would be,
3879 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3880
3881 // -- it is implicitly considered to have the same
3882 // exception-specification as if it had been implicitly declared
3883 //
3884 // FIXME: a compatible, but different, explicit exception specification
3885 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003886 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithe653ba22012-02-26 00:31:33 +00003887
3888 // Such a function is also trivial if the implicitly-declared function
3889 // would have been.
3890 CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
Sean Hunt001cad92011-05-10 00:49:42 +00003891 }
Sean Huntca46d132011-05-12 03:51:48 +00003892
Sean Hunt49634cf2011-05-13 06:10:58 +00003893 if (HadError) {
3894 CD->setInvalidDecl();
3895 return;
3896 }
3897
Sean Hunte16da072011-10-10 06:18:57 +00003898 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003899 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003900 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003901 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003902 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003903 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003904 CD->setInvalidDecl();
3905 }
3906 }
3907}
3908
3909void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3910 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3911
3912 // Whether this was the first-declared instance of the constructor.
3913 bool First = CD == CD->getCanonicalDecl();
3914
3915 bool HadError = false;
3916 if (CD->getNumParams() != 1) {
3917 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3918 << CD->getSourceRange();
3919 HadError = true;
3920 }
3921
3922 ImplicitExceptionSpecification Spec(Context);
3923 bool Const;
3924 llvm::tie(Spec, Const) =
3925 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3926
3927 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3928 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3929 *ExceptionType = Context.getFunctionType(
3930 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3931
3932 // Check for parameter type matching.
3933 // This is a copy ctor so we know it's a cv-qualified reference to T.
3934 QualType ArgType = CtorType->getArgType(0);
3935 if (ArgType->getPointeeType().isVolatileQualified()) {
3936 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3937 HadError = true;
3938 }
3939 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3940 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3941 HadError = true;
3942 }
3943
Richard Smith61802452011-12-22 02:22:31 +00003944 // C++11 [dcl.fct.def.default]p2:
3945 // An explicitly-defaulted function may be declared constexpr only if it
3946 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003947 // Do not apply this rule to templates, since core issue 1358 makes such
3948 // functions always instantiate to constexpr functions.
3949 if (CD->isConstexpr() &&
3950 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003951 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3952 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3953 << CXXCopyConstructor;
3954 HadError = true;
3955 }
3956 }
3957 // and may have an explicit exception-specification only if it is compatible
3958 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003959 if (CtorType->hasExceptionSpec()) {
3960 if (CheckEquivalentExceptionSpec(
3961 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003962 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003963 PDiag(),
3964 ExceptionType, SourceLocation(),
3965 CtorType, CD->getLocation())) {
3966 HadError = true;
3967 }
Richard Smith61802452011-12-22 02:22:31 +00003968 }
3969
3970 // If a function is explicitly defaulted on its first declaration,
3971 if (First) {
3972 // -- it is implicitly considered to be constexpr if the implicit
3973 // definition would be,
3974 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3975
3976 // -- it is implicitly considered to have the same
3977 // exception-specification as if it had been implicitly declared, and
3978 //
3979 // FIXME: a compatible, but different, explicit exception specification
3980 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003981 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003982
3983 // -- [...] it shall have the same parameter type as if it had been
3984 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003985 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00003986
3987 // Such a function is also trivial if the implicitly-declared function
3988 // would have been.
3989 CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00003990 }
3991
3992 if (HadError) {
3993 CD->setInvalidDecl();
3994 return;
3995 }
3996
Sean Huntc32d6842011-10-11 04:55:36 +00003997 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003998 if (First) {
3999 CD->setDeletedAsWritten();
4000 } else {
4001 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004002 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004003 CD->setInvalidDecl();
4004 }
Sean Huntca46d132011-05-12 03:51:48 +00004005 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004006}
Sean Hunt001cad92011-05-10 00:49:42 +00004007
Sean Hunt2b188082011-05-14 05:23:28 +00004008void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4009 assert(MD->isExplicitlyDefaulted());
4010
4011 // Whether this was the first-declared instance of the operator
4012 bool First = MD == MD->getCanonicalDecl();
4013
4014 bool HadError = false;
4015 if (MD->getNumParams() != 1) {
4016 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4017 << MD->getSourceRange();
4018 HadError = true;
4019 }
4020
4021 QualType ReturnType =
4022 MD->getType()->getAs<FunctionType>()->getResultType();
4023 if (!ReturnType->isLValueReferenceType() ||
4024 !Context.hasSameType(
4025 Context.getCanonicalType(ReturnType->getPointeeType()),
4026 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4027 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4028 HadError = true;
4029 }
4030
4031 ImplicitExceptionSpecification Spec(Context);
4032 bool Const;
4033 llvm::tie(Spec, Const) =
4034 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4035
4036 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4037 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4038 *ExceptionType = Context.getFunctionType(
4039 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4040
Sean Hunt2b188082011-05-14 05:23:28 +00004041 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004042 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004043 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004044 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004045 } else {
4046 if (ArgType->getPointeeType().isVolatileQualified()) {
4047 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4048 HadError = true;
4049 }
4050 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4051 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4052 HadError = true;
4053 }
Sean Hunt2b188082011-05-14 05:23:28 +00004054 }
Sean Huntbe631222011-05-17 20:44:43 +00004055
Sean Hunt2b188082011-05-14 05:23:28 +00004056 if (OperType->getTypeQuals()) {
4057 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4058 HadError = true;
4059 }
4060
4061 if (OperType->hasExceptionSpec()) {
4062 if (CheckEquivalentExceptionSpec(
4063 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004064 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004065 PDiag(),
4066 ExceptionType, SourceLocation(),
4067 OperType, MD->getLocation())) {
4068 HadError = true;
4069 }
Richard Smith61802452011-12-22 02:22:31 +00004070 }
4071 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004072 // We set the declaration to have the computed exception spec here.
4073 // We duplicate the one parameter type.
4074 EPI.RefQualifier = OperType->getRefQualifier();
4075 EPI.ExtInfo = OperType->getExtInfo();
4076 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004077
4078 // Such a function is also trivial if the implicitly-declared function
4079 // would have been.
4080 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
Sean Hunt2b188082011-05-14 05:23:28 +00004081 }
4082
4083 if (HadError) {
4084 MD->setInvalidDecl();
4085 return;
4086 }
4087
Richard Smith7d5088a2012-02-18 02:02:13 +00004088 if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
Sean Hunt2b188082011-05-14 05:23:28 +00004089 if (First) {
4090 MD->setDeletedAsWritten();
4091 } else {
4092 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004093 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004094 MD->setInvalidDecl();
4095 }
4096 }
4097}
4098
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004099void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4100 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4101
4102 // Whether this was the first-declared instance of the constructor.
4103 bool First = CD == CD->getCanonicalDecl();
4104
4105 bool HadError = false;
4106 if (CD->getNumParams() != 1) {
4107 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4108 << CD->getSourceRange();
4109 HadError = true;
4110 }
4111
4112 ImplicitExceptionSpecification Spec(
4113 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4114
4115 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4116 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4117 *ExceptionType = Context.getFunctionType(
4118 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4119
4120 // Check for parameter type matching.
4121 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4122 QualType ArgType = CtorType->getArgType(0);
4123 if (ArgType->getPointeeType().isVolatileQualified()) {
4124 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4125 HadError = true;
4126 }
4127 if (ArgType->getPointeeType().isConstQualified()) {
4128 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4129 HadError = true;
4130 }
4131
Richard Smith61802452011-12-22 02:22:31 +00004132 // C++11 [dcl.fct.def.default]p2:
4133 // An explicitly-defaulted function may be declared constexpr only if it
4134 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004135 // Do not apply this rule to templates, since core issue 1358 makes such
4136 // functions always instantiate to constexpr functions.
4137 if (CD->isConstexpr() &&
4138 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004139 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4140 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4141 << CXXMoveConstructor;
4142 HadError = true;
4143 }
4144 }
4145 // and may have an explicit exception-specification only if it is compatible
4146 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004147 if (CtorType->hasExceptionSpec()) {
4148 if (CheckEquivalentExceptionSpec(
4149 PDiag(diag::err_incorrect_defaulted_exception_spec)
4150 << CXXMoveConstructor,
4151 PDiag(),
4152 ExceptionType, SourceLocation(),
4153 CtorType, CD->getLocation())) {
4154 HadError = true;
4155 }
Richard Smith61802452011-12-22 02:22:31 +00004156 }
4157
4158 // If a function is explicitly defaulted on its first declaration,
4159 if (First) {
4160 // -- it is implicitly considered to be constexpr if the implicit
4161 // definition would be,
4162 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4163
4164 // -- it is implicitly considered to have the same
4165 // exception-specification as if it had been implicitly declared, and
4166 //
4167 // FIXME: a compatible, but different, explicit exception specification
4168 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004169 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004170
4171 // -- [...] it shall have the same parameter type as if it had been
4172 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004173 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004174
4175 // Such a function is also trivial if the implicitly-declared function
4176 // would have been.
4177 CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004178 }
4179
4180 if (HadError) {
4181 CD->setInvalidDecl();
4182 return;
4183 }
4184
Sean Hunt769bb2d2011-10-11 06:43:29 +00004185 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004186 if (First) {
4187 CD->setDeletedAsWritten();
4188 } else {
4189 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4190 << CXXMoveConstructor;
4191 CD->setInvalidDecl();
4192 }
4193 }
4194}
4195
4196void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4197 assert(MD->isExplicitlyDefaulted());
4198
4199 // Whether this was the first-declared instance of the operator
4200 bool First = MD == MD->getCanonicalDecl();
4201
4202 bool HadError = false;
4203 if (MD->getNumParams() != 1) {
4204 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4205 << MD->getSourceRange();
4206 HadError = true;
4207 }
4208
4209 QualType ReturnType =
4210 MD->getType()->getAs<FunctionType>()->getResultType();
4211 if (!ReturnType->isLValueReferenceType() ||
4212 !Context.hasSameType(
4213 Context.getCanonicalType(ReturnType->getPointeeType()),
4214 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4215 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4216 HadError = true;
4217 }
4218
4219 ImplicitExceptionSpecification Spec(
4220 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4221
4222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4223 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4224 *ExceptionType = Context.getFunctionType(
4225 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4226
4227 QualType ArgType = OperType->getArgType(0);
4228 if (!ArgType->isRValueReferenceType()) {
4229 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4230 HadError = true;
4231 } else {
4232 if (ArgType->getPointeeType().isVolatileQualified()) {
4233 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4234 HadError = true;
4235 }
4236 if (ArgType->getPointeeType().isConstQualified()) {
4237 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4238 HadError = true;
4239 }
4240 }
4241
4242 if (OperType->getTypeQuals()) {
4243 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4244 HadError = true;
4245 }
4246
4247 if (OperType->hasExceptionSpec()) {
4248 if (CheckEquivalentExceptionSpec(
4249 PDiag(diag::err_incorrect_defaulted_exception_spec)
4250 << CXXMoveAssignment,
4251 PDiag(),
4252 ExceptionType, SourceLocation(),
4253 OperType, MD->getLocation())) {
4254 HadError = true;
4255 }
Richard Smith61802452011-12-22 02:22:31 +00004256 }
4257 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004258 // We set the declaration to have the computed exception spec here.
4259 // We duplicate the one parameter type.
4260 EPI.RefQualifier = OperType->getRefQualifier();
4261 EPI.ExtInfo = OperType->getExtInfo();
4262 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004263
4264 // Such a function is also trivial if the implicitly-declared function
4265 // would have been.
4266 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004267 }
4268
4269 if (HadError) {
4270 MD->setInvalidDecl();
4271 return;
4272 }
4273
Richard Smith7d5088a2012-02-18 02:02:13 +00004274 if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004275 if (First) {
4276 MD->setDeletedAsWritten();
4277 } else {
4278 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4279 << CXXMoveAssignment;
4280 MD->setInvalidDecl();
4281 }
4282 }
4283}
4284
Sean Huntcb45a0f2011-05-12 22:46:25 +00004285void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4286 assert(DD->isExplicitlyDefaulted());
4287
4288 // Whether this was the first-declared instance of the destructor.
4289 bool First = DD == DD->getCanonicalDecl();
4290
4291 ImplicitExceptionSpecification Spec
4292 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4293 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4294 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4295 *ExceptionType = Context.getFunctionType(
4296 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4297
4298 if (DtorType->hasExceptionSpec()) {
4299 if (CheckEquivalentExceptionSpec(
4300 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004301 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004302 PDiag(),
4303 ExceptionType, SourceLocation(),
4304 DtorType, DD->getLocation())) {
4305 DD->setInvalidDecl();
4306 return;
4307 }
Richard Smith61802452011-12-22 02:22:31 +00004308 }
4309 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004310 // We set the declaration to have the computed exception spec here.
4311 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004312 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004313 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004314
4315 // Such a function is also trivial if the implicitly-declared function
4316 // would have been.
4317 DD->setTrivial(DD->getParent()->hasTrivialDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00004318 }
4319
Richard Smith7d5088a2012-02-18 02:02:13 +00004320 if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004321 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004322 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004323 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004324 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004325 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004326 DD->setInvalidDecl();
4327 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004328 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004329}
4330
Richard Smith7d5088a2012-02-18 02:02:13 +00004331namespace {
4332struct SpecialMemberDeletionInfo {
4333 Sema &S;
4334 CXXMethodDecl *MD;
4335 Sema::CXXSpecialMember CSM;
4336
4337 // Properties of the special member, computed for convenience.
4338 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4339 SourceLocation Loc;
4340
4341 bool AllFieldsAreConst;
4342
4343 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4344 Sema::CXXSpecialMember CSM)
4345 : S(S), MD(MD), CSM(CSM),
4346 IsConstructor(false), IsAssignment(false), IsMove(false),
4347 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4348 AllFieldsAreConst(true) {
4349 switch (CSM) {
4350 case Sema::CXXDefaultConstructor:
4351 case Sema::CXXCopyConstructor:
4352 IsConstructor = true;
4353 break;
4354 case Sema::CXXMoveConstructor:
4355 IsConstructor = true;
4356 IsMove = true;
4357 break;
4358 case Sema::CXXCopyAssignment:
4359 IsAssignment = true;
4360 break;
4361 case Sema::CXXMoveAssignment:
4362 IsAssignment = true;
4363 IsMove = true;
4364 break;
4365 case Sema::CXXDestructor:
4366 break;
4367 case Sema::CXXInvalid:
4368 llvm_unreachable("invalid special member kind");
4369 }
4370
4371 if (MD->getNumParams()) {
4372 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4373 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4374 }
4375 }
4376
4377 bool inUnion() const { return MD->getParent()->isUnion(); }
4378
4379 /// Look up the corresponding special member in the given class.
4380 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4381 unsigned TQ = MD->getTypeQualifiers();
4382 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4383 MD->getRefQualifier() == RQ_RValue,
4384 TQ & Qualifiers::Const,
4385 TQ & Qualifiers::Volatile);
4386 }
4387
Richard Smith9a561d52012-02-26 09:11:52 +00004388 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, FieldDecl *Field);
4389
Richard Smith7d5088a2012-02-18 02:02:13 +00004390 bool shouldDeleteForBase(CXXRecordDecl *BaseDecl, bool IsVirtualBase);
4391 bool shouldDeleteForField(FieldDecl *FD);
4392 bool shouldDeleteForAllConstMembers();
4393};
4394}
4395
Richard Smith9a561d52012-02-26 09:11:52 +00004396/// Check whether we should delete a special member function due to having a
4397/// direct or virtual base class or static data member of class type M.
4398bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4399 CXXRecordDecl *Class, FieldDecl *Field) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004400 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
4401 // -- any direct or virtual base class [...] has a type with a destructor
4402 // that is deleted or inaccessible
4403 if (!IsAssignment) {
Richard Smith9a561d52012-02-26 09:11:52 +00004404 CXXDestructorDecl *Dtor = S.LookupDestructor(Class);
4405 if (Dtor->isDeleted())
Richard Smith7d5088a2012-02-18 02:02:13 +00004406 return true;
Richard Smith9a561d52012-02-26 09:11:52 +00004407 if (S.CheckDestructorAccess(Loc, Dtor, S.PDiag()) != Sema::AR_accessible)
4408 return true;
4409
4410 // C++11 [class.dtor]p5:
4411 // -- X is a union-like class that has a variant member with a non-trivial
4412 // destructor
4413 if (CSM == Sema::CXXDestructor && Field && Field->getParent()->isUnion() &&
4414 !Dtor->isTrivial())
Richard Smith7d5088a2012-02-18 02:02:13 +00004415 return true;
4416 }
4417
4418 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004419 // -- any direct or virtual base class, or non-static data member with no
4420 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004421 // either M has no default constructor or overload resolution as applied
4422 // to M's default constructor results in an ambiguity or in a function
4423 // that is deleted or inaccessible
4424 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4425 // -- a direct or virtual base class B that cannot be copied/moved because
4426 // overload resolution, as applied to B's corresponding special member,
4427 // results in an ambiguity or a function that is deleted or inaccessible
4428 // from the defaulted special member
Richard Smithdf8dc862012-03-29 19:00:10 +00004429 if (CSM != Sema::CXXDestructor &&
4430 !(CSM == Sema::CXXDefaultConstructor &&
4431 Field && Field->hasInClassInitializer())) {
Richard Smith9a561d52012-02-26 09:11:52 +00004432 Sema::SpecialMemberOverloadResult *SMOR = lookupIn(Class);
Richard Smith7d5088a2012-02-18 02:02:13 +00004433 if (!SMOR->hasSuccess())
4434 return true;
4435
Richard Smith9a561d52012-02-26 09:11:52 +00004436 CXXMethodDecl *Member = SMOR->getMethod();
4437 // A member of a union must have a trivial corresponding special member.
4438 if (Field && Field->getParent()->isUnion() && !Member->isTrivial())
4439 return true;
4440
Richard Smith7d5088a2012-02-18 02:02:13 +00004441 if (IsConstructor) {
Richard Smith9a561d52012-02-26 09:11:52 +00004442 CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Member);
4443 if (S.CheckConstructorAccess(Loc, Ctor, Ctor->getAccess(), S.PDiag())
4444 != Sema::AR_accessible)
Richard Smith7d5088a2012-02-18 02:02:13 +00004445 return true;
4446
4447 // -- for the move constructor, a [...] direct or virtual base class with
4448 // a type that does not have a move constructor and is not trivially
4449 // copyable.
Richard Smith9a561d52012-02-26 09:11:52 +00004450 if (IsMove && !Ctor->isMoveConstructor() && !Class->isTriviallyCopyable())
Richard Smith7d5088a2012-02-18 02:02:13 +00004451 return true;
4452 } else {
4453 assert(IsAssignment && "unexpected kind of special member");
Richard Smith9a561d52012-02-26 09:11:52 +00004454 if (S.CheckDirectMemberAccess(Loc, Member, S.PDiag())
Richard Smith7d5088a2012-02-18 02:02:13 +00004455 != Sema::AR_accessible)
4456 return true;
4457
4458 // -- for the move assignment operator, a direct base class with a type
4459 // that does not have a move assignment operator and is not trivially
4460 // copyable.
Richard Smith9a561d52012-02-26 09:11:52 +00004461 if (IsMove && !Member->isMoveAssignmentOperator() &&
4462 !Class->isTriviallyCopyable())
Richard Smith7d5088a2012-02-18 02:02:13 +00004463 return true;
4464 }
4465 }
4466
Richard Smith9a561d52012-02-26 09:11:52 +00004467 return false;
4468}
4469
4470/// Check whether we should delete a special member function due to the class
4471/// having a particular direct or virtual base class.
4472bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXRecordDecl *BaseDecl,
4473 bool IsVirtualBase) {
4474 // C++11 [class.copy]p23:
4475 // -- for the move assignment operator, any direct or indirect virtual
4476 // base class.
4477 if (CSM == Sema::CXXMoveAssignment && IsVirtualBase)
4478 return true;
4479
4480 if (shouldDeleteForClassSubobject(BaseDecl, 0))
4481 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004482
4483 return false;
4484}
4485
4486/// Check whether we should delete a special member function due to the class
4487/// having a particular non-static data member.
4488bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4489 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4490 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4491
4492 if (CSM == Sema::CXXDefaultConstructor) {
4493 // For a default constructor, all references must be initialized in-class
4494 // and, if a union, it must have a non-const member.
4495 if (FieldType->isReferenceType() && !FD->hasInClassInitializer())
4496 return true;
4497
4498 if (inUnion() && !FieldType.isConstQualified())
4499 AllFieldsAreConst = false;
Richard Smith79363f52012-02-27 06:07:25 +00004500
4501 // C++11 [class.ctor]p5: any non-variant non-static data member of
4502 // const-qualified type (or array thereof) with no
4503 // brace-or-equal-initializer does not have a user-provided default
4504 // constructor.
4505 if (!inUnion() && FieldType.isConstQualified() &&
4506 !FD->hasInClassInitializer() &&
4507 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor()))
4508 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004509 } else if (CSM == Sema::CXXCopyConstructor) {
4510 // For a copy constructor, data members must not be of rvalue reference
4511 // type.
4512 if (FieldType->isRValueReferenceType())
4513 return true;
4514 } else if (IsAssignment) {
4515 // For an assignment operator, data members must not be of reference type.
4516 if (FieldType->isReferenceType())
4517 return true;
4518 }
4519
4520 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004521 // Some additional restrictions exist on the variant members.
4522 if (!inUnion() && FieldRecord->isUnion() &&
4523 FieldRecord->isAnonymousStructOrUnion()) {
4524 bool AllVariantFieldsAreConst = true;
4525
Richard Smithdf8dc862012-03-29 19:00:10 +00004526 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004527 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4528 UE = FieldRecord->field_end();
4529 UI != UE; ++UI) {
4530 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004531
4532 if (!UnionFieldType.isConstQualified())
4533 AllVariantFieldsAreConst = false;
4534
Richard Smith9a561d52012-02-26 09:11:52 +00004535 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4536 if (UnionFieldRecord &&
4537 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4538 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004539 }
4540
4541 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004542 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4543 FieldRecord->field_begin() != FieldRecord->field_end())
Richard Smith7d5088a2012-02-18 02:02:13 +00004544 return true;
4545
Richard Smithdf8dc862012-03-29 19:00:10 +00004546 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004547 // This is technically non-conformant, but sanity demands it.
4548 return false;
4549 }
4550
Richard Smithdf8dc862012-03-29 19:00:10 +00004551 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4552 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004553 } else if (IsAssignment && FieldType.isConstQualified()) {
4554 // C++11 [class.copy]p23:
4555 // -- a non-static data member of const non-class type (or array thereof)
4556 return true;
4557 }
4558
4559 return false;
4560}
4561
4562/// C++11 [class.ctor] p5:
4563/// A defaulted default constructor for a class X is defined as deleted if
4564/// X is a union and all of its variant members are of const-qualified type.
4565bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004566 // This is a silly definition, because it gives an empty union a deleted
4567 // default constructor. Don't do that.
4568 return CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4569 (MD->getParent()->field_begin() != MD->getParent()->field_end());
Richard Smith7d5088a2012-02-18 02:02:13 +00004570}
4571
4572/// Determine whether a defaulted special member function should be defined as
4573/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4574/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Sean Hunte16da072011-10-10 06:18:57 +00004575bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4576 assert(!MD->isInvalidDecl());
4577 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004578 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004579 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004580 return false;
4581
Richard Smith9a561d52012-02-26 09:11:52 +00004582 // FIXME: Provide the ability to diagnose why a special member was deleted.
4583
Richard Smith7d5088a2012-02-18 02:02:13 +00004584 // C++11 [expr.lambda.prim]p19:
4585 // The closure type associated with a lambda-expression has a
4586 // deleted (8.4.3) default constructor and a deleted copy
4587 // assignment operator.
4588 if (RD->isLambda() &&
4589 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment))
4590 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004591
Richard Smith9a561d52012-02-26 09:11:52 +00004592 // C++11 [class.dtor]p5:
4593 // -- for a virtual destructor, lookup of the non-array deallocation function
4594 // results in an ambiguity or in a function that is deleted or inaccessible
4595 if (CSM == Sema::CXXDestructor && MD->isVirtual()) {
4596 FunctionDecl *OperatorDelete = 0;
4597 DeclarationName Name =
4598 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4599 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4600 OperatorDelete, false))
4601 return true;
4602 }
4603
Richard Smith7d5088a2012-02-18 02:02:13 +00004604 // For an anonymous struct or union, the copy and assignment special members
4605 // will never be used, so skip the check. For an anonymous union declared at
4606 // namespace scope, the constructor and destructor are used.
4607 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4608 RD->isAnonymousStructOrUnion())
4609 return false;
Sean Hunt71a682f2011-05-18 03:41:58 +00004610
Sean Huntc32d6842011-10-11 04:55:36 +00004611 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004612 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004613
Richard Smith7d5088a2012-02-18 02:02:13 +00004614 SpecialMemberDeletionInfo SMI(*this, MD, CSM);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004615
Sean Huntcdee3fe2011-05-11 22:34:38 +00004616 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004617 BE = RD->bases_end(); BI != BE; ++BI)
4618 if (!BI->isVirtual() &&
4619 SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), false))
4620 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004621
4622 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004623 BE = RD->vbases_end(); BI != BE; ++BI)
4624 if (SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), true))
4625 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004626
4627 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004628 FE = RD->field_end(); FI != FE; ++FI)
4629 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4630 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004631 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004632
Richard Smith7d5088a2012-02-18 02:02:13 +00004633 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004634 return true;
4635
4636 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004637}
4638
4639/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004640namespace {
4641 struct FindHiddenVirtualMethodData {
4642 Sema *S;
4643 CXXMethodDecl *Method;
4644 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004645 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004646 };
4647}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004648
4649/// \brief Member lookup function that determines whether a given C++
4650/// method overloads virtual methods in a base class without overriding any,
4651/// to be used with CXXRecordDecl::lookupInBases().
4652static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4653 CXXBasePath &Path,
4654 void *UserData) {
4655 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4656
4657 FindHiddenVirtualMethodData &Data
4658 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4659
4660 DeclarationName Name = Data.Method->getDeclName();
4661 assert(Name.getNameKind() == DeclarationName::Identifier);
4662
4663 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004664 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004665 for (Path.Decls = BaseRecord->lookup(Name);
4666 Path.Decls.first != Path.Decls.second;
4667 ++Path.Decls.first) {
4668 NamedDecl *D = *Path.Decls.first;
4669 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004670 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004671 foundSameNameMethod = true;
4672 // Interested only in hidden virtual methods.
4673 if (!MD->isVirtual())
4674 continue;
4675 // If the method we are checking overrides a method from its base
4676 // don't warn about the other overloaded methods.
4677 if (!Data.S->IsOverload(Data.Method, MD, false))
4678 return true;
4679 // Collect the overload only if its hidden.
4680 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4681 overloadedMethods.push_back(MD);
4682 }
4683 }
4684
4685 if (foundSameNameMethod)
4686 Data.OverloadedMethods.append(overloadedMethods.begin(),
4687 overloadedMethods.end());
4688 return foundSameNameMethod;
4689}
4690
4691/// \brief See if a method overloads virtual methods in a base class without
4692/// overriding any.
4693void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4694 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004695 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004696 return;
4697 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4698 return;
4699
4700 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4701 /*bool RecordPaths=*/false,
4702 /*bool DetectVirtual=*/false);
4703 FindHiddenVirtualMethodData Data;
4704 Data.Method = MD;
4705 Data.S = this;
4706
4707 // Keep the base methods that were overriden or introduced in the subclass
4708 // by 'using' in a set. A base method not in this set is hidden.
4709 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4710 res.first != res.second; ++res.first) {
4711 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4712 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4713 E = MD->end_overridden_methods();
4714 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004715 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004716 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4717 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004718 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004719 }
4720
4721 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4722 !Data.OverloadedMethods.empty()) {
4723 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4724 << MD << (Data.OverloadedMethods.size() > 1);
4725
4726 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4727 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4728 Diag(overloadedMD->getLocation(),
4729 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4730 }
4731 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004732}
4733
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004734void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004735 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004736 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004737 SourceLocation RBrac,
4738 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004739 if (!TagDecl)
4740 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Douglas Gregor42af25f2009-05-11 19:58:34 +00004742 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004743
David Blaikie77b6de02011-09-22 02:58:26 +00004744 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004745 // strict aliasing violation!
4746 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004747 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004748
Douglas Gregor23c94db2010-07-02 17:43:08 +00004749 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004750 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004751}
4752
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004753/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4754/// special functions, such as the default constructor, copy
4755/// constructor, or destructor, to the given C++ class (C++
4756/// [special]p1). This routine can only be executed just before the
4757/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004758void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004759 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004760 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004761
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004762 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004763 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004764
David Blaikie4e4d0842012-03-11 07:00:24 +00004765 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004766 ++ASTContext::NumImplicitMoveConstructors;
4767
Douglas Gregora376d102010-07-02 21:50:04 +00004768 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4769 ++ASTContext::NumImplicitCopyAssignmentOperators;
4770
4771 // If we have a dynamic class, then the copy assignment operator may be
4772 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4773 // it shows up in the right place in the vtable and that we diagnose
4774 // problems with the implicit exception specification.
4775 if (ClassDecl->isDynamicClass())
4776 DeclareImplicitCopyAssignment(ClassDecl);
4777 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004778
David Blaikie4e4d0842012-03-11 07:00:24 +00004779 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
Richard Smithb701d3d2011-12-24 21:56:24 +00004780 ++ASTContext::NumImplicitMoveAssignmentOperators;
4781
4782 // Likewise for the move assignment operator.
4783 if (ClassDecl->isDynamicClass())
4784 DeclareImplicitMoveAssignment(ClassDecl);
4785 }
4786
Douglas Gregor4923aa22010-07-02 20:37:36 +00004787 if (!ClassDecl->hasUserDeclaredDestructor()) {
4788 ++ASTContext::NumImplicitDestructors;
4789
4790 // If we have a dynamic class, then the destructor may be virtual, so we
4791 // have to declare the destructor immediately. This ensures that, e.g., it
4792 // shows up in the right place in the vtable and that we diagnose problems
4793 // with the implicit exception specification.
4794 if (ClassDecl->isDynamicClass())
4795 DeclareImplicitDestructor(ClassDecl);
4796 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004797}
4798
Francois Pichet8387e2a2011-04-22 22:18:13 +00004799void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4800 if (!D)
4801 return;
4802
4803 int NumParamList = D->getNumTemplateParameterLists();
4804 for (int i = 0; i < NumParamList; i++) {
4805 TemplateParameterList* Params = D->getTemplateParameterList(i);
4806 for (TemplateParameterList::iterator Param = Params->begin(),
4807 ParamEnd = Params->end();
4808 Param != ParamEnd; ++Param) {
4809 NamedDecl *Named = cast<NamedDecl>(*Param);
4810 if (Named->getDeclName()) {
4811 S->AddDecl(Named);
4812 IdResolver.AddDecl(Named);
4813 }
4814 }
4815 }
4816}
4817
John McCalld226f652010-08-21 09:40:31 +00004818void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004819 if (!D)
4820 return;
4821
4822 TemplateParameterList *Params = 0;
4823 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4824 Params = Template->getTemplateParameters();
4825 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4826 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4827 Params = PartialSpec->getTemplateParameters();
4828 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004829 return;
4830
Douglas Gregor6569d682009-05-27 23:11:45 +00004831 for (TemplateParameterList::iterator Param = Params->begin(),
4832 ParamEnd = Params->end();
4833 Param != ParamEnd; ++Param) {
4834 NamedDecl *Named = cast<NamedDecl>(*Param);
4835 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004836 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004837 IdResolver.AddDecl(Named);
4838 }
4839 }
4840}
4841
John McCalld226f652010-08-21 09:40:31 +00004842void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004843 if (!RecordD) return;
4844 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004845 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004846 PushDeclContext(S, Record);
4847}
4848
John McCalld226f652010-08-21 09:40:31 +00004849void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004850 if (!RecordD) return;
4851 PopDeclContext();
4852}
4853
Douglas Gregor72b505b2008-12-16 21:30:33 +00004854/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4855/// parsing a top-level (non-nested) C++ class, and we are now
4856/// parsing those parts of the given Method declaration that could
4857/// not be parsed earlier (C++ [class.mem]p2), such as default
4858/// arguments. This action should enter the scope of the given
4859/// Method declaration as if we had just parsed the qualified method
4860/// name. However, it should not bring the parameters into scope;
4861/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004862void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004863}
4864
4865/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4866/// C++ method declaration. We're (re-)introducing the given
4867/// function parameter into scope for use in parsing later parts of
4868/// the method declaration. For example, we could see an
4869/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004870void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004871 if (!ParamD)
4872 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004873
John McCalld226f652010-08-21 09:40:31 +00004874 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004875
4876 // If this parameter has an unparsed default argument, clear it out
4877 // to make way for the parsed default argument.
4878 if (Param->hasUnparsedDefaultArg())
4879 Param->setDefaultArg(0);
4880
John McCalld226f652010-08-21 09:40:31 +00004881 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004882 if (Param->getDeclName())
4883 IdResolver.AddDecl(Param);
4884}
4885
4886/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4887/// processing the delayed method declaration for Method. The method
4888/// declaration is now considered finished. There may be a separate
4889/// ActOnStartOfFunctionDef action later (not necessarily
4890/// immediately!) for this method, if it was also defined inside the
4891/// class body.
John McCalld226f652010-08-21 09:40:31 +00004892void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004893 if (!MethodD)
4894 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004896 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004897
John McCalld226f652010-08-21 09:40:31 +00004898 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004899
4900 // Now that we have our default arguments, check the constructor
4901 // again. It could produce additional diagnostics or affect whether
4902 // the class has implicitly-declared destructors, among other
4903 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004904 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4905 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004906
4907 // Check the default arguments, which we may have added.
4908 if (!Method->isInvalidDecl())
4909 CheckCXXDefaultArguments(Method);
4910}
4911
Douglas Gregor42a552f2008-11-05 20:51:48 +00004912/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004913/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004914/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004915/// emit diagnostics and set the invalid bit to true. In any case, the type
4916/// will be updated to reflect a well-formed type for the constructor and
4917/// returned.
4918QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004919 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004920 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004921
4922 // C++ [class.ctor]p3:
4923 // A constructor shall not be virtual (10.3) or static (9.4). A
4924 // constructor can be invoked for a const, volatile or const
4925 // volatile object. A constructor shall not be declared const,
4926 // volatile, or const volatile (9.3.2).
4927 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004928 if (!D.isInvalidType())
4929 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4930 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4931 << SourceRange(D.getIdentifierLoc());
4932 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004933 }
John McCalld931b082010-08-26 03:08:43 +00004934 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004935 if (!D.isInvalidType())
4936 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4937 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4938 << SourceRange(D.getIdentifierLoc());
4939 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004940 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004941 }
Mike Stump1eb44332009-09-09 15:08:12 +00004942
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004943 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004944 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004945 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004946 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4947 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004948 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004949 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4950 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004951 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004952 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4953 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004954 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004955 }
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Douglas Gregorc938c162011-01-26 05:01:58 +00004957 // C++0x [class.ctor]p4:
4958 // A constructor shall not be declared with a ref-qualifier.
4959 if (FTI.hasRefQualifier()) {
4960 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4961 << FTI.RefQualifierIsLValueRef
4962 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4963 D.setInvalidType();
4964 }
4965
Douglas Gregor42a552f2008-11-05 20:51:48 +00004966 // Rebuild the function type "R" without any type qualifiers (in
4967 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004968 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004969 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004970 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4971 return R;
4972
4973 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4974 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004975 EPI.RefQualifier = RQ_None;
4976
Chris Lattner65401802009-04-25 08:28:21 +00004977 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004978 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004979}
4980
Douglas Gregor72b505b2008-12-16 21:30:33 +00004981/// CheckConstructor - Checks a fully-formed constructor for
4982/// well-formedness, issuing any diagnostics required. Returns true if
4983/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004984void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004985 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004986 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4987 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004988 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004989
4990 // C++ [class.copy]p3:
4991 // A declaration of a constructor for a class X is ill-formed if
4992 // its first parameter is of type (optionally cv-qualified) X and
4993 // either there are no other parameters or else all other
4994 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004995 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004996 ((Constructor->getNumParams() == 1) ||
4997 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004998 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4999 Constructor->getTemplateSpecializationKind()
5000 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005001 QualType ParamType = Constructor->getParamDecl(0)->getType();
5002 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5003 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005004 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005005 const char *ConstRef
5006 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5007 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005008 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005009 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005010
5011 // FIXME: Rather that making the constructor invalid, we should endeavor
5012 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005013 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005014 }
5015 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005016}
5017
John McCall15442822010-08-04 01:04:25 +00005018/// CheckDestructor - Checks a fully-formed destructor definition for
5019/// well-formedness, issuing any diagnostics required. Returns true
5020/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005021bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005022 CXXRecordDecl *RD = Destructor->getParent();
5023
5024 if (Destructor->isVirtual()) {
5025 SourceLocation Loc;
5026
5027 if (!Destructor->isImplicit())
5028 Loc = Destructor->getLocation();
5029 else
5030 Loc = RD->getLocation();
5031
5032 // If we have a virtual destructor, look up the deallocation function
5033 FunctionDecl *OperatorDelete = 0;
5034 DeclarationName Name =
5035 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005036 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005037 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005038
Eli Friedman5f2987c2012-02-02 03:46:19 +00005039 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005040
5041 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005042 }
Anders Carlsson37909802009-11-30 21:24:50 +00005043
5044 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005045}
5046
Mike Stump1eb44332009-09-09 15:08:12 +00005047static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005048FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5049 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5050 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005051 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005052}
5053
Douglas Gregor42a552f2008-11-05 20:51:48 +00005054/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5055/// the well-formednes of the destructor declarator @p D with type @p
5056/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005057/// emit diagnostics and set the declarator to invalid. Even if this happens,
5058/// will be updated to reflect a well-formed type for the destructor and
5059/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005060QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005061 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005062 // C++ [class.dtor]p1:
5063 // [...] A typedef-name that names a class is a class-name
5064 // (7.1.3); however, a typedef-name that names a class shall not
5065 // be used as the identifier in the declarator for a destructor
5066 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005067 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005068 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005069 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005070 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005071 else if (const TemplateSpecializationType *TST =
5072 DeclaratorType->getAs<TemplateSpecializationType>())
5073 if (TST->isTypeAlias())
5074 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5075 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005076
5077 // C++ [class.dtor]p2:
5078 // A destructor is used to destroy objects of its class type. A
5079 // destructor takes no parameters, and no return type can be
5080 // specified for it (not even void). The address of a destructor
5081 // shall not be taken. A destructor shall not be static. A
5082 // destructor can be invoked for a const, volatile or const
5083 // volatile object. A destructor shall not be declared const,
5084 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005085 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005086 if (!D.isInvalidType())
5087 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5088 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005089 << SourceRange(D.getIdentifierLoc())
5090 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5091
John McCalld931b082010-08-26 03:08:43 +00005092 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005093 }
Chris Lattner65401802009-04-25 08:28:21 +00005094 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005095 // Destructors don't have return types, but the parser will
5096 // happily parse something like:
5097 //
5098 // class X {
5099 // float ~X();
5100 // };
5101 //
5102 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005103 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5104 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5105 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005106 }
Mike Stump1eb44332009-09-09 15:08:12 +00005107
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005108 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005109 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005110 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5112 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005113 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005114 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5115 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005116 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005117 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5118 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005119 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005120 }
5121
Douglas Gregorc938c162011-01-26 05:01:58 +00005122 // C++0x [class.dtor]p2:
5123 // A destructor shall not be declared with a ref-qualifier.
5124 if (FTI.hasRefQualifier()) {
5125 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5126 << FTI.RefQualifierIsLValueRef
5127 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5128 D.setInvalidType();
5129 }
5130
Douglas Gregor42a552f2008-11-05 20:51:48 +00005131 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005132 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005133 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5134
5135 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005136 FTI.freeArgs();
5137 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005138 }
5139
Mike Stump1eb44332009-09-09 15:08:12 +00005140 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005141 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005142 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005143 D.setInvalidType();
5144 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005145
5146 // Rebuild the function type "R" without any type qualifiers or
5147 // parameters (in case any of the errors above fired) and with
5148 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005149 // types.
John McCalle23cf432010-12-14 08:05:40 +00005150 if (!D.isInvalidType())
5151 return R;
5152
Douglas Gregord92ec472010-07-01 05:10:53 +00005153 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005154 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5155 EPI.Variadic = false;
5156 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005157 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005158 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005159}
5160
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005161/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5162/// well-formednes of the conversion function declarator @p D with
5163/// type @p R. If there are any errors in the declarator, this routine
5164/// will emit diagnostics and return true. Otherwise, it will return
5165/// false. Either way, the type @p R will be updated to reflect a
5166/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005167void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005168 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005169 // C++ [class.conv.fct]p1:
5170 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005171 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005172 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005173 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005174 if (!D.isInvalidType())
5175 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5176 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5177 << SourceRange(D.getIdentifierLoc());
5178 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005179 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005180 }
John McCalla3f81372010-04-13 00:04:31 +00005181
5182 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5183
Chris Lattner6e475012009-04-25 08:35:12 +00005184 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005185 // Conversion functions don't have return types, but the parser will
5186 // happily parse something like:
5187 //
5188 // class X {
5189 // float operator bool();
5190 // };
5191 //
5192 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005193 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5194 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5195 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005196 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005197 }
5198
John McCalla3f81372010-04-13 00:04:31 +00005199 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5200
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005201 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005202 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005203 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5204
5205 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005206 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005207 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005208 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005209 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005210 D.setInvalidType();
5211 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005212
John McCalla3f81372010-04-13 00:04:31 +00005213 // Diagnose "&operator bool()" and other such nonsense. This
5214 // is actually a gcc extension which we don't support.
5215 if (Proto->getResultType() != ConvType) {
5216 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5217 << Proto->getResultType();
5218 D.setInvalidType();
5219 ConvType = Proto->getResultType();
5220 }
5221
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005222 // C++ [class.conv.fct]p4:
5223 // The conversion-type-id shall not represent a function type nor
5224 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005225 if (ConvType->isArrayType()) {
5226 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5227 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005228 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005229 } else if (ConvType->isFunctionType()) {
5230 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5231 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005232 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005233 }
5234
5235 // Rebuild the function type "R" without any parameters (in case any
5236 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005237 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005238 if (D.isInvalidType())
5239 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005240
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005241 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005242 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005243 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005244 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005245 diag::warn_cxx98_compat_explicit_conversion_functions :
5246 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005247 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005248}
5249
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005250/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5251/// the declaration of the given C++ conversion function. This routine
5252/// is responsible for recording the conversion function in the C++
5253/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005254Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005255 assert(Conversion && "Expected to receive a conversion function declaration");
5256
Douglas Gregor9d350972008-12-12 08:25:50 +00005257 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005258
5259 // Make sure we aren't redeclaring the conversion function.
5260 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005261
5262 // C++ [class.conv.fct]p1:
5263 // [...] A conversion function is never used to convert a
5264 // (possibly cv-qualified) object to the (possibly cv-qualified)
5265 // same object type (or a reference to it), to a (possibly
5266 // cv-qualified) base class of that type (or a reference to it),
5267 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005268 // FIXME: Suppress this warning if the conversion function ends up being a
5269 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005270 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005271 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005272 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005273 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005274 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5275 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005276 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005277 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005278 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5279 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005280 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005281 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005282 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005283 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005284 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005285 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005286 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005287 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005288 }
5289
Douglas Gregore80622f2010-09-29 04:25:11 +00005290 if (FunctionTemplateDecl *ConversionTemplate
5291 = Conversion->getDescribedFunctionTemplate())
5292 return ConversionTemplate;
5293
John McCalld226f652010-08-21 09:40:31 +00005294 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005295}
5296
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005297//===----------------------------------------------------------------------===//
5298// Namespace Handling
5299//===----------------------------------------------------------------------===//
5300
John McCallea318642010-08-26 09:15:37 +00005301
5302
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005303/// ActOnStartNamespaceDef - This is called at the start of a namespace
5304/// definition.
John McCalld226f652010-08-21 09:40:31 +00005305Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005306 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005307 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005308 SourceLocation IdentLoc,
5309 IdentifierInfo *II,
5310 SourceLocation LBrace,
5311 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005312 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5313 // For anonymous namespace, take the location of the left brace.
5314 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005315 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005316 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005317 bool IsStd = false;
5318 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005319 Scope *DeclRegionScope = NamespcScope->getParent();
5320
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005321 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005322 if (II) {
5323 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005324 // The identifier in an original-namespace-definition shall not
5325 // have been previously defined in the declarative region in
5326 // which the original-namespace-definition appears. The
5327 // identifier in an original-namespace-definition is the name of
5328 // the namespace. Subsequently in that declarative region, it is
5329 // treated as an original-namespace-name.
5330 //
5331 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005332 // look through using directives, just look for any ordinary names.
5333
5334 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005335 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5336 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005337 NamedDecl *PrevDecl = 0;
5338 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005339 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005340 R.first != R.second; ++R.first) {
5341 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5342 PrevDecl = *R.first;
5343 break;
5344 }
5345 }
5346
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5348
5349 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005350 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005351 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005352 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005353 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005354 // The user probably just forgot the 'inline', so suggest that it
5355 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005356 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005357 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5358 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005359 Diag(Loc, diag::err_inline_namespace_mismatch)
5360 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005361 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005362 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5363
5364 IsInline = PrevNS->isInline();
5365 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005366 } else if (PrevDecl) {
5367 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005368 Diag(Loc, diag::err_redefinition_different_kind)
5369 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005370 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005371 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005372 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005373 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005374 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005375 // This is the first "real" definition of the namespace "std", so update
5376 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005377 PrevNS = getStdNamespace();
5378 IsStd = true;
5379 AddToKnown = !IsInline;
5380 } else {
5381 // We've seen this namespace for the first time.
5382 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005383 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005384 } else {
John McCall9aeed322009-10-01 00:25:31 +00005385 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005386
5387 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005388 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005389 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005390 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005391 } else {
5392 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005393 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005394 }
5395
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005396 if (PrevNS && IsInline != PrevNS->isInline()) {
5397 // inline-ness must match
5398 Diag(Loc, diag::err_inline_namespace_mismatch)
5399 << IsInline;
5400 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005401
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005402 // Recover by ignoring the new namespace's inline status.
5403 IsInline = PrevNS->isInline();
5404 }
5405 }
5406
5407 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5408 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005409 if (IsInvalid)
5410 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005411
5412 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005413
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005414 // FIXME: Should we be merging attributes?
5415 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005416 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005417
5418 if (IsStd)
5419 StdNamespace = Namespc;
5420 if (AddToKnown)
5421 KnownNamespaces[Namespc] = false;
5422
5423 if (II) {
5424 PushOnScopeChains(Namespc, DeclRegionScope);
5425 } else {
5426 // Link the anonymous namespace into its parent.
5427 DeclContext *Parent = CurContext->getRedeclContext();
5428 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5429 TU->setAnonymousNamespace(Namespc);
5430 } else {
5431 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005432 }
John McCall9aeed322009-10-01 00:25:31 +00005433
Douglas Gregora4181472010-03-24 00:46:35 +00005434 CurContext->addDecl(Namespc);
5435
John McCall9aeed322009-10-01 00:25:31 +00005436 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5437 // behaves as if it were replaced by
5438 // namespace unique { /* empty body */ }
5439 // using namespace unique;
5440 // namespace unique { namespace-body }
5441 // where all occurrences of 'unique' in a translation unit are
5442 // replaced by the same identifier and this identifier differs
5443 // from all other identifiers in the entire program.
5444
5445 // We just create the namespace with an empty name and then add an
5446 // implicit using declaration, just like the standard suggests.
5447 //
5448 // CodeGen enforces the "universally unique" aspect by giving all
5449 // declarations semantically contained within an anonymous
5450 // namespace internal linkage.
5451
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005452 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005453 UsingDirectiveDecl* UD
5454 = UsingDirectiveDecl::Create(Context, CurContext,
5455 /* 'using' */ LBrace,
5456 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005457 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005458 /* identifier */ SourceLocation(),
5459 Namespc,
5460 /* Ancestor */ CurContext);
5461 UD->setImplicit();
5462 CurContext->addDecl(UD);
5463 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005464 }
5465
5466 // Although we could have an invalid decl (i.e. the namespace name is a
5467 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005468 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5469 // for the namespace has the declarations that showed up in that particular
5470 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005471 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005472 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005473}
5474
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005475/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5476/// is a namespace alias, returns the namespace it points to.
5477static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5478 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5479 return AD->getNamespace();
5480 return dyn_cast_or_null<NamespaceDecl>(D);
5481}
5482
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005483/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5484/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005485void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005486 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5487 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005488 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005489 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005490 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005491 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005492}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005493
John McCall384aff82010-08-25 07:42:41 +00005494CXXRecordDecl *Sema::getStdBadAlloc() const {
5495 return cast_or_null<CXXRecordDecl>(
5496 StdBadAlloc.get(Context.getExternalSource()));
5497}
5498
5499NamespaceDecl *Sema::getStdNamespace() const {
5500 return cast_or_null<NamespaceDecl>(
5501 StdNamespace.get(Context.getExternalSource()));
5502}
5503
Douglas Gregor66992202010-06-29 17:53:46 +00005504/// \brief Retrieve the special "std" namespace, which may require us to
5505/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005506NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005507 if (!StdNamespace) {
5508 // The "std" namespace has not yet been defined, so build one implicitly.
5509 StdNamespace = NamespaceDecl::Create(Context,
5510 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005511 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005512 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005513 &PP.getIdentifierTable().get("std"),
5514 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005515 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005516 }
5517
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005518 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005519}
5520
Sebastian Redl395e04d2012-01-17 22:49:33 +00005521bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005522 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005523 "Looking for std::initializer_list outside of C++.");
5524
5525 // We're looking for implicit instantiations of
5526 // template <typename E> class std::initializer_list.
5527
5528 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5529 return false;
5530
Sebastian Redl84760e32012-01-17 22:49:58 +00005531 ClassTemplateDecl *Template = 0;
5532 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005533
Sebastian Redl84760e32012-01-17 22:49:58 +00005534 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005535
Sebastian Redl84760e32012-01-17 22:49:58 +00005536 ClassTemplateSpecializationDecl *Specialization =
5537 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5538 if (!Specialization)
5539 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005540
Sebastian Redl84760e32012-01-17 22:49:58 +00005541 Template = Specialization->getSpecializedTemplate();
5542 Arguments = Specialization->getTemplateArgs().data();
5543 } else if (const TemplateSpecializationType *TST =
5544 Ty->getAs<TemplateSpecializationType>()) {
5545 Template = dyn_cast_or_null<ClassTemplateDecl>(
5546 TST->getTemplateName().getAsTemplateDecl());
5547 Arguments = TST->getArgs();
5548 }
5549 if (!Template)
5550 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005551
5552 if (!StdInitializerList) {
5553 // Haven't recognized std::initializer_list yet, maybe this is it.
5554 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5555 if (TemplateClass->getIdentifier() !=
5556 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005557 !getStdNamespace()->InEnclosingNamespaceSetOf(
5558 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005559 return false;
5560 // This is a template called std::initializer_list, but is it the right
5561 // template?
5562 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005563 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005564 return false;
5565 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5566 return false;
5567
5568 // It's the right template.
5569 StdInitializerList = Template;
5570 }
5571
5572 if (Template != StdInitializerList)
5573 return false;
5574
5575 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005576 if (Element)
5577 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005578 return true;
5579}
5580
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005581static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5582 NamespaceDecl *Std = S.getStdNamespace();
5583 if (!Std) {
5584 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5585 return 0;
5586 }
5587
5588 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5589 Loc, Sema::LookupOrdinaryName);
5590 if (!S.LookupQualifiedName(Result, Std)) {
5591 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5592 return 0;
5593 }
5594 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5595 if (!Template) {
5596 Result.suppressDiagnostics();
5597 // We found something weird. Complain about the first thing we found.
5598 NamedDecl *Found = *Result.begin();
5599 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5600 return 0;
5601 }
5602
5603 // We found some template called std::initializer_list. Now verify that it's
5604 // correct.
5605 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005606 if (Params->getMinRequiredArguments() != 1 ||
5607 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005608 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5609 return 0;
5610 }
5611
5612 return Template;
5613}
5614
5615QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5616 if (!StdInitializerList) {
5617 StdInitializerList = LookupStdInitializerList(*this, Loc);
5618 if (!StdInitializerList)
5619 return QualType();
5620 }
5621
5622 TemplateArgumentListInfo Args(Loc, Loc);
5623 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5624 Context.getTrivialTypeSourceInfo(Element,
5625 Loc)));
5626 return Context.getCanonicalType(
5627 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5628}
5629
Sebastian Redl98d36062012-01-17 22:50:14 +00005630bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5631 // C++ [dcl.init.list]p2:
5632 // A constructor is an initializer-list constructor if its first parameter
5633 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5634 // std::initializer_list<E> for some type E, and either there are no other
5635 // parameters or else all other parameters have default arguments.
5636 if (Ctor->getNumParams() < 1 ||
5637 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5638 return false;
5639
5640 QualType ArgType = Ctor->getParamDecl(0)->getType();
5641 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5642 ArgType = RT->getPointeeType().getUnqualifiedType();
5643
5644 return isStdInitializerList(ArgType, 0);
5645}
5646
Douglas Gregor9172aa62011-03-26 22:25:30 +00005647/// \brief Determine whether a using statement is in a context where it will be
5648/// apply in all contexts.
5649static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5650 switch (CurContext->getDeclKind()) {
5651 case Decl::TranslationUnit:
5652 return true;
5653 case Decl::LinkageSpec:
5654 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5655 default:
5656 return false;
5657 }
5658}
5659
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005660namespace {
5661
5662// Callback to only accept typo corrections that are namespaces.
5663class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5664 public:
5665 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5666 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5667 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5668 }
5669 return false;
5670 }
5671};
5672
5673}
5674
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005675static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5676 CXXScopeSpec &SS,
5677 SourceLocation IdentLoc,
5678 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005679 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005680 R.clear();
5681 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005682 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005683 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005684 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5685 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005686 if (DeclContext *DC = S.computeDeclContext(SS, false))
5687 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5688 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5689 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5690 else
5691 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5692 << Ident << CorrectedQuotedStr
5693 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005694
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005695 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5696 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005697
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005698 Ident = Corrected.getCorrectionAsIdentifierInfo();
5699 R.addDecl(Corrected.getCorrectionDecl());
5700 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005701 }
5702 return false;
5703}
5704
John McCalld226f652010-08-21 09:40:31 +00005705Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005706 SourceLocation UsingLoc,
5707 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005708 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005709 SourceLocation IdentLoc,
5710 IdentifierInfo *NamespcName,
5711 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005712 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5713 assert(NamespcName && "Invalid NamespcName.");
5714 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005715
5716 // This can only happen along a recovery path.
5717 while (S->getFlags() & Scope::TemplateParamScope)
5718 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005719 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005720
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005721 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005722 NestedNameSpecifier *Qualifier = 0;
5723 if (SS.isSet())
5724 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5725
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005726 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005727 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5728 LookupParsedName(R, S, &SS);
5729 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005730 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005731
Douglas Gregor66992202010-06-29 17:53:46 +00005732 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005733 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005734 // Allow "using namespace std;" or "using namespace ::std;" even if
5735 // "std" hasn't been defined yet, for GCC compatibility.
5736 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5737 NamespcName->isStr("std")) {
5738 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005739 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005740 R.resolveKind();
5741 }
5742 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005743 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005744 }
5745
John McCallf36e02d2009-10-09 21:13:30 +00005746 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005747 NamedDecl *Named = R.getFoundDecl();
5748 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5749 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005750 // C++ [namespace.udir]p1:
5751 // A using-directive specifies that the names in the nominated
5752 // namespace can be used in the scope in which the
5753 // using-directive appears after the using-directive. During
5754 // unqualified name lookup (3.4.1), the names appear as if they
5755 // were declared in the nearest enclosing namespace which
5756 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005757 // namespace. [Note: in this context, "contains" means "contains
5758 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005759
5760 // Find enclosing context containing both using-directive and
5761 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005762 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005763 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5764 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5765 CommonAncestor = CommonAncestor->getParent();
5766
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005767 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005768 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005769 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005770
Douglas Gregor9172aa62011-03-26 22:25:30 +00005771 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005772 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005773 Diag(IdentLoc, diag::warn_using_directive_in_header);
5774 }
5775
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005776 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005777 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005778 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005779 }
5780
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005781 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005782 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005783}
5784
5785void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005786 // If the scope has an associated entity and the using directive is at
5787 // namespace or translation unit scope, add the UsingDirectiveDecl into
5788 // its lookup structure so qualified name lookup can find it.
5789 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5790 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005791 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005792 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005793 // Otherwise, it is at block sope. The using-directives will affect lookup
5794 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005795 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005796}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005797
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005798
John McCalld226f652010-08-21 09:40:31 +00005799Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005800 AccessSpecifier AS,
5801 bool HasUsingKeyword,
5802 SourceLocation UsingLoc,
5803 CXXScopeSpec &SS,
5804 UnqualifiedId &Name,
5805 AttributeList *AttrList,
5806 bool IsTypeName,
5807 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005808 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Douglas Gregor12c118a2009-11-04 16:30:06 +00005810 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005811 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005812 case UnqualifiedId::IK_Identifier:
5813 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005814 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005815 case UnqualifiedId::IK_ConversionFunctionId:
5816 break;
5817
5818 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005819 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005820 // C++0x inherited constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005821 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005822 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005823 diag::warn_cxx98_compat_using_decl_constructor :
5824 diag::err_using_decl_constructor)
5825 << SS.getRange();
5826
David Blaikie4e4d0842012-03-11 07:00:24 +00005827 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005828
John McCalld226f652010-08-21 09:40:31 +00005829 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005830
5831 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005832 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005833 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005834 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005835
5836 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005837 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005838 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005839 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005840 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005841
5842 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5843 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005844 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005845 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005846
John McCall60fa3cf2009-12-11 02:10:03 +00005847 // Warn about using declarations.
5848 // TODO: store that the declaration was written without 'using' and
5849 // talk about access decls instead of using decls in the
5850 // diagnostics.
5851 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005852 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005853
5854 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005855 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005856 }
5857
Douglas Gregor56c04582010-12-16 00:46:58 +00005858 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5859 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5860 return 0;
5861
John McCall9488ea12009-11-17 05:59:44 +00005862 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005863 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005864 /* IsInstantiation */ false,
5865 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005866 if (UD)
5867 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005868
John McCalld226f652010-08-21 09:40:31 +00005869 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005870}
5871
Douglas Gregor09acc982010-07-07 23:08:52 +00005872/// \brief Determine whether a using declaration considers the given
5873/// declarations as "equivalent", e.g., if they are redeclarations of
5874/// the same entity or are both typedefs of the same type.
5875static bool
5876IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5877 bool &SuppressRedeclaration) {
5878 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5879 SuppressRedeclaration = false;
5880 return true;
5881 }
5882
Richard Smith162e1c12011-04-15 14:24:37 +00005883 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5884 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005885 SuppressRedeclaration = true;
5886 return Context.hasSameType(TD1->getUnderlyingType(),
5887 TD2->getUnderlyingType());
5888 }
5889
5890 return false;
5891}
5892
5893
John McCall9f54ad42009-12-10 09:41:52 +00005894/// Determines whether to create a using shadow decl for a particular
5895/// decl, given the set of decls existing prior to this using lookup.
5896bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5897 const LookupResult &Previous) {
5898 // Diagnose finding a decl which is not from a base class of the
5899 // current class. We do this now because there are cases where this
5900 // function will silently decide not to build a shadow decl, which
5901 // will pre-empt further diagnostics.
5902 //
5903 // We don't need to do this in C++0x because we do the check once on
5904 // the qualifier.
5905 //
5906 // FIXME: diagnose the following if we care enough:
5907 // struct A { int foo; };
5908 // struct B : A { using A::foo; };
5909 // template <class T> struct C : A {};
5910 // template <class T> struct D : C<T> { using B::foo; } // <---
5911 // This is invalid (during instantiation) in C++03 because B::foo
5912 // resolves to the using decl in B, which is not a base class of D<T>.
5913 // We can't diagnose it immediately because C<T> is an unknown
5914 // specialization. The UsingShadowDecl in D<T> then points directly
5915 // to A::foo, which will look well-formed when we instantiate.
5916 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005917 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005918 DeclContext *OrigDC = Orig->getDeclContext();
5919
5920 // Handle enums and anonymous structs.
5921 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5922 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5923 while (OrigRec->isAnonymousStructOrUnion())
5924 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5925
5926 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5927 if (OrigDC == CurContext) {
5928 Diag(Using->getLocation(),
5929 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005930 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005931 Diag(Orig->getLocation(), diag::note_using_decl_target);
5932 return true;
5933 }
5934
Douglas Gregordc355712011-02-25 00:36:19 +00005935 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005936 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005937 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005938 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005939 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005940 Diag(Orig->getLocation(), diag::note_using_decl_target);
5941 return true;
5942 }
5943 }
5944
5945 if (Previous.empty()) return false;
5946
5947 NamedDecl *Target = Orig;
5948 if (isa<UsingShadowDecl>(Target))
5949 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5950
John McCalld7533ec2009-12-11 02:33:26 +00005951 // If the target happens to be one of the previous declarations, we
5952 // don't have a conflict.
5953 //
5954 // FIXME: but we might be increasing its access, in which case we
5955 // should redeclare it.
5956 NamedDecl *NonTag = 0, *Tag = 0;
5957 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5958 I != E; ++I) {
5959 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005960 bool Result;
5961 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5962 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005963
5964 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5965 }
5966
John McCall9f54ad42009-12-10 09:41:52 +00005967 if (Target->isFunctionOrFunctionTemplate()) {
5968 FunctionDecl *FD;
5969 if (isa<FunctionTemplateDecl>(Target))
5970 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5971 else
5972 FD = cast<FunctionDecl>(Target);
5973
5974 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005975 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005976 case Ovl_Overload:
5977 return false;
5978
5979 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005980 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005981 break;
5982
5983 // We found a decl with the exact signature.
5984 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005985 // If we're in a record, we want to hide the target, so we
5986 // return true (without a diagnostic) to tell the caller not to
5987 // build a shadow decl.
5988 if (CurContext->isRecord())
5989 return true;
5990
5991 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005992 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005993 break;
5994 }
5995
5996 Diag(Target->getLocation(), diag::note_using_decl_target);
5997 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5998 return true;
5999 }
6000
6001 // Target is not a function.
6002
John McCall9f54ad42009-12-10 09:41:52 +00006003 if (isa<TagDecl>(Target)) {
6004 // No conflict between a tag and a non-tag.
6005 if (!Tag) return false;
6006
John McCall41ce66f2009-12-10 19:51:03 +00006007 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006008 Diag(Target->getLocation(), diag::note_using_decl_target);
6009 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6010 return true;
6011 }
6012
6013 // No conflict between a tag and a non-tag.
6014 if (!NonTag) return false;
6015
John McCall41ce66f2009-12-10 19:51:03 +00006016 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006017 Diag(Target->getLocation(), diag::note_using_decl_target);
6018 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6019 return true;
6020}
6021
John McCall9488ea12009-11-17 05:59:44 +00006022/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006023UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006024 UsingDecl *UD,
6025 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006026
6027 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006028 NamedDecl *Target = Orig;
6029 if (isa<UsingShadowDecl>(Target)) {
6030 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6031 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006032 }
6033
6034 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006035 = UsingShadowDecl::Create(Context, CurContext,
6036 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006037 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006038
6039 Shadow->setAccess(UD->getAccess());
6040 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6041 Shadow->setInvalidDecl();
6042
John McCall9488ea12009-11-17 05:59:44 +00006043 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006044 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006045 else
John McCall604e7f12009-12-08 07:46:18 +00006046 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006047
John McCall604e7f12009-12-08 07:46:18 +00006048
John McCall9f54ad42009-12-10 09:41:52 +00006049 return Shadow;
6050}
John McCall604e7f12009-12-08 07:46:18 +00006051
John McCall9f54ad42009-12-10 09:41:52 +00006052/// Hides a using shadow declaration. This is required by the current
6053/// using-decl implementation when a resolvable using declaration in a
6054/// class is followed by a declaration which would hide or override
6055/// one or more of the using decl's targets; for example:
6056///
6057/// struct Base { void foo(int); };
6058/// struct Derived : Base {
6059/// using Base::foo;
6060/// void foo(int);
6061/// };
6062///
6063/// The governing language is C++03 [namespace.udecl]p12:
6064///
6065/// When a using-declaration brings names from a base class into a
6066/// derived class scope, member functions in the derived class
6067/// override and/or hide member functions with the same name and
6068/// parameter types in a base class (rather than conflicting).
6069///
6070/// There are two ways to implement this:
6071/// (1) optimistically create shadow decls when they're not hidden
6072/// by existing declarations, or
6073/// (2) don't create any shadow decls (or at least don't make them
6074/// visible) until we've fully parsed/instantiated the class.
6075/// The problem with (1) is that we might have to retroactively remove
6076/// a shadow decl, which requires several O(n) operations because the
6077/// decl structures are (very reasonably) not designed for removal.
6078/// (2) avoids this but is very fiddly and phase-dependent.
6079void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006080 if (Shadow->getDeclName().getNameKind() ==
6081 DeclarationName::CXXConversionFunctionName)
6082 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6083
John McCall9f54ad42009-12-10 09:41:52 +00006084 // Remove it from the DeclContext...
6085 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006086
John McCall9f54ad42009-12-10 09:41:52 +00006087 // ...and the scope, if applicable...
6088 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006089 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006090 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006091 }
6092
John McCall9f54ad42009-12-10 09:41:52 +00006093 // ...and the using decl.
6094 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6095
6096 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006097 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006098}
6099
John McCall7ba107a2009-11-18 02:36:19 +00006100/// Builds a using declaration.
6101///
6102/// \param IsInstantiation - Whether this call arises from an
6103/// instantiation of an unresolved using declaration. We treat
6104/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006105NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6106 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006107 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006108 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006109 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006110 bool IsInstantiation,
6111 bool IsTypeName,
6112 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006113 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006114 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006115 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006116
Anders Carlsson550b14b2009-08-28 05:49:21 +00006117 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006118
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006119 if (SS.isEmpty()) {
6120 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006121 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006122 }
Mike Stump1eb44332009-09-09 15:08:12 +00006123
John McCall9f54ad42009-12-10 09:41:52 +00006124 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006125 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006126 ForRedeclaration);
6127 Previous.setHideTags(false);
6128 if (S) {
6129 LookupName(Previous, S);
6130
6131 // It is really dumb that we have to do this.
6132 LookupResult::Filter F = Previous.makeFilter();
6133 while (F.hasNext()) {
6134 NamedDecl *D = F.next();
6135 if (!isDeclInScope(D, CurContext, S))
6136 F.erase();
6137 }
6138 F.done();
6139 } else {
6140 assert(IsInstantiation && "no scope in non-instantiation");
6141 assert(CurContext->isRecord() && "scope not record in instantiation");
6142 LookupQualifiedName(Previous, CurContext);
6143 }
6144
John McCall9f54ad42009-12-10 09:41:52 +00006145 // Check for invalid redeclarations.
6146 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6147 return 0;
6148
6149 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006150 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6151 return 0;
6152
John McCallaf8e6ed2009-11-12 03:15:40 +00006153 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006154 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006155 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006156 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006157 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006158 // FIXME: not all declaration name kinds are legal here
6159 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6160 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006161 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006162 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006163 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006164 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6165 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006166 }
John McCalled976492009-12-04 22:46:56 +00006167 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006168 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6169 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006170 }
John McCalled976492009-12-04 22:46:56 +00006171 D->setAccess(AS);
6172 CurContext->addDecl(D);
6173
6174 if (!LookupContext) return D;
6175 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006176
John McCall77bb1aa2010-05-01 00:40:08 +00006177 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006178 UD->setInvalidDecl();
6179 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006180 }
6181
Sebastian Redlf677ea32011-02-05 19:23:19 +00006182 // Constructor inheriting using decls get special treatment.
6183 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006184 if (CheckInheritedConstructorUsingDecl(UD))
6185 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006186 return UD;
6187 }
6188
6189 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006190
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006191 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006192
John McCall604e7f12009-12-08 07:46:18 +00006193 // Unlike most lookups, we don't always want to hide tag
6194 // declarations: tag names are visible through the using declaration
6195 // even if hidden by ordinary names, *except* in a dependent context
6196 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006197 if (!IsInstantiation)
6198 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006199
John McCalla24dc2e2009-11-17 02:14:36 +00006200 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006201
John McCallf36e02d2009-10-09 21:13:30 +00006202 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006203 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006204 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006205 UD->setInvalidDecl();
6206 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006207 }
6208
John McCalled976492009-12-04 22:46:56 +00006209 if (R.isAmbiguous()) {
6210 UD->setInvalidDecl();
6211 return UD;
6212 }
Mike Stump1eb44332009-09-09 15:08:12 +00006213
John McCall7ba107a2009-11-18 02:36:19 +00006214 if (IsTypeName) {
6215 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006216 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006217 Diag(IdentLoc, diag::err_using_typename_non_type);
6218 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6219 Diag((*I)->getUnderlyingDecl()->getLocation(),
6220 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006221 UD->setInvalidDecl();
6222 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006223 }
6224 } else {
6225 // If we asked for a non-typename and we got a type, error out,
6226 // but only if this is an instantiation of an unresolved using
6227 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006228 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006229 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6230 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006231 UD->setInvalidDecl();
6232 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006233 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006234 }
6235
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006236 // C++0x N2914 [namespace.udecl]p6:
6237 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006238 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006239 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6240 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006241 UD->setInvalidDecl();
6242 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006243 }
Mike Stump1eb44332009-09-09 15:08:12 +00006244
John McCall9f54ad42009-12-10 09:41:52 +00006245 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6246 if (!CheckUsingShadowDecl(UD, *I, Previous))
6247 BuildUsingShadowDecl(S, UD, *I);
6248 }
John McCall9488ea12009-11-17 05:59:44 +00006249
6250 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006251}
6252
Sebastian Redlf677ea32011-02-05 19:23:19 +00006253/// Additional checks for a using declaration referring to a constructor name.
6254bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6255 if (UD->isTypeName()) {
6256 // FIXME: Cannot specify typename when specifying constructor
6257 return true;
6258 }
6259
Douglas Gregordc355712011-02-25 00:36:19 +00006260 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006261 assert(SourceType &&
6262 "Using decl naming constructor doesn't have type in scope spec.");
6263 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6264
6265 // Check whether the named type is a direct base class.
6266 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6267 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6268 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6269 BaseIt != BaseE; ++BaseIt) {
6270 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6271 if (CanonicalSourceType == BaseType)
6272 break;
6273 }
6274
6275 if (BaseIt == BaseE) {
6276 // Did not find SourceType in the bases.
6277 Diag(UD->getUsingLocation(),
6278 diag::err_using_decl_constructor_not_in_direct_base)
6279 << UD->getNameInfo().getSourceRange()
6280 << QualType(SourceType, 0) << TargetClass;
6281 return true;
6282 }
6283
6284 BaseIt->setInheritConstructors();
6285
6286 return false;
6287}
6288
John McCall9f54ad42009-12-10 09:41:52 +00006289/// Checks that the given using declaration is not an invalid
6290/// redeclaration. Note that this is checking only for the using decl
6291/// itself, not for any ill-formedness among the UsingShadowDecls.
6292bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6293 bool isTypeName,
6294 const CXXScopeSpec &SS,
6295 SourceLocation NameLoc,
6296 const LookupResult &Prev) {
6297 // C++03 [namespace.udecl]p8:
6298 // C++0x [namespace.udecl]p10:
6299 // A using-declaration is a declaration and can therefore be used
6300 // repeatedly where (and only where) multiple declarations are
6301 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006302 //
John McCall8a726212010-11-29 18:01:58 +00006303 // That's in non-member contexts.
6304 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006305 return false;
6306
6307 NestedNameSpecifier *Qual
6308 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6309
6310 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6311 NamedDecl *D = *I;
6312
6313 bool DTypename;
6314 NestedNameSpecifier *DQual;
6315 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6316 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006317 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006318 } else if (UnresolvedUsingValueDecl *UD
6319 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6320 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006321 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006322 } else if (UnresolvedUsingTypenameDecl *UD
6323 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6324 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006325 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006326 } else continue;
6327
6328 // using decls differ if one says 'typename' and the other doesn't.
6329 // FIXME: non-dependent using decls?
6330 if (isTypeName != DTypename) continue;
6331
6332 // using decls differ if they name different scopes (but note that
6333 // template instantiation can cause this check to trigger when it
6334 // didn't before instantiation).
6335 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6336 Context.getCanonicalNestedNameSpecifier(DQual))
6337 continue;
6338
6339 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006340 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006341 return true;
6342 }
6343
6344 return false;
6345}
6346
John McCall604e7f12009-12-08 07:46:18 +00006347
John McCalled976492009-12-04 22:46:56 +00006348/// Checks that the given nested-name qualifier used in a using decl
6349/// in the current context is appropriately related to the current
6350/// scope. If an error is found, diagnoses it and returns true.
6351bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6352 const CXXScopeSpec &SS,
6353 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006354 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006355
John McCall604e7f12009-12-08 07:46:18 +00006356 if (!CurContext->isRecord()) {
6357 // C++03 [namespace.udecl]p3:
6358 // C++0x [namespace.udecl]p8:
6359 // A using-declaration for a class member shall be a member-declaration.
6360
6361 // If we weren't able to compute a valid scope, it must be a
6362 // dependent class scope.
6363 if (!NamedContext || NamedContext->isRecord()) {
6364 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6365 << SS.getRange();
6366 return true;
6367 }
6368
6369 // Otherwise, everything is known to be fine.
6370 return false;
6371 }
6372
6373 // The current scope is a record.
6374
6375 // If the named context is dependent, we can't decide much.
6376 if (!NamedContext) {
6377 // FIXME: in C++0x, we can diagnose if we can prove that the
6378 // nested-name-specifier does not refer to a base class, which is
6379 // still possible in some cases.
6380
6381 // Otherwise we have to conservatively report that things might be
6382 // okay.
6383 return false;
6384 }
6385
6386 if (!NamedContext->isRecord()) {
6387 // Ideally this would point at the last name in the specifier,
6388 // but we don't have that level of source info.
6389 Diag(SS.getRange().getBegin(),
6390 diag::err_using_decl_nested_name_specifier_is_not_class)
6391 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6392 return true;
6393 }
6394
Douglas Gregor6fb07292010-12-21 07:41:49 +00006395 if (!NamedContext->isDependentContext() &&
6396 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6397 return true;
6398
David Blaikie4e4d0842012-03-11 07:00:24 +00006399 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006400 // C++0x [namespace.udecl]p3:
6401 // In a using-declaration used as a member-declaration, the
6402 // nested-name-specifier shall name a base class of the class
6403 // being defined.
6404
6405 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6406 cast<CXXRecordDecl>(NamedContext))) {
6407 if (CurContext == NamedContext) {
6408 Diag(NameLoc,
6409 diag::err_using_decl_nested_name_specifier_is_current_class)
6410 << SS.getRange();
6411 return true;
6412 }
6413
6414 Diag(SS.getRange().getBegin(),
6415 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6416 << (NestedNameSpecifier*) SS.getScopeRep()
6417 << cast<CXXRecordDecl>(CurContext)
6418 << SS.getRange();
6419 return true;
6420 }
6421
6422 return false;
6423 }
6424
6425 // C++03 [namespace.udecl]p4:
6426 // A using-declaration used as a member-declaration shall refer
6427 // to a member of a base class of the class being defined [etc.].
6428
6429 // Salient point: SS doesn't have to name a base class as long as
6430 // lookup only finds members from base classes. Therefore we can
6431 // diagnose here only if we can prove that that can't happen,
6432 // i.e. if the class hierarchies provably don't intersect.
6433
6434 // TODO: it would be nice if "definitely valid" results were cached
6435 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6436 // need to be repeated.
6437
6438 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006439 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006440
6441 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6442 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6443 Data->Bases.insert(Base);
6444 return true;
6445 }
6446
6447 bool hasDependentBases(const CXXRecordDecl *Class) {
6448 return !Class->forallBases(collect, this);
6449 }
6450
6451 /// Returns true if the base is dependent or is one of the
6452 /// accumulated base classes.
6453 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6454 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6455 return !Data->Bases.count(Base);
6456 }
6457
6458 bool mightShareBases(const CXXRecordDecl *Class) {
6459 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6460 }
6461 };
6462
6463 UserData Data;
6464
6465 // Returns false if we find a dependent base.
6466 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6467 return false;
6468
6469 // Returns false if the class has a dependent base or if it or one
6470 // of its bases is present in the base set of the current context.
6471 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6472 return false;
6473
6474 Diag(SS.getRange().getBegin(),
6475 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6476 << (NestedNameSpecifier*) SS.getScopeRep()
6477 << cast<CXXRecordDecl>(CurContext)
6478 << SS.getRange();
6479
6480 return true;
John McCalled976492009-12-04 22:46:56 +00006481}
6482
Richard Smith162e1c12011-04-15 14:24:37 +00006483Decl *Sema::ActOnAliasDeclaration(Scope *S,
6484 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006485 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006486 SourceLocation UsingLoc,
6487 UnqualifiedId &Name,
6488 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006489 // Skip up to the relevant declaration scope.
6490 while (S->getFlags() & Scope::TemplateParamScope)
6491 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006492 assert((S->getFlags() & Scope::DeclScope) &&
6493 "got alias-declaration outside of declaration scope");
6494
6495 if (Type.isInvalid())
6496 return 0;
6497
6498 bool Invalid = false;
6499 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6500 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006501 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006502
6503 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6504 return 0;
6505
6506 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006507 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006508 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006509 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6510 TInfo->getTypeLoc().getBeginLoc());
6511 }
Richard Smith162e1c12011-04-15 14:24:37 +00006512
6513 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6514 LookupName(Previous, S);
6515
6516 // Warn about shadowing the name of a template parameter.
6517 if (Previous.isSingleResult() &&
6518 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006519 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006520 Previous.clear();
6521 }
6522
6523 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6524 "name in alias declaration must be an identifier");
6525 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6526 Name.StartLocation,
6527 Name.Identifier, TInfo);
6528
6529 NewTD->setAccess(AS);
6530
6531 if (Invalid)
6532 NewTD->setInvalidDecl();
6533
Richard Smith3e4c6c42011-05-05 21:57:07 +00006534 CheckTypedefForVariablyModifiedType(S, NewTD);
6535 Invalid |= NewTD->isInvalidDecl();
6536
Richard Smith162e1c12011-04-15 14:24:37 +00006537 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006538
6539 NamedDecl *NewND;
6540 if (TemplateParamLists.size()) {
6541 TypeAliasTemplateDecl *OldDecl = 0;
6542 TemplateParameterList *OldTemplateParams = 0;
6543
6544 if (TemplateParamLists.size() != 1) {
6545 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6546 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6547 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6548 }
6549 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6550
6551 // Only consider previous declarations in the same scope.
6552 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6553 /*ExplicitInstantiationOrSpecialization*/false);
6554 if (!Previous.empty()) {
6555 Redeclaration = true;
6556
6557 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6558 if (!OldDecl && !Invalid) {
6559 Diag(UsingLoc, diag::err_redefinition_different_kind)
6560 << Name.Identifier;
6561
6562 NamedDecl *OldD = Previous.getRepresentativeDecl();
6563 if (OldD->getLocation().isValid())
6564 Diag(OldD->getLocation(), diag::note_previous_definition);
6565
6566 Invalid = true;
6567 }
6568
6569 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6570 if (TemplateParameterListsAreEqual(TemplateParams,
6571 OldDecl->getTemplateParameters(),
6572 /*Complain=*/true,
6573 TPL_TemplateMatch))
6574 OldTemplateParams = OldDecl->getTemplateParameters();
6575 else
6576 Invalid = true;
6577
6578 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6579 if (!Invalid &&
6580 !Context.hasSameType(OldTD->getUnderlyingType(),
6581 NewTD->getUnderlyingType())) {
6582 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6583 // but we can't reasonably accept it.
6584 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6585 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6586 if (OldTD->getLocation().isValid())
6587 Diag(OldTD->getLocation(), diag::note_previous_definition);
6588 Invalid = true;
6589 }
6590 }
6591 }
6592
6593 // Merge any previous default template arguments into our parameters,
6594 // and check the parameter list.
6595 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6596 TPC_TypeAliasTemplate))
6597 return 0;
6598
6599 TypeAliasTemplateDecl *NewDecl =
6600 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6601 Name.Identifier, TemplateParams,
6602 NewTD);
6603
6604 NewDecl->setAccess(AS);
6605
6606 if (Invalid)
6607 NewDecl->setInvalidDecl();
6608 else if (OldDecl)
6609 NewDecl->setPreviousDeclaration(OldDecl);
6610
6611 NewND = NewDecl;
6612 } else {
6613 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6614 NewND = NewTD;
6615 }
Richard Smith162e1c12011-04-15 14:24:37 +00006616
6617 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006618 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006619
Richard Smith3e4c6c42011-05-05 21:57:07 +00006620 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006621}
6622
John McCalld226f652010-08-21 09:40:31 +00006623Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006624 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006625 SourceLocation AliasLoc,
6626 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006627 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006628 SourceLocation IdentLoc,
6629 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006630
Anders Carlsson81c85c42009-03-28 23:53:49 +00006631 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006632 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6633 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006634
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006635 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006636 NamedDecl *PrevDecl
6637 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6638 ForRedeclaration);
6639 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6640 PrevDecl = 0;
6641
6642 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006643 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006644 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006645 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006646 // FIXME: At some point, we'll want to create the (redundant)
6647 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006648 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006649 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006650 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006651 }
Mike Stump1eb44332009-09-09 15:08:12 +00006652
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006653 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6654 diag::err_redefinition_different_kind;
6655 Diag(AliasLoc, DiagID) << Alias;
6656 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006657 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006658 }
6659
John McCalla24dc2e2009-11-17 02:14:36 +00006660 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006661 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006662
John McCallf36e02d2009-10-09 21:13:30 +00006663 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006664 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006665 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006666 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006667 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006668 }
Mike Stump1eb44332009-09-09 15:08:12 +00006669
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006670 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006671 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006672 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006673 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006674
John McCall3dbd3d52010-02-16 06:53:13 +00006675 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006676 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006677}
6678
Douglas Gregor39957dc2010-05-01 15:04:51 +00006679namespace {
6680 /// \brief Scoped object used to handle the state changes required in Sema
6681 /// to implicitly define the body of a C++ member function;
6682 class ImplicitlyDefinedFunctionScope {
6683 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006684 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006685
6686 public:
6687 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006688 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006689 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006690 S.PushFunctionScope();
6691 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6692 }
6693
6694 ~ImplicitlyDefinedFunctionScope() {
6695 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006696 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006697 }
6698 };
6699}
6700
Sean Hunt001cad92011-05-10 00:49:42 +00006701Sema::ImplicitExceptionSpecification
6702Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006703 // C++ [except.spec]p14:
6704 // An implicitly declared special member function (Clause 12) shall have an
6705 // exception-specification. [...]
6706 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006707 if (ClassDecl->isInvalidDecl())
6708 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006709
Sebastian Redl60618fa2011-03-12 11:50:43 +00006710 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006711 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6712 BEnd = ClassDecl->bases_end();
6713 B != BEnd; ++B) {
6714 if (B->isVirtual()) // Handled below.
6715 continue;
6716
Douglas Gregor18274032010-07-03 00:47:00 +00006717 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6718 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006719 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6720 // If this is a deleted function, add it anyway. This might be conformant
6721 // with the standard. This might not. I'm not sure. It might not matter.
6722 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006723 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006724 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006725 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006726
6727 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006728 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6729 BEnd = ClassDecl->vbases_end();
6730 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006731 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6732 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006733 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6734 // If this is a deleted function, add it anyway. This might be conformant
6735 // with the standard. This might not. I'm not sure. It might not matter.
6736 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006737 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006738 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006739 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006740
6741 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006742 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6743 FEnd = ClassDecl->field_end();
6744 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006745 if (F->hasInClassInitializer()) {
6746 if (Expr *E = F->getInClassInitializer())
6747 ExceptSpec.CalledExpr(E);
6748 else if (!F->isInvalidDecl())
6749 ExceptSpec.SetDelayed();
6750 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006751 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006752 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6753 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6754 // If this is a deleted function, add it anyway. This might be conformant
6755 // with the standard. This might not. I'm not sure. It might not matter.
6756 // In particular, the problem is that this function never gets called. It
6757 // might just be ill-formed because this function attempts to refer to
6758 // a deleted function here.
6759 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006760 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006761 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006762 }
John McCalle23cf432010-12-14 08:05:40 +00006763
Sean Hunt001cad92011-05-10 00:49:42 +00006764 return ExceptSpec;
6765}
6766
6767CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6768 CXXRecordDecl *ClassDecl) {
6769 // C++ [class.ctor]p5:
6770 // A default constructor for a class X is a constructor of class X
6771 // that can be called without an argument. If there is no
6772 // user-declared constructor for class X, a default constructor is
6773 // implicitly declared. An implicitly-declared default constructor
6774 // is an inline public member of its class.
6775 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6776 "Should not build implicit default constructor!");
6777
6778 ImplicitExceptionSpecification Spec =
6779 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6780 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006781
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006782 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006783 CanQualType ClassType
6784 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006785 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006786 DeclarationName Name
6787 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006788 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006789 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6790 Context, ClassDecl, ClassLoc, NameInfo,
6791 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6792 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6793 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006794 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006795 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006796 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006797 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006798 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006799
6800 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006801 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6802
Douglas Gregor23c94db2010-07-02 17:43:08 +00006803 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006804 PushOnScopeChains(DefaultCon, S, false);
6805 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006806
Sean Hunte16da072011-10-10 06:18:57 +00006807 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006808 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006809
Douglas Gregor32df23e2010-07-01 22:02:46 +00006810 return DefaultCon;
6811}
6812
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006813void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6814 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006815 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006816 !Constructor->doesThisDeclarationHaveABody() &&
6817 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006818 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006819
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006820 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006821 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006822
Douglas Gregor39957dc2010-05-01 15:04:51 +00006823 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006824 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006825 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006826 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006827 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006828 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006829 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006830 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006831 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006832
6833 SourceLocation Loc = Constructor->getLocation();
6834 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6835
6836 Constructor->setUsed();
6837 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006838
6839 if (ASTMutationListener *L = getASTMutationListener()) {
6840 L->CompletedImplicitDefinition(Constructor);
6841 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006842}
6843
Richard Smith7a614d82011-06-11 17:19:42 +00006844/// Get any existing defaulted default constructor for the given class. Do not
6845/// implicitly define one if it does not exist.
6846static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6847 CXXRecordDecl *D) {
6848 ASTContext &Context = Self.Context;
6849 QualType ClassType = Context.getTypeDeclType(D);
6850 DeclarationName ConstructorName
6851 = Context.DeclarationNames.getCXXConstructorName(
6852 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6853
6854 DeclContext::lookup_const_iterator Con, ConEnd;
6855 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6856 Con != ConEnd; ++Con) {
6857 // A function template cannot be defaulted.
6858 if (isa<FunctionTemplateDecl>(*Con))
6859 continue;
6860
6861 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6862 if (Constructor->isDefaultConstructor())
6863 return Constructor->isDefaulted() ? Constructor : 0;
6864 }
6865 return 0;
6866}
6867
6868void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6869 if (!D) return;
6870 AdjustDeclIfTemplate(D);
6871
6872 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6873 CXXConstructorDecl *CtorDecl
6874 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6875
6876 if (!CtorDecl) return;
6877
6878 // Compute the exception specification for the default constructor.
6879 const FunctionProtoType *CtorTy =
6880 CtorDecl->getType()->castAs<FunctionProtoType>();
6881 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6882 ImplicitExceptionSpecification Spec =
6883 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6884 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6885 assert(EPI.ExceptionSpecType != EST_Delayed);
6886
6887 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6888 }
6889
6890 // If the default constructor is explicitly defaulted, checking the exception
6891 // specification is deferred until now.
6892 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6893 !ClassDecl->isDependentType())
6894 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6895}
6896
Sebastian Redlf677ea32011-02-05 19:23:19 +00006897void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6898 // We start with an initial pass over the base classes to collect those that
6899 // inherit constructors from. If there are none, we can forgo all further
6900 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006901 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006902 BasesVector BasesToInheritFrom;
6903 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6904 BaseE = ClassDecl->bases_end();
6905 BaseIt != BaseE; ++BaseIt) {
6906 if (BaseIt->getInheritConstructors()) {
6907 QualType Base = BaseIt->getType();
6908 if (Base->isDependentType()) {
6909 // If we inherit constructors from anything that is dependent, just
6910 // abort processing altogether. We'll get another chance for the
6911 // instantiations.
6912 return;
6913 }
6914 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6915 }
6916 }
6917 if (BasesToInheritFrom.empty())
6918 return;
6919
6920 // Now collect the constructors that we already have in the current class.
6921 // Those take precedence over inherited constructors.
6922 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6923 // unless there is a user-declared constructor with the same signature in
6924 // the class where the using-declaration appears.
6925 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6926 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6927 CtorE = ClassDecl->ctor_end();
6928 CtorIt != CtorE; ++CtorIt) {
6929 ExistingConstructors.insert(
6930 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6931 }
6932
6933 Scope *S = getScopeForContext(ClassDecl);
6934 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.
6955 DeclarationName Name =
6956 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6957 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6958 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6959 SourceLocation UsingLoc = UD ? UD->getLocation() :
6960 ClassDecl->getLocation();
6961
6962 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6963 // from the class X named in the using-declaration consists of actual
6964 // constructors and notional constructors that result from the
6965 // transformation of defaulted parameters as follows:
6966 // - all non-template default constructors of X, and
6967 // - for each non-template constructor of X that has at least one
6968 // parameter with a default argument, the set of constructors that
6969 // results from omitting any ellipsis parameter specification and
6970 // successively omitting parameters with a default argument from the
6971 // end of the parameter-type-list.
6972 CXXConstructorDecl *BaseCtor = *CtorIt;
6973 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6974 const FunctionProtoType *BaseCtorType =
6975 BaseCtor->getType()->getAs<FunctionProtoType>();
6976
6977 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6978 maxParams = BaseCtor->getNumParams();
6979 params <= maxParams; ++params) {
6980 // Skip default constructors. They're never inherited.
6981 if (params == 0)
6982 continue;
6983 // Skip copy and move constructors for the same reason.
6984 if (CanBeCopyOrMove && params == 1)
6985 continue;
6986
6987 // Build up a function type for this particular constructor.
6988 // FIXME: The working paper does not consider that the exception spec
6989 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006990 // source. This code doesn't yet, either. When it does, this code will
6991 // need to be delayed until after exception specifications and in-class
6992 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006993 const Type *NewCtorType;
6994 if (params == maxParams)
6995 NewCtorType = BaseCtorType;
6996 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006997 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006998 for (unsigned i = 0; i < params; ++i) {
6999 Args.push_back(BaseCtorType->getArgType(i));
7000 }
7001 FunctionProtoType::ExtProtoInfo ExtInfo =
7002 BaseCtorType->getExtProtoInfo();
7003 ExtInfo.Variadic = false;
7004 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7005 Args.data(), params, ExtInfo)
7006 .getTypePtr();
7007 }
7008 const Type *CanonicalNewCtorType =
7009 Context.getCanonicalType(NewCtorType);
7010
7011 // Now that we have the type, first check if the class already has a
7012 // constructor with this signature.
7013 if (ExistingConstructors.count(CanonicalNewCtorType))
7014 continue;
7015
7016 // Then we check if we have already declared an inherited constructor
7017 // with this signature.
7018 std::pair<ConstructorToSourceMap::iterator, bool> result =
7019 InheritedConstructors.insert(std::make_pair(
7020 CanonicalNewCtorType,
7021 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7022 if (!result.second) {
7023 // Already in the map. If it came from a different class, that's an
7024 // error. Not if it's from the same.
7025 CanQualType PreviousBase = result.first->second.first;
7026 if (CanonicalBase != PreviousBase) {
7027 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7028 const CXXConstructorDecl *PrevBaseCtor =
7029 PrevCtor->getInheritedConstructor();
7030 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7031
7032 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7033 Diag(BaseCtor->getLocation(),
7034 diag::note_using_decl_constructor_conflict_current_ctor);
7035 Diag(PrevBaseCtor->getLocation(),
7036 diag::note_using_decl_constructor_conflict_previous_ctor);
7037 Diag(PrevCtor->getLocation(),
7038 diag::note_using_decl_constructor_conflict_previous_using);
7039 }
7040 continue;
7041 }
7042
7043 // OK, we're there, now add the constructor.
7044 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007045 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007046 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7047 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007048 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7049 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007050 /*ImplicitlyDeclared=*/true,
7051 // FIXME: Due to a defect in the standard, we treat inherited
7052 // constructors as constexpr even if that makes them ill-formed.
7053 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007054 NewCtor->setAccess(BaseCtor->getAccess());
7055
7056 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007057 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007058 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007059 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7060 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007061 /*IdentifierInfo=*/0,
7062 BaseCtorType->getArgType(i),
7063 /*TInfo=*/0, SC_None,
7064 SC_None, /*DefaultArg=*/0));
7065 }
David Blaikie4278c652011-09-21 18:16:56 +00007066 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007067 NewCtor->setInheritedConstructor(BaseCtor);
7068
7069 PushOnScopeChains(NewCtor, S, false);
7070 ClassDecl->addDecl(NewCtor);
7071 result.first->second.second = NewCtor;
7072 }
7073 }
7074 }
7075}
7076
Sean Huntcb45a0f2011-05-12 22:46:25 +00007077Sema::ImplicitExceptionSpecification
7078Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007079 // C++ [except.spec]p14:
7080 // An implicitly declared special member function (Clause 12) shall have
7081 // an exception-specification.
7082 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007083 if (ClassDecl->isInvalidDecl())
7084 return ExceptSpec;
7085
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007086 // Direct base-class destructors.
7087 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7088 BEnd = ClassDecl->bases_end();
7089 B != BEnd; ++B) {
7090 if (B->isVirtual()) // Handled below.
7091 continue;
7092
7093 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7094 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007095 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007096 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007097
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007098 // Virtual base-class destructors.
7099 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7100 BEnd = ClassDecl->vbases_end();
7101 B != BEnd; ++B) {
7102 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7103 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007104 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007105 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007106
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007107 // Field destructors.
7108 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7109 FEnd = ClassDecl->field_end();
7110 F != FEnd; ++F) {
7111 if (const RecordType *RecordTy
7112 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7113 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007114 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007115 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007116
Sean Huntcb45a0f2011-05-12 22:46:25 +00007117 return ExceptSpec;
7118}
7119
7120CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7121 // C++ [class.dtor]p2:
7122 // If a class has no user-declared destructor, a destructor is
7123 // declared implicitly. An implicitly-declared destructor is an
7124 // inline public member of its class.
7125
7126 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007127 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007128 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7129
Douglas Gregor4923aa22010-07-02 20:37:36 +00007130 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007131 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007132
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007133 CanQualType ClassType
7134 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007135 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007136 DeclarationName Name
7137 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007138 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007139 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007140 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7141 /*isInline=*/true,
7142 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007143 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007144 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007145 Destructor->setImplicit();
7146 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007147
7148 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007149 ++ASTContext::NumImplicitDestructorsDeclared;
7150
7151 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007152 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007153 PushOnScopeChains(Destructor, S, false);
7154 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007155
7156 // This could be uniqued if it ever proves significant.
7157 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
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();
7194 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, 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
Sebastian Redl0ee33912011-05-19 05:13:44 +00007204void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7205 CXXDestructorDecl *destructor) {
7206 // C++11 [class.dtor]p3:
7207 // A declaration of a destructor that does not have an exception-
7208 // specification is implicitly considered to have the same exception-
7209 // specification as an implicit declaration.
7210 const FunctionProtoType *dtorType = destructor->getType()->
7211 getAs<FunctionProtoType>();
7212 if (dtorType->hasExceptionSpec())
7213 return;
7214
7215 ImplicitExceptionSpecification exceptSpec =
7216 ComputeDefaultedDtorExceptionSpec(classDecl);
7217
Chandler Carruth3f224b22011-09-20 04:55:26 +00007218 // Replace the destructor's type, building off the existing one. Fortunately,
7219 // the only thing of interest in the destructor type is its extended info.
7220 // The return and arguments are fixed.
7221 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007222 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7223 epi.NumExceptions = exceptSpec.size();
7224 epi.Exceptions = exceptSpec.data();
7225 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7226
7227 destructor->setType(ty);
7228
7229 // FIXME: If the destructor has a body that could throw, and the newly created
7230 // spec doesn't allow exceptions, we should emit a warning, because this
7231 // change in behavior can break conforming C++03 programs at runtime.
7232 // However, we don't have a body yet, so it needs to be done somewhere else.
7233}
7234
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007235/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007236/// \c To.
7237///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007238/// This routine is used to copy/move the members of a class with an
7239/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007240/// copied are arrays, this routine builds for loops to copy them.
7241///
7242/// \param S The Sema object used for type-checking.
7243///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007244/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007245///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007246/// \param T The type of the expressions being copied/moved. Both expressions
7247/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007248///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007249/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007250///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007251/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007252///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007253/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007254/// Otherwise, it's a non-static member subobject.
7255///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007256/// \param Copying Whether we're copying or moving.
7257///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007258/// \param Depth Internal parameter recording the depth of the recursion.
7259///
7260/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007261static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007262BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007263 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007264 bool CopyingBaseSubobject, bool Copying,
7265 unsigned Depth = 0) {
7266 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007267 // Each subobject is assigned in the manner appropriate to its type:
7268 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007269 // - if the subobject is of class type, as if by a call to operator= with
7270 // the subobject as the object expression and the corresponding
7271 // subobject of x as a single function argument (as if by explicit
7272 // qualification; that is, ignoring any possible virtual overriding
7273 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007274 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7275 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7276
7277 // Look for operator=.
7278 DeclarationName Name
7279 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7280 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7281 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7282
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007283 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007284 LookupResult::Filter F = OpLookup.makeFilter();
7285 while (F.hasNext()) {
7286 NamedDecl *D = F.next();
7287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007288 if (Copying ? Method->isCopyAssignmentOperator() :
7289 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007290 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007291
Douglas Gregor06a9f362010-05-01 20:49:11 +00007292 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007293 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007294 F.done();
7295
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007296 // Suppress the protected check (C++ [class.protected]) for each of the
7297 // assignment operators we found. This strange dance is required when
7298 // we're assigning via a base classes's copy-assignment operator. To
7299 // ensure that we're getting the right base class subobject (without
7300 // ambiguities), we need to cast "this" to that subobject type; to
7301 // ensure that we don't go through the virtual call mechanism, we need
7302 // to qualify the operator= name with the base class (see below). However,
7303 // this means that if the base class has a protected copy assignment
7304 // operator, the protected member access check will fail. So, we
7305 // rewrite "protected" access to "public" access in this case, since we
7306 // know by construction that we're calling from a derived class.
7307 if (CopyingBaseSubobject) {
7308 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7309 L != LEnd; ++L) {
7310 if (L.getAccess() == AS_protected)
7311 L.setAccess(AS_public);
7312 }
7313 }
7314
Douglas Gregor06a9f362010-05-01 20:49:11 +00007315 // Create the nested-name-specifier that will be used to qualify the
7316 // reference to operator=; this is required to suppress the virtual
7317 // call mechanism.
7318 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007319 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007320 SS.MakeTrivial(S.Context,
7321 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007322 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007323 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007324
7325 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007326 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007327 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007328 /*TemplateKWLoc=*/SourceLocation(),
7329 /*FirstQualifierInScope=*/0,
7330 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007331 /*TemplateArgs=*/0,
7332 /*SuppressQualifierCheck=*/true);
7333 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007334 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007335
7336 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007337
John McCall60d7b3a2010-08-24 06:29:42 +00007338 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007339 OpEqualRef.takeAs<Expr>(),
7340 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007341 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007342 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007343
7344 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007345 }
John McCallb0207482010-03-16 06:11:48 +00007346
Douglas Gregor06a9f362010-05-01 20:49:11 +00007347 // - if the subobject is of scalar type, the built-in assignment
7348 // operator is used.
7349 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7350 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007351 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007352 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007353 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354
7355 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007356 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007357
7358 // - if the subobject is an array, each element is assigned, in the
7359 // manner appropriate to the element type;
7360
7361 // Construct a loop over the array bounds, e.g.,
7362 //
7363 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7364 //
7365 // that will copy each of the array elements.
7366 QualType SizeType = S.Context.getSizeType();
7367
7368 // Create the iteration variable.
7369 IdentifierInfo *IterationVarName = 0;
7370 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007371 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007372 llvm::raw_svector_ostream OS(Str);
7373 OS << "__i" << Depth;
7374 IterationVarName = &S.Context.Idents.get(OS.str());
7375 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007376 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007377 IterationVarName, SizeType,
7378 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007379 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007380
7381 // Initialize the iteration variable to zero.
7382 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007383 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007384
7385 // Create a reference to the iteration variable; we'll use this several
7386 // times throughout.
7387 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007388 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007389 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007390 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7391 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7392
Douglas Gregor06a9f362010-05-01 20:49:11 +00007393 // Create the DeclStmt that holds the iteration variable.
7394 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7395
7396 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007397 llvm::APInt Upper
7398 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007399 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007400 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007401 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7402 BO_NE, S.Context.BoolTy,
7403 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007404
7405 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007406 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007407 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7408 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007409
7410 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007411 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007412 IterationVarRefRVal,
7413 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007414 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007415 IterationVarRefRVal,
7416 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007417 if (!Copying) // Cast to rvalue
7418 From = CastForMoving(S, From);
7419
7420 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007421 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7422 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007423 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007424 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007425 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007426
7427 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007428 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007429 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007430 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007431 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007432}
7433
Sean Hunt30de05c2011-05-14 05:23:20 +00007434std::pair<Sema::ImplicitExceptionSpecification, bool>
7435Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7436 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007437 if (ClassDecl->isInvalidDecl())
7438 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7439
Douglas Gregord3c35902010-07-01 16:36:15 +00007440 // C++ [class.copy]p10:
7441 // If the class definition does not explicitly declare a copy
7442 // assignment operator, one is declared implicitly.
7443 // The implicitly-defined copy assignment operator for a class X
7444 // will have the form
7445 //
7446 // X& X::operator=(const X&)
7447 //
7448 // if
7449 bool HasConstCopyAssignment = true;
7450
7451 // -- each direct base class B of X has a copy assignment operator
7452 // whose parameter is of type const B&, const volatile B& or B,
7453 // and
7454 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7455 BaseEnd = ClassDecl->bases_end();
7456 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007457 // We'll handle this below
7458 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7459 continue;
7460
Douglas Gregord3c35902010-07-01 16:36:15 +00007461 assert(!Base->getType()->isDependentType() &&
7462 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007463 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7464 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7465 &HasConstCopyAssignment);
7466 }
7467
Richard Smithebaf0e62011-10-18 20:49:44 +00007468 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007469 if (LangOpts.CPlusPlus0x) {
7470 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7471 BaseEnd = ClassDecl->vbases_end();
7472 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7473 assert(!Base->getType()->isDependentType() &&
7474 "Cannot generate implicit members for class with dependent bases.");
7475 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7476 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7477 &HasConstCopyAssignment);
7478 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007479 }
7480
7481 // -- for all the nonstatic data members of X that are of a class
7482 // type M (or array thereof), each such class type has a copy
7483 // assignment operator whose parameter is of type const M&,
7484 // const volatile M& or M.
7485 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7486 FieldEnd = ClassDecl->field_end();
7487 HasConstCopyAssignment && Field != FieldEnd;
7488 ++Field) {
7489 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007490 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7491 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7492 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007493 }
7494 }
7495
7496 // Otherwise, the implicitly declared copy assignment operator will
7497 // have the form
7498 //
7499 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007500
Douglas Gregorb87786f2010-07-01 17:48:08 +00007501 // C++ [except.spec]p14:
7502 // An implicitly declared special member function (Clause 12) shall have an
7503 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007504
7505 // It is unspecified whether or not an implicit copy assignment operator
7506 // attempts to deduplicate calls to assignment operators of virtual bases are
7507 // made. As such, this exception specification is effectively unspecified.
7508 // Based on a similar decision made for constness in C++0x, we're erring on
7509 // the side of assuming such calls to be made regardless of whether they
7510 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007511 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007512 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7514 BaseEnd = ClassDecl->bases_end();
7515 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007516 if (Base->isVirtual())
7517 continue;
7518
Douglas Gregora376d102010-07-02 21:50:04 +00007519 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007520 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007521 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7522 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007523 ExceptSpec.CalledDecl(CopyAssign);
7524 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007525
7526 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7527 BaseEnd = ClassDecl->vbases_end();
7528 Base != BaseEnd; ++Base) {
7529 CXXRecordDecl *BaseClassDecl
7530 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7531 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7532 ArgQuals, false, 0))
7533 ExceptSpec.CalledDecl(CopyAssign);
7534 }
7535
Douglas Gregorb87786f2010-07-01 17:48:08 +00007536 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7537 FieldEnd = ClassDecl->field_end();
7538 Field != FieldEnd;
7539 ++Field) {
7540 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007541 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7542 if (CXXMethodDecl *CopyAssign =
7543 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7544 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007545 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007546 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007547
Sean Hunt30de05c2011-05-14 05:23:20 +00007548 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7549}
7550
7551CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7552 // Note: The following rules are largely analoguous to the copy
7553 // constructor rules. Note that virtual bases are not taken into account
7554 // for determining the argument type of the operator. Note also that
7555 // operators taking an object instead of a reference are allowed.
7556
7557 ImplicitExceptionSpecification Spec(Context);
7558 bool Const;
7559 llvm::tie(Spec, Const) =
7560 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7561
7562 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7563 QualType RetType = Context.getLValueReferenceType(ArgType);
7564 if (Const)
7565 ArgType = ArgType.withConst();
7566 ArgType = Context.getLValueReferenceType(ArgType);
7567
Douglas Gregord3c35902010-07-01 16:36:15 +00007568 // An implicitly-declared copy assignment operator is an inline public
7569 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007570 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007571 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007572 SourceLocation ClassLoc = ClassDecl->getLocation();
7573 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007574 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007575 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007576 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007577 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007578 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007579 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007580 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007581 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007582 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007583 CopyAssignment->setImplicit();
7584 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007585
7586 // Add the parameter to the operator.
7587 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007588 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007589 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007590 SC_None,
7591 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007592 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007593
Douglas Gregora376d102010-07-02 21:50:04 +00007594 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007595 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007596
Douglas Gregor23c94db2010-07-02 17:43:08 +00007597 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007598 PushOnScopeChains(CopyAssignment, S, false);
7599 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007600
Nico Weberafcc96a2012-01-23 03:19:29 +00007601 // C++0x [class.copy]p19:
7602 // .... If the class definition does not explicitly declare a copy
7603 // assignment operator, there is no user-declared move constructor, and
7604 // there is no user-declared move assignment operator, a copy assignment
7605 // operator is implicitly declared as defaulted.
7606 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007607 !getLangOpts().MicrosoftMode) ||
Nico Weber28976602012-01-23 04:01:33 +00007608 ClassDecl->hasUserDeclaredMoveAssignment() ||
Richard Smith7d5088a2012-02-18 02:02:13 +00007609 ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007610 CopyAssignment->setDeletedAsWritten();
7611
Douglas Gregord3c35902010-07-01 16:36:15 +00007612 AddOverriddenMethods(ClassDecl, CopyAssignment);
7613 return CopyAssignment;
7614}
7615
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7617 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007618 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619 CopyAssignOperator->isOverloadedOperator() &&
7620 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007621 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7622 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007623 "DefineImplicitCopyAssignment called for wrong function");
7624
7625 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7626
7627 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7628 CopyAssignOperator->setInvalidDecl();
7629 return;
7630 }
7631
7632 CopyAssignOperator->setUsed();
7633
7634 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007635 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007636
7637 // C++0x [class.copy]p30:
7638 // The implicitly-defined or explicitly-defaulted copy assignment operator
7639 // for a non-union class X performs memberwise copy assignment of its
7640 // subobjects. The direct base classes of X are assigned first, in the
7641 // order of their declaration in the base-specifier-list, and then the
7642 // immediate non-static data members of X are assigned, in the order in
7643 // which they were declared in the class definition.
7644
7645 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007646 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007647
7648 // The parameter for the "other" object, which we are copying from.
7649 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7650 Qualifiers OtherQuals = Other->getType().getQualifiers();
7651 QualType OtherRefType = Other->getType();
7652 if (const LValueReferenceType *OtherRef
7653 = OtherRefType->getAs<LValueReferenceType>()) {
7654 OtherRefType = OtherRef->getPointeeType();
7655 OtherQuals = OtherRefType.getQualifiers();
7656 }
7657
7658 // Our location for everything implicitly-generated.
7659 SourceLocation Loc = CopyAssignOperator->getLocation();
7660
7661 // Construct a reference to the "other" object. We'll be using this
7662 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007663 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007664 assert(OtherRef && "Reference to parameter cannot fail!");
7665
7666 // Construct the "this" pointer. We'll be using this throughout the generated
7667 // ASTs.
7668 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7669 assert(This && "Reference to this cannot fail!");
7670
7671 // Assign base classes.
7672 bool Invalid = false;
7673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7674 E = ClassDecl->bases_end(); Base != E; ++Base) {
7675 // Form the assignment:
7676 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7677 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007678 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679 Invalid = true;
7680 continue;
7681 }
7682
John McCallf871d0c2010-08-07 06:22:56 +00007683 CXXCastPath BasePath;
7684 BasePath.push_back(Base);
7685
Douglas Gregor06a9f362010-05-01 20:49:11 +00007686 // Construct the "from" expression, which is an implicit cast to the
7687 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007688 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007689 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7690 CK_UncheckedDerivedToBase,
7691 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007692
7693 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007694 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007695
7696 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007697 To = ImpCastExprToType(To.take(),
7698 Context.getCVRQualifiedType(BaseType,
7699 CopyAssignOperator->getTypeQualifiers()),
7700 CK_UncheckedDerivedToBase,
7701 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007702
7703 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007704 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007705 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007706 /*CopyingBaseSubobject=*/true,
7707 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007708 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007709 Diag(CurrentLocation, diag::note_member_synthesized_at)
7710 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7711 CopyAssignOperator->setInvalidDecl();
7712 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007713 }
7714
7715 // Success! Record the copy.
7716 Statements.push_back(Copy.takeAs<Expr>());
7717 }
7718
7719 // \brief Reference to the __builtin_memcpy function.
7720 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007721 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007722 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007723
7724 // Assign non-static members.
7725 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7726 FieldEnd = ClassDecl->field_end();
7727 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007728 if (Field->isUnnamedBitfield())
7729 continue;
7730
Douglas Gregor06a9f362010-05-01 20:49:11 +00007731 // Check for members of reference type; we can't copy those.
7732 if (Field->getType()->isReferenceType()) {
7733 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7734 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7735 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007736 Diag(CurrentLocation, diag::note_member_synthesized_at)
7737 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007738 Invalid = true;
7739 continue;
7740 }
7741
7742 // Check for members of const-qualified, non-class type.
7743 QualType BaseType = Context.getBaseElementType(Field->getType());
7744 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7745 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7746 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7747 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007748 Diag(CurrentLocation, diag::note_member_synthesized_at)
7749 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007750 Invalid = true;
7751 continue;
7752 }
John McCallb77115d2011-06-17 00:18:42 +00007753
7754 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007755 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7756 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007757
7758 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007759 if (FieldType->isIncompleteArrayType()) {
7760 assert(ClassDecl->hasFlexibleArrayMember() &&
7761 "Incomplete array type is not valid");
7762 continue;
7763 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007764
7765 // Build references to the field in the object we're copying from and to.
7766 CXXScopeSpec SS; // Intentionally empty
7767 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7768 LookupMemberName);
7769 MemberLookup.addDecl(*Field);
7770 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007771 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007772 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007773 SS, SourceLocation(), 0,
7774 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007775 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007776 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007777 SS, SourceLocation(), 0,
7778 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007779 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7780 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7781
7782 // If the field should be copied with __builtin_memcpy rather than via
7783 // explicit assignments, do so. This optimization only applies for arrays
7784 // of scalars and arrays of class type with trivial copy-assignment
7785 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007786 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007787 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007788 // Compute the size of the memory buffer to be copied.
7789 QualType SizeType = Context.getSizeType();
7790 llvm::APInt Size(Context.getTypeSize(SizeType),
7791 Context.getTypeSizeInChars(BaseType).getQuantity());
7792 for (const ConstantArrayType *Array
7793 = Context.getAsConstantArrayType(FieldType);
7794 Array;
7795 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007796 llvm::APInt ArraySize
7797 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007798 Size *= ArraySize;
7799 }
7800
7801 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007802 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7803 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007804
7805 bool NeedsCollectableMemCpy =
7806 (BaseType->isRecordType() &&
7807 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7808
7809 if (NeedsCollectableMemCpy) {
7810 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007811 // Create a reference to the __builtin_objc_memmove_collectable function.
7812 LookupResult R(*this,
7813 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007814 Loc, LookupOrdinaryName);
7815 LookupName(R, TUScope, true);
7816
7817 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7818 if (!CollectableMemCpy) {
7819 // Something went horribly wrong earlier, and we will have
7820 // complained about it.
7821 Invalid = true;
7822 continue;
7823 }
7824
7825 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7826 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007827 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007828 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7829 }
7830 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007831 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007832 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007833 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7834 LookupOrdinaryName);
7835 LookupName(R, TUScope, true);
7836
7837 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7838 if (!BuiltinMemCpy) {
7839 // Something went horribly wrong earlier, and we will have complained
7840 // about it.
7841 Invalid = true;
7842 continue;
7843 }
7844
7845 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7846 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007847 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007848 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7849 }
7850
John McCallca0408f2010-08-23 06:44:23 +00007851 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007852 CallArgs.push_back(To.takeAs<Expr>());
7853 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007854 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007855 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007856 if (NeedsCollectableMemCpy)
7857 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007858 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007859 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007860 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007861 else
7862 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007863 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007864 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007865 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007866
Douglas Gregor06a9f362010-05-01 20:49:11 +00007867 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7868 Statements.push_back(Call.takeAs<Expr>());
7869 continue;
7870 }
7871
7872 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007873 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007874 To.get(), From.get(),
7875 /*CopyingBaseSubobject=*/false,
7876 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007877 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007878 Diag(CurrentLocation, diag::note_member_synthesized_at)
7879 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7880 CopyAssignOperator->setInvalidDecl();
7881 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007882 }
7883
7884 // Success! Record the copy.
7885 Statements.push_back(Copy.takeAs<Stmt>());
7886 }
7887
7888 if (!Invalid) {
7889 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007890 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007891
John McCall60d7b3a2010-08-24 06:29:42 +00007892 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007893 if (Return.isInvalid())
7894 Invalid = true;
7895 else {
7896 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007897
7898 if (Trap.hasErrorOccurred()) {
7899 Diag(CurrentLocation, diag::note_member_synthesized_at)
7900 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7901 Invalid = true;
7902 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007903 }
7904 }
7905
7906 if (Invalid) {
7907 CopyAssignOperator->setInvalidDecl();
7908 return;
7909 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007910
7911 StmtResult Body;
7912 {
7913 CompoundScopeRAII CompoundScope(*this);
7914 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7915 /*isStmtExpr=*/false);
7916 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7917 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007918 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007919
7920 if (ASTMutationListener *L = getASTMutationListener()) {
7921 L->CompletedImplicitDefinition(CopyAssignOperator);
7922 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007923}
7924
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007925Sema::ImplicitExceptionSpecification
7926Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7927 ImplicitExceptionSpecification ExceptSpec(Context);
7928
7929 if (ClassDecl->isInvalidDecl())
7930 return ExceptSpec;
7931
7932 // C++0x [except.spec]p14:
7933 // An implicitly declared special member function (Clause 12) shall have an
7934 // exception-specification. [...]
7935
7936 // It is unspecified whether or not an implicit move assignment operator
7937 // attempts to deduplicate calls to assignment operators of virtual bases are
7938 // made. As such, this exception specification is effectively unspecified.
7939 // Based on a similar decision made for constness in C++0x, we're erring on
7940 // the side of assuming such calls to be made regardless of whether they
7941 // actually happen.
7942 // Note that a move constructor is not implicitly declared when there are
7943 // virtual bases, but it can still be user-declared and explicitly defaulted.
7944 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7945 BaseEnd = ClassDecl->bases_end();
7946 Base != BaseEnd; ++Base) {
7947 if (Base->isVirtual())
7948 continue;
7949
7950 CXXRecordDecl *BaseClassDecl
7951 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7952 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7953 false, 0))
7954 ExceptSpec.CalledDecl(MoveAssign);
7955 }
7956
7957 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7958 BaseEnd = ClassDecl->vbases_end();
7959 Base != BaseEnd; ++Base) {
7960 CXXRecordDecl *BaseClassDecl
7961 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7962 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7963 false, 0))
7964 ExceptSpec.CalledDecl(MoveAssign);
7965 }
7966
7967 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7968 FieldEnd = ClassDecl->field_end();
7969 Field != FieldEnd;
7970 ++Field) {
7971 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7972 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7973 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7974 false, 0))
7975 ExceptSpec.CalledDecl(MoveAssign);
7976 }
7977 }
7978
7979 return ExceptSpec;
7980}
7981
7982CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7983 // Note: The following rules are largely analoguous to the move
7984 // constructor rules.
7985
7986 ImplicitExceptionSpecification Spec(
7987 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7988
7989 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7990 QualType RetType = Context.getLValueReferenceType(ArgType);
7991 ArgType = Context.getRValueReferenceType(ArgType);
7992
7993 // An implicitly-declared move assignment operator is an inline public
7994 // member of its class.
7995 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7996 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7997 SourceLocation ClassLoc = ClassDecl->getLocation();
7998 DeclarationNameInfo NameInfo(Name, ClassLoc);
7999 CXXMethodDecl *MoveAssignment
8000 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8001 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8002 /*TInfo=*/0, /*isStatic=*/false,
8003 /*StorageClassAsWritten=*/SC_None,
8004 /*isInline=*/true,
8005 /*isConstexpr=*/false,
8006 SourceLocation());
8007 MoveAssignment->setAccess(AS_public);
8008 MoveAssignment->setDefaulted();
8009 MoveAssignment->setImplicit();
8010 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8011
8012 // Add the parameter to the operator.
8013 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8014 ClassLoc, ClassLoc, /*Id=*/0,
8015 ArgType, /*TInfo=*/0,
8016 SC_None,
8017 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008018 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008019
8020 // Note that we have added this copy-assignment operator.
8021 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8022
8023 // C++0x [class.copy]p9:
8024 // If the definition of a class X does not explicitly declare a move
8025 // assignment operator, one will be implicitly declared as defaulted if and
8026 // only if:
8027 // [...]
8028 // - the move assignment operator would not be implicitly defined as
8029 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008030 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008031 // Cache this result so that we don't try to generate this over and over
8032 // on every lookup, leaking memory and wasting time.
8033 ClassDecl->setFailedImplicitMoveAssignment();
8034 return 0;
8035 }
8036
8037 if (Scope *S = getScopeForContext(ClassDecl))
8038 PushOnScopeChains(MoveAssignment, S, false);
8039 ClassDecl->addDecl(MoveAssignment);
8040
8041 AddOverriddenMethods(ClassDecl, MoveAssignment);
8042 return MoveAssignment;
8043}
8044
8045void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8046 CXXMethodDecl *MoveAssignOperator) {
8047 assert((MoveAssignOperator->isDefaulted() &&
8048 MoveAssignOperator->isOverloadedOperator() &&
8049 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008050 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8051 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008052 "DefineImplicitMoveAssignment called for wrong function");
8053
8054 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8055
8056 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8057 MoveAssignOperator->setInvalidDecl();
8058 return;
8059 }
8060
8061 MoveAssignOperator->setUsed();
8062
8063 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8064 DiagnosticErrorTrap Trap(Diags);
8065
8066 // C++0x [class.copy]p28:
8067 // The implicitly-defined or move assignment operator for a non-union class
8068 // X performs memberwise move assignment of its subobjects. The direct base
8069 // classes of X are assigned first, in the order of their declaration in the
8070 // base-specifier-list, and then the immediate non-static data members of X
8071 // are assigned, in the order in which they were declared in the class
8072 // definition.
8073
8074 // The statements that form the synthesized function body.
8075 ASTOwningVector<Stmt*> Statements(*this);
8076
8077 // The parameter for the "other" object, which we are move from.
8078 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8079 QualType OtherRefType = Other->getType()->
8080 getAs<RValueReferenceType>()->getPointeeType();
8081 assert(OtherRefType.getQualifiers() == 0 &&
8082 "Bad argument type of defaulted move assignment");
8083
8084 // Our location for everything implicitly-generated.
8085 SourceLocation Loc = MoveAssignOperator->getLocation();
8086
8087 // Construct a reference to the "other" object. We'll be using this
8088 // throughout the generated ASTs.
8089 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8090 assert(OtherRef && "Reference to parameter cannot fail!");
8091 // Cast to rvalue.
8092 OtherRef = CastForMoving(*this, OtherRef);
8093
8094 // Construct the "this" pointer. We'll be using this throughout the generated
8095 // ASTs.
8096 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8097 assert(This && "Reference to this cannot fail!");
8098
8099 // Assign base classes.
8100 bool Invalid = false;
8101 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8102 E = ClassDecl->bases_end(); Base != E; ++Base) {
8103 // Form the assignment:
8104 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8105 QualType BaseType = Base->getType().getUnqualifiedType();
8106 if (!BaseType->isRecordType()) {
8107 Invalid = true;
8108 continue;
8109 }
8110
8111 CXXCastPath BasePath;
8112 BasePath.push_back(Base);
8113
8114 // Construct the "from" expression, which is an implicit cast to the
8115 // appropriately-qualified base type.
8116 Expr *From = OtherRef;
8117 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008118 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008119
8120 // Dereference "this".
8121 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8122
8123 // Implicitly cast "this" to the appropriately-qualified base type.
8124 To = ImpCastExprToType(To.take(),
8125 Context.getCVRQualifiedType(BaseType,
8126 MoveAssignOperator->getTypeQualifiers()),
8127 CK_UncheckedDerivedToBase,
8128 VK_LValue, &BasePath);
8129
8130 // Build the move.
8131 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8132 To.get(), From,
8133 /*CopyingBaseSubobject=*/true,
8134 /*Copying=*/false);
8135 if (Move.isInvalid()) {
8136 Diag(CurrentLocation, diag::note_member_synthesized_at)
8137 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8138 MoveAssignOperator->setInvalidDecl();
8139 return;
8140 }
8141
8142 // Success! Record the move.
8143 Statements.push_back(Move.takeAs<Expr>());
8144 }
8145
8146 // \brief Reference to the __builtin_memcpy function.
8147 Expr *BuiltinMemCpyRef = 0;
8148 // \brief Reference to the __builtin_objc_memmove_collectable function.
8149 Expr *CollectableMemCpyRef = 0;
8150
8151 // Assign non-static members.
8152 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8153 FieldEnd = ClassDecl->field_end();
8154 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008155 if (Field->isUnnamedBitfield())
8156 continue;
8157
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008158 // Check for members of reference type; we can't move those.
8159 if (Field->getType()->isReferenceType()) {
8160 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8161 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8162 Diag(Field->getLocation(), diag::note_declared_at);
8163 Diag(CurrentLocation, diag::note_member_synthesized_at)
8164 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8165 Invalid = true;
8166 continue;
8167 }
8168
8169 // Check for members of const-qualified, non-class type.
8170 QualType BaseType = Context.getBaseElementType(Field->getType());
8171 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8172 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8173 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8174 Diag(Field->getLocation(), diag::note_declared_at);
8175 Diag(CurrentLocation, diag::note_member_synthesized_at)
8176 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8177 Invalid = true;
8178 continue;
8179 }
8180
8181 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008182 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8183 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008184
8185 QualType FieldType = Field->getType().getNonReferenceType();
8186 if (FieldType->isIncompleteArrayType()) {
8187 assert(ClassDecl->hasFlexibleArrayMember() &&
8188 "Incomplete array type is not valid");
8189 continue;
8190 }
8191
8192 // Build references to the field in the object we're copying from and to.
8193 CXXScopeSpec SS; // Intentionally empty
8194 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8195 LookupMemberName);
8196 MemberLookup.addDecl(*Field);
8197 MemberLookup.resolveKind();
8198 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8199 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008200 SS, SourceLocation(), 0,
8201 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008202 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8203 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008204 SS, SourceLocation(), 0,
8205 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008206 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8207 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8208
8209 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8210 "Member reference with rvalue base must be rvalue except for reference "
8211 "members, which aren't allowed for move assignment.");
8212
8213 // If the field should be copied with __builtin_memcpy rather than via
8214 // explicit assignments, do so. This optimization only applies for arrays
8215 // of scalars and arrays of class type with trivial move-assignment
8216 // operators.
8217 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8218 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8219 // Compute the size of the memory buffer to be copied.
8220 QualType SizeType = Context.getSizeType();
8221 llvm::APInt Size(Context.getTypeSize(SizeType),
8222 Context.getTypeSizeInChars(BaseType).getQuantity());
8223 for (const ConstantArrayType *Array
8224 = Context.getAsConstantArrayType(FieldType);
8225 Array;
8226 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8227 llvm::APInt ArraySize
8228 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8229 Size *= ArraySize;
8230 }
8231
Douglas Gregor45d3d712011-09-01 02:09:07 +00008232 // Take the address of the field references for "from" and "to". We
8233 // directly construct UnaryOperators here because semantic analysis
8234 // does not permit us to take the address of an xvalue.
8235 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8236 Context.getPointerType(From.get()->getType()),
8237 VK_RValue, OK_Ordinary, Loc);
8238 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8239 Context.getPointerType(To.get()->getType()),
8240 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008241
8242 bool NeedsCollectableMemCpy =
8243 (BaseType->isRecordType() &&
8244 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8245
8246 if (NeedsCollectableMemCpy) {
8247 if (!CollectableMemCpyRef) {
8248 // Create a reference to the __builtin_objc_memmove_collectable function.
8249 LookupResult R(*this,
8250 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8251 Loc, LookupOrdinaryName);
8252 LookupName(R, TUScope, true);
8253
8254 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8255 if (!CollectableMemCpy) {
8256 // Something went horribly wrong earlier, and we will have
8257 // complained about it.
8258 Invalid = true;
8259 continue;
8260 }
8261
8262 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8263 CollectableMemCpy->getType(),
8264 VK_LValue, Loc, 0).take();
8265 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8266 }
8267 }
8268 // Create a reference to the __builtin_memcpy builtin function.
8269 else if (!BuiltinMemCpyRef) {
8270 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8271 LookupOrdinaryName);
8272 LookupName(R, TUScope, true);
8273
8274 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8275 if (!BuiltinMemCpy) {
8276 // Something went horribly wrong earlier, and we will have complained
8277 // about it.
8278 Invalid = true;
8279 continue;
8280 }
8281
8282 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8283 BuiltinMemCpy->getType(),
8284 VK_LValue, Loc, 0).take();
8285 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8286 }
8287
8288 ASTOwningVector<Expr*> CallArgs(*this);
8289 CallArgs.push_back(To.takeAs<Expr>());
8290 CallArgs.push_back(From.takeAs<Expr>());
8291 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8292 ExprResult Call = ExprError();
8293 if (NeedsCollectableMemCpy)
8294 Call = ActOnCallExpr(/*Scope=*/0,
8295 CollectableMemCpyRef,
8296 Loc, move_arg(CallArgs),
8297 Loc);
8298 else
8299 Call = ActOnCallExpr(/*Scope=*/0,
8300 BuiltinMemCpyRef,
8301 Loc, move_arg(CallArgs),
8302 Loc);
8303
8304 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8305 Statements.push_back(Call.takeAs<Expr>());
8306 continue;
8307 }
8308
8309 // Build the move of this field.
8310 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8311 To.get(), From.get(),
8312 /*CopyingBaseSubobject=*/false,
8313 /*Copying=*/false);
8314 if (Move.isInvalid()) {
8315 Diag(CurrentLocation, diag::note_member_synthesized_at)
8316 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8317 MoveAssignOperator->setInvalidDecl();
8318 return;
8319 }
8320
8321 // Success! Record the copy.
8322 Statements.push_back(Move.takeAs<Stmt>());
8323 }
8324
8325 if (!Invalid) {
8326 // Add a "return *this;"
8327 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8328
8329 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8330 if (Return.isInvalid())
8331 Invalid = true;
8332 else {
8333 Statements.push_back(Return.takeAs<Stmt>());
8334
8335 if (Trap.hasErrorOccurred()) {
8336 Diag(CurrentLocation, diag::note_member_synthesized_at)
8337 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8338 Invalid = true;
8339 }
8340 }
8341 }
8342
8343 if (Invalid) {
8344 MoveAssignOperator->setInvalidDecl();
8345 return;
8346 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008347
8348 StmtResult Body;
8349 {
8350 CompoundScopeRAII CompoundScope(*this);
8351 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8352 /*isStmtExpr=*/false);
8353 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8354 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008355 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8356
8357 if (ASTMutationListener *L = getASTMutationListener()) {
8358 L->CompletedImplicitDefinition(MoveAssignOperator);
8359 }
8360}
8361
Sean Hunt49634cf2011-05-13 06:10:58 +00008362std::pair<Sema::ImplicitExceptionSpecification, bool>
8363Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008364 if (ClassDecl->isInvalidDecl())
8365 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8366
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008367 // C++ [class.copy]p5:
8368 // The implicitly-declared copy constructor for a class X will
8369 // have the form
8370 //
8371 // X::X(const X&)
8372 //
8373 // if
Sean Huntc530d172011-06-10 04:44:37 +00008374 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008375 bool HasConstCopyConstructor = true;
8376
8377 // -- each direct or virtual base class B of X has a copy
8378 // constructor whose first parameter is of type const B& or
8379 // const volatile B&, and
8380 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8381 BaseEnd = ClassDecl->bases_end();
8382 HasConstCopyConstructor && Base != BaseEnd;
8383 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008384 // Virtual bases are handled below.
8385 if (Base->isVirtual())
8386 continue;
8387
Douglas Gregor22584312010-07-02 23:41:54 +00008388 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008389 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008390 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8391 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008392 }
8393
8394 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8395 BaseEnd = ClassDecl->vbases_end();
8396 HasConstCopyConstructor && Base != BaseEnd;
8397 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008398 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008399 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008400 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8401 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008402 }
8403
8404 // -- for all the nonstatic data members of X that are of a
8405 // class type M (or array thereof), each such class type
8406 // has a copy constructor whose first parameter is of type
8407 // const M& or const volatile M&.
8408 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8409 FieldEnd = ClassDecl->field_end();
8410 HasConstCopyConstructor && Field != FieldEnd;
8411 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008412 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008413 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008414 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8415 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008416 }
8417 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008418 // Otherwise, the implicitly declared copy constructor will have
8419 // the form
8420 //
8421 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008422
Douglas Gregor0d405db2010-07-01 20:59:04 +00008423 // C++ [except.spec]p14:
8424 // An implicitly declared special member function (Clause 12) shall have an
8425 // exception-specification. [...]
8426 ImplicitExceptionSpecification ExceptSpec(Context);
8427 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8429 BaseEnd = ClassDecl->bases_end();
8430 Base != BaseEnd;
8431 ++Base) {
8432 // Virtual bases are handled below.
8433 if (Base->isVirtual())
8434 continue;
8435
Douglas Gregor22584312010-07-02 23:41:54 +00008436 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008437 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008438 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008439 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008440 ExceptSpec.CalledDecl(CopyConstructor);
8441 }
8442 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8443 BaseEnd = ClassDecl->vbases_end();
8444 Base != BaseEnd;
8445 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008446 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008447 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008448 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008449 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008450 ExceptSpec.CalledDecl(CopyConstructor);
8451 }
8452 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8453 FieldEnd = ClassDecl->field_end();
8454 Field != FieldEnd;
8455 ++Field) {
8456 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008457 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8458 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008459 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008460 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008461 }
8462 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008463
Sean Hunt49634cf2011-05-13 06:10:58 +00008464 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8465}
8466
8467CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8468 CXXRecordDecl *ClassDecl) {
8469 // C++ [class.copy]p4:
8470 // If the class definition does not explicitly declare a copy
8471 // constructor, one is declared implicitly.
8472
8473 ImplicitExceptionSpecification Spec(Context);
8474 bool Const;
8475 llvm::tie(Spec, Const) =
8476 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8477
8478 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8479 QualType ArgType = ClassType;
8480 if (Const)
8481 ArgType = ArgType.withConst();
8482 ArgType = Context.getLValueReferenceType(ArgType);
8483
8484 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8485
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008486 DeclarationName Name
8487 = Context.DeclarationNames.getCXXConstructorName(
8488 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008489 SourceLocation ClassLoc = ClassDecl->getLocation();
8490 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008491
8492 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008493 // member of its class.
8494 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8495 Context, ClassDecl, ClassLoc, NameInfo,
8496 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8497 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8498 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008499 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008500 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008501 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008502 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008503
Douglas Gregor22584312010-07-02 23:41:54 +00008504 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008505 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8506
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008507 // Add the parameter to the constructor.
8508 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008509 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008510 /*IdentifierInfo=*/0,
8511 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008512 SC_None,
8513 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008514 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008515
Douglas Gregor23c94db2010-07-02 17:43:08 +00008516 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008517 PushOnScopeChains(CopyConstructor, S, false);
8518 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008519
Nico Weberafcc96a2012-01-23 03:19:29 +00008520 // C++11 [class.copy]p8:
8521 // ... If the class definition does not explicitly declare a copy
8522 // constructor, there is no user-declared move constructor, and there is no
8523 // user-declared move assignment operator, a copy constructor is implicitly
8524 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008525 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008526 (ClassDecl->hasUserDeclaredMoveAssignment() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008527 !getLangOpts().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008528 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008529 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008530
8531 return CopyConstructor;
8532}
8533
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008534void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008535 CXXConstructorDecl *CopyConstructor) {
8536 assert((CopyConstructor->isDefaulted() &&
8537 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008538 !CopyConstructor->doesThisDeclarationHaveABody() &&
8539 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008540 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008541
Anders Carlsson63010a72010-04-23 16:24:12 +00008542 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008543 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008544
Douglas Gregor39957dc2010-05-01 15:04:51 +00008545 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008546 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008547
Sean Huntcbb67482011-01-08 20:30:50 +00008548 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008549 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008550 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008551 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008552 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008553 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008554 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008555 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8556 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008557 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008558 /*isStmtExpr=*/false)
8559 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008560 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008561 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008562
8563 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008564 if (ASTMutationListener *L = getASTMutationListener()) {
8565 L->CompletedImplicitDefinition(CopyConstructor);
8566 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008567}
8568
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008569Sema::ImplicitExceptionSpecification
8570Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8571 // C++ [except.spec]p14:
8572 // An implicitly declared special member function (Clause 12) shall have an
8573 // exception-specification. [...]
8574 ImplicitExceptionSpecification ExceptSpec(Context);
8575 if (ClassDecl->isInvalidDecl())
8576 return ExceptSpec;
8577
8578 // Direct base-class constructors.
8579 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8580 BEnd = ClassDecl->bases_end();
8581 B != BEnd; ++B) {
8582 if (B->isVirtual()) // Handled below.
8583 continue;
8584
8585 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8586 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8587 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8588 // If this is a deleted function, add it anyway. This might be conformant
8589 // with the standard. This might not. I'm not sure. It might not matter.
8590 if (Constructor)
8591 ExceptSpec.CalledDecl(Constructor);
8592 }
8593 }
8594
8595 // Virtual base-class constructors.
8596 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8597 BEnd = ClassDecl->vbases_end();
8598 B != BEnd; ++B) {
8599 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8600 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8601 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8602 // If this is a deleted function, add it anyway. This might be conformant
8603 // with the standard. This might not. I'm not sure. It might not matter.
8604 if (Constructor)
8605 ExceptSpec.CalledDecl(Constructor);
8606 }
8607 }
8608
8609 // Field constructors.
8610 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8611 FEnd = ClassDecl->field_end();
8612 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008613 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008614 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8615 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8616 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8617 // If this is a deleted function, add it anyway. This might be conformant
8618 // with the standard. This might not. I'm not sure. It might not matter.
8619 // In particular, the problem is that this function never gets called. It
8620 // might just be ill-formed because this function attempts to refer to
8621 // a deleted function here.
8622 if (Constructor)
8623 ExceptSpec.CalledDecl(Constructor);
8624 }
8625 }
8626
8627 return ExceptSpec;
8628}
8629
8630CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8631 CXXRecordDecl *ClassDecl) {
8632 ImplicitExceptionSpecification Spec(
8633 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8634
8635 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8636 QualType ArgType = Context.getRValueReferenceType(ClassType);
8637
8638 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8639
8640 DeclarationName Name
8641 = Context.DeclarationNames.getCXXConstructorName(
8642 Context.getCanonicalType(ClassType));
8643 SourceLocation ClassLoc = ClassDecl->getLocation();
8644 DeclarationNameInfo NameInfo(Name, ClassLoc);
8645
8646 // C++0x [class.copy]p11:
8647 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008648 // member of its class.
8649 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8650 Context, ClassDecl, ClassLoc, NameInfo,
8651 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8652 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8653 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008654 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008655 MoveConstructor->setAccess(AS_public);
8656 MoveConstructor->setDefaulted();
8657 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008658
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008659 // Add the parameter to the constructor.
8660 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8661 ClassLoc, ClassLoc,
8662 /*IdentifierInfo=*/0,
8663 ArgType, /*TInfo=*/0,
8664 SC_None,
8665 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008666 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008667
8668 // C++0x [class.copy]p9:
8669 // If the definition of a class X does not explicitly declare a move
8670 // constructor, one will be implicitly declared as defaulted if and only if:
8671 // [...]
8672 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008673 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008674 // Cache this result so that we don't try to generate this over and over
8675 // on every lookup, leaking memory and wasting time.
8676 ClassDecl->setFailedImplicitMoveConstructor();
8677 return 0;
8678 }
8679
8680 // Note that we have declared this constructor.
8681 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8682
8683 if (Scope *S = getScopeForContext(ClassDecl))
8684 PushOnScopeChains(MoveConstructor, S, false);
8685 ClassDecl->addDecl(MoveConstructor);
8686
8687 return MoveConstructor;
8688}
8689
8690void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8691 CXXConstructorDecl *MoveConstructor) {
8692 assert((MoveConstructor->isDefaulted() &&
8693 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008694 !MoveConstructor->doesThisDeclarationHaveABody() &&
8695 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008696 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8697
8698 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8699 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8700
8701 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8702 DiagnosticErrorTrap Trap(Diags);
8703
8704 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8705 Trap.hasErrorOccurred()) {
8706 Diag(CurrentLocation, diag::note_member_synthesized_at)
8707 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8708 MoveConstructor->setInvalidDecl();
8709 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008710 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008711 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8712 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008713 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008714 /*isStmtExpr=*/false)
8715 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008716 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008717 }
8718
8719 MoveConstructor->setUsed();
8720
8721 if (ASTMutationListener *L = getASTMutationListener()) {
8722 L->CompletedImplicitDefinition(MoveConstructor);
8723 }
8724}
8725
Douglas Gregore4e68d42012-02-15 19:33:52 +00008726bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8727 return FD->isDeleted() &&
8728 (FD->isDefaulted() || FD->isImplicit()) &&
8729 isa<CXXMethodDecl>(FD);
8730}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008731
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008732/// \brief Mark the call operator of the given lambda closure type as "used".
8733static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8734 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008735 = cast<CXXMethodDecl>(
8736 *Lambda->lookup(
8737 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008738 CallOperator->setReferenced();
8739 CallOperator->setUsed();
8740}
8741
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008742void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8743 SourceLocation CurrentLocation,
8744 CXXConversionDecl *Conv)
8745{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008746 CXXRecordDecl *Lambda = Conv->getParent();
8747
8748 // Make sure that the lambda call operator is marked used.
8749 markLambdaCallOperatorUsed(*this, Lambda);
8750
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008751 Conv->setUsed();
8752
8753 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8754 DiagnosticErrorTrap Trap(Diags);
8755
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008756 // Return the address of the __invoke function.
8757 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8758 CXXMethodDecl *Invoke
8759 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8760 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8761 VK_LValue, Conv->getLocation()).take();
8762 assert(FunctionRef && "Can't refer to __invoke function?");
8763 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8764 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8765 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008766 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008767
8768 // Fill in the __invoke function with a dummy implementation. IR generation
8769 // will fill in the actual details.
8770 Invoke->setUsed();
8771 Invoke->setReferenced();
8772 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8773 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008774
8775 if (ASTMutationListener *L = getASTMutationListener()) {
8776 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008777 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008778 }
8779}
8780
8781void Sema::DefineImplicitLambdaToBlockPointerConversion(
8782 SourceLocation CurrentLocation,
8783 CXXConversionDecl *Conv)
8784{
8785 Conv->setUsed();
8786
8787 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8788 DiagnosticErrorTrap Trap(Diags);
8789
Douglas Gregorac1303e2012-02-22 05:02:47 +00008790 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008791 Expr *This = ActOnCXXThis(CurrentLocation).take();
8792 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008793
Eli Friedman23f02672012-03-01 04:01:32 +00008794 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8795 Conv->getLocation(),
8796 Conv, DerefThis);
8797
8798 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8799 // behavior. Note that only the general conversion function does this
8800 // (since it's unusable otherwise); in the case where we inline the
8801 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008802 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008803 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8804 CK_CopyAndAutoreleaseBlockObject,
8805 BuildBlock.get(), 0, VK_RValue);
8806
8807 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008808 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008809 Conv->setInvalidDecl();
8810 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008811 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008812
Douglas Gregorac1303e2012-02-22 05:02:47 +00008813 // Create the return statement that returns the block from the conversion
8814 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008815 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008816 if (Return.isInvalid()) {
8817 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8818 Conv->setInvalidDecl();
8819 return;
8820 }
8821
8822 // Set the body of the conversion function.
8823 Stmt *ReturnS = Return.take();
8824 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8825 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008826 Conv->getLocation()));
8827
Douglas Gregorac1303e2012-02-22 05:02:47 +00008828 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008829 if (ASTMutationListener *L = getASTMutationListener()) {
8830 L->CompletedImplicitDefinition(Conv);
8831 }
8832}
8833
Douglas Gregorf52757d2012-03-10 06:53:13 +00008834/// \brief Determine whether the given list arguments contains exactly one
8835/// "real" (non-default) argument.
8836static bool hasOneRealArgument(MultiExprArg Args) {
8837 switch (Args.size()) {
8838 case 0:
8839 return false;
8840
8841 default:
8842 if (!Args.get()[1]->isDefaultArgument())
8843 return false;
8844
8845 // fall through
8846 case 1:
8847 return !Args.get()[0]->isDefaultArgument();
8848 }
8849
8850 return false;
8851}
8852
John McCall60d7b3a2010-08-24 06:29:42 +00008853ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008854Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008855 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008856 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008857 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008858 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008859 unsigned ConstructKind,
8860 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008861 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008862
Douglas Gregor2f599792010-04-02 18:24:57 +00008863 // C++0x [class.copy]p34:
8864 // When certain criteria are met, an implementation is allowed to
8865 // omit the copy/move construction of a class object, even if the
8866 // copy/move constructor and/or destructor for the object have
8867 // side effects. [...]
8868 // - when a temporary class object that has not been bound to a
8869 // reference (12.2) would be copied/moved to a class object
8870 // with the same cv-unqualified type, the copy/move operation
8871 // can be omitted by constructing the temporary object
8872 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008873 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00008874 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008875 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008876 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008877 }
Mike Stump1eb44332009-09-09 15:08:12 +00008878
8879 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008880 Elidable, move(ExprArgs), HadMultipleCandidates,
8881 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008882}
8883
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008884/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8885/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008886ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008887Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8888 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008889 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008890 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008891 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008892 unsigned ConstructKind,
8893 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008894 unsigned NumExprs = ExprArgs.size();
8895 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008896
Nick Lewycky909a70d2011-03-25 01:44:32 +00008897 for (specific_attr_iterator<NonNullAttr>
8898 i = Constructor->specific_attr_begin<NonNullAttr>(),
8899 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8900 const NonNullAttr *NonNull = *i;
8901 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8902 }
8903
Eli Friedman5f2987c2012-02-02 03:46:19 +00008904 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008905 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008906 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008907 HadMultipleCandidates, /*FIXME*/false,
8908 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008909 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8910 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008911}
8912
Mike Stump1eb44332009-09-09 15:08:12 +00008913bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008914 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008915 MultiExprArg Exprs,
8916 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008917 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008918 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008919 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008920 move(Exprs), HadMultipleCandidates, false,
8921 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008922 if (TempResult.isInvalid())
8923 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008924
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008925 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008926 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00008927 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008928 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008929 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008930
Anders Carlssonfe2de492009-08-25 05:18:00 +00008931 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008932}
8933
John McCall68c6c9a2010-02-02 09:10:11 +00008934void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008935 if (VD->isInvalidDecl()) return;
8936
John McCall68c6c9a2010-02-02 09:10:11 +00008937 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008938 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00008939 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008940 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008941
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008942 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00008943 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008944 CheckDestructorAccess(VD->getLocation(), Destructor,
8945 PDiag(diag::err_access_dtor_var)
8946 << VD->getDeclName()
8947 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00008948 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008949
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008950 if (!VD->hasGlobalStorage()) return;
8951
8952 // Emit warning for non-trivial dtor in global scope (a real global,
8953 // class-static, function-static).
8954 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8955
8956 // TODO: this should be re-enabled for static locals by !CXAAtExit
8957 if (!VD->isStaticLocal())
8958 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008959}
8960
Douglas Gregor39da0b82009-09-09 23:08:42 +00008961/// \brief Given a constructor and the set of arguments provided for the
8962/// constructor, convert the arguments and add any required default arguments
8963/// to form a proper call to this constructor.
8964///
8965/// \returns true if an error occurred, false otherwise.
8966bool
8967Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8968 MultiExprArg ArgsPtr,
8969 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00008970 ASTOwningVector<Expr*> &ConvertedArgs,
8971 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008972 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8973 unsigned NumArgs = ArgsPtr.size();
8974 Expr **Args = (Expr **)ArgsPtr.get();
8975
8976 const FunctionProtoType *Proto
8977 = Constructor->getType()->getAs<FunctionProtoType>();
8978 assert(Proto && "Constructor without a prototype?");
8979 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008980
8981 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008982 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008983 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008984 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008985 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008986
8987 VariadicCallType CallType =
8988 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008989 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008990 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8991 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00008992 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00008993 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00008994
8995 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
8996
8997 // FIXME: Missing call to CheckFunctionCall or equivalent
8998
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008999 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009000}
9001
Anders Carlsson20d45d22009-12-12 00:32:00 +00009002static inline bool
9003CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9004 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009005 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009006 if (isa<NamespaceDecl>(DC)) {
9007 return SemaRef.Diag(FnDecl->getLocation(),
9008 diag::err_operator_new_delete_declared_in_namespace)
9009 << FnDecl->getDeclName();
9010 }
9011
9012 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009013 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009014 return SemaRef.Diag(FnDecl->getLocation(),
9015 diag::err_operator_new_delete_declared_static)
9016 << FnDecl->getDeclName();
9017 }
9018
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009019 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009020}
9021
Anders Carlsson156c78e2009-12-13 17:53:43 +00009022static inline bool
9023CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9024 CanQualType ExpectedResultType,
9025 CanQualType ExpectedFirstParamType,
9026 unsigned DependentParamTypeDiag,
9027 unsigned InvalidParamTypeDiag) {
9028 QualType ResultType =
9029 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9030
9031 // Check that the result type is not dependent.
9032 if (ResultType->isDependentType())
9033 return SemaRef.Diag(FnDecl->getLocation(),
9034 diag::err_operator_new_delete_dependent_result_type)
9035 << FnDecl->getDeclName() << ExpectedResultType;
9036
9037 // Check that the result type is what we expect.
9038 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9039 return SemaRef.Diag(FnDecl->getLocation(),
9040 diag::err_operator_new_delete_invalid_result_type)
9041 << FnDecl->getDeclName() << ExpectedResultType;
9042
9043 // A function template must have at least 2 parameters.
9044 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9045 return SemaRef.Diag(FnDecl->getLocation(),
9046 diag::err_operator_new_delete_template_too_few_parameters)
9047 << FnDecl->getDeclName();
9048
9049 // The function decl must have at least 1 parameter.
9050 if (FnDecl->getNumParams() == 0)
9051 return SemaRef.Diag(FnDecl->getLocation(),
9052 diag::err_operator_new_delete_too_few_parameters)
9053 << FnDecl->getDeclName();
9054
9055 // Check the the first parameter type is not dependent.
9056 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9057 if (FirstParamType->isDependentType())
9058 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9059 << FnDecl->getDeclName() << ExpectedFirstParamType;
9060
9061 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009062 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009063 ExpectedFirstParamType)
9064 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9065 << FnDecl->getDeclName() << ExpectedFirstParamType;
9066
9067 return false;
9068}
9069
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009070static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009071CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009072 // C++ [basic.stc.dynamic.allocation]p1:
9073 // A program is ill-formed if an allocation function is declared in a
9074 // namespace scope other than global scope or declared static in global
9075 // scope.
9076 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9077 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009078
9079 CanQualType SizeTy =
9080 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9081
9082 // C++ [basic.stc.dynamic.allocation]p1:
9083 // The return type shall be void*. The first parameter shall have type
9084 // std::size_t.
9085 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9086 SizeTy,
9087 diag::err_operator_new_dependent_param_type,
9088 diag::err_operator_new_param_type))
9089 return true;
9090
9091 // C++ [basic.stc.dynamic.allocation]p1:
9092 // The first parameter shall not have an associated default argument.
9093 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009094 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009095 diag::err_operator_new_default_arg)
9096 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9097
9098 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009099}
9100
9101static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009102CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9103 // C++ [basic.stc.dynamic.deallocation]p1:
9104 // A program is ill-formed if deallocation functions are declared in a
9105 // namespace scope other than global scope or declared static in global
9106 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009107 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9108 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009109
9110 // C++ [basic.stc.dynamic.deallocation]p2:
9111 // Each deallocation function shall return void and its first parameter
9112 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009113 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9114 SemaRef.Context.VoidPtrTy,
9115 diag::err_operator_delete_dependent_param_type,
9116 diag::err_operator_delete_param_type))
9117 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009118
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009119 return false;
9120}
9121
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009122/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9123/// of this overloaded operator is well-formed. If so, returns false;
9124/// otherwise, emits appropriate diagnostics and returns true.
9125bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009126 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009127 "Expected an overloaded operator declaration");
9128
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009129 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9130
Mike Stump1eb44332009-09-09 15:08:12 +00009131 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009132 // The allocation and deallocation functions, operator new,
9133 // operator new[], operator delete and operator delete[], are
9134 // described completely in 3.7.3. The attributes and restrictions
9135 // found in the rest of this subclause do not apply to them unless
9136 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009137 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009138 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009139
Anders Carlssona3ccda52009-12-12 00:26:23 +00009140 if (Op == OO_New || Op == OO_Array_New)
9141 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009142
9143 // C++ [over.oper]p6:
9144 // An operator function shall either be a non-static member
9145 // function or be a non-member function and have at least one
9146 // parameter whose type is a class, a reference to a class, an
9147 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009148 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9149 if (MethodDecl->isStatic())
9150 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009151 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009152 } else {
9153 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009154 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9155 ParamEnd = FnDecl->param_end();
9156 Param != ParamEnd; ++Param) {
9157 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009158 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9159 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009160 ClassOrEnumParam = true;
9161 break;
9162 }
9163 }
9164
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009165 if (!ClassOrEnumParam)
9166 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009167 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009168 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009169 }
9170
9171 // C++ [over.oper]p8:
9172 // An operator function cannot have default arguments (8.3.6),
9173 // except where explicitly stated below.
9174 //
Mike Stump1eb44332009-09-09 15:08:12 +00009175 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009176 // (C++ [over.call]p1).
9177 if (Op != OO_Call) {
9178 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9179 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009180 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009181 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009182 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009183 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009184 }
9185 }
9186
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009187 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9188 { false, false, false }
9189#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9190 , { Unary, Binary, MemberOnly }
9191#include "clang/Basic/OperatorKinds.def"
9192 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009193
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009194 bool CanBeUnaryOperator = OperatorUses[Op][0];
9195 bool CanBeBinaryOperator = OperatorUses[Op][1];
9196 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009197
9198 // C++ [over.oper]p8:
9199 // [...] Operator functions cannot have more or fewer parameters
9200 // than the number required for the corresponding operator, as
9201 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009202 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009203 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009204 if (Op != OO_Call &&
9205 ((NumParams == 1 && !CanBeUnaryOperator) ||
9206 (NumParams == 2 && !CanBeBinaryOperator) ||
9207 (NumParams < 1) || (NumParams > 2))) {
9208 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009209 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009210 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009211 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009212 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009213 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009214 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009215 assert(CanBeBinaryOperator &&
9216 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009217 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009218 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009219
Chris Lattner416e46f2008-11-21 07:57:12 +00009220 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009221 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009222 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009223
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009224 // Overloaded operators other than operator() cannot be variadic.
9225 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009226 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009227 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009228 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009229 }
9230
9231 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009232 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9233 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009234 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009235 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009236 }
9237
9238 // C++ [over.inc]p1:
9239 // The user-defined function called operator++ implements the
9240 // prefix and postfix ++ operator. If this function is a member
9241 // function with no parameters, or a non-member function with one
9242 // parameter of class or enumeration type, it defines the prefix
9243 // increment operator ++ for objects of that type. If the function
9244 // is a member function with one parameter (which shall be of type
9245 // int) or a non-member function with two parameters (the second
9246 // of which shall be of type int), it defines the postfix
9247 // increment operator ++ for objects of that type.
9248 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9249 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9250 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009251 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009252 ParamIsInt = BT->getKind() == BuiltinType::Int;
9253
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009254 if (!ParamIsInt)
9255 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009256 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009257 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009258 }
9259
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009260 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009261}
Chris Lattner5a003a42008-12-17 07:09:26 +00009262
Sean Hunta6c058d2010-01-13 09:01:02 +00009263/// CheckLiteralOperatorDeclaration - Check whether the declaration
9264/// of this literal operator function is well-formed. If so, returns
9265/// false; otherwise, emits appropriate diagnostics and returns true.
9266bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009267 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009268 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9269 << FnDecl->getDeclName();
9270 return true;
9271 }
9272
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009273 if (FnDecl->isExternC()) {
9274 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9275 return true;
9276 }
9277
Sean Hunta6c058d2010-01-13 09:01:02 +00009278 bool Valid = false;
9279
Richard Smith36f5cfe2012-03-09 08:00:36 +00009280 // This might be the definition of a literal operator template.
9281 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9282 // This might be a specialization of a literal operator template.
9283 if (!TpDecl)
9284 TpDecl = FnDecl->getPrimaryTemplate();
9285
Sean Hunt216c2782010-04-07 23:11:06 +00009286 // template <char...> type operator "" name() is the only valid template
9287 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009288 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009289 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009290 // Must have only one template parameter
9291 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9292 if (Params->size() == 1) {
9293 NonTypeTemplateParmDecl *PmDecl =
9294 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009295
Sean Hunt216c2782010-04-07 23:11:06 +00009296 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009297 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9298 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9299 Valid = true;
9300 }
9301 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009302 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009303 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009304 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9305
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009306 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009307
Sean Hunt30019c02010-04-07 22:57:35 +00009308 // unsigned long long int, long double, and any character type are allowed
9309 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009310 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9311 Context.hasSameType(T, Context.LongDoubleTy) ||
9312 Context.hasSameType(T, Context.CharTy) ||
9313 Context.hasSameType(T, Context.WCharTy) ||
9314 Context.hasSameType(T, Context.Char16Ty) ||
9315 Context.hasSameType(T, Context.Char32Ty)) {
9316 if (++Param == FnDecl->param_end())
9317 Valid = true;
9318 goto FinishedParams;
9319 }
9320
Sean Hunt30019c02010-04-07 22:57:35 +00009321 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009322 const PointerType *PT = T->getAs<PointerType>();
9323 if (!PT)
9324 goto FinishedParams;
9325 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009326 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009327 goto FinishedParams;
9328 T = T.getUnqualifiedType();
9329
9330 // Move on to the second parameter;
9331 ++Param;
9332
9333 // If there is no second parameter, the first must be a const char *
9334 if (Param == FnDecl->param_end()) {
9335 if (Context.hasSameType(T, Context.CharTy))
9336 Valid = true;
9337 goto FinishedParams;
9338 }
9339
9340 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9341 // are allowed as the first parameter to a two-parameter function
9342 if (!(Context.hasSameType(T, Context.CharTy) ||
9343 Context.hasSameType(T, Context.WCharTy) ||
9344 Context.hasSameType(T, Context.Char16Ty) ||
9345 Context.hasSameType(T, Context.Char32Ty)))
9346 goto FinishedParams;
9347
9348 // The second and final parameter must be an std::size_t
9349 T = (*Param)->getType().getUnqualifiedType();
9350 if (Context.hasSameType(T, Context.getSizeType()) &&
9351 ++Param == FnDecl->param_end())
9352 Valid = true;
9353 }
9354
9355 // FIXME: This diagnostic is absolutely terrible.
9356FinishedParams:
9357 if (!Valid) {
9358 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9359 << FnDecl->getDeclName();
9360 return true;
9361 }
9362
Richard Smitha9e88b22012-03-09 08:16:22 +00009363 // A parameter-declaration-clause containing a default argument is not
9364 // equivalent to any of the permitted forms.
9365 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9366 ParamEnd = FnDecl->param_end();
9367 Param != ParamEnd; ++Param) {
9368 if ((*Param)->hasDefaultArg()) {
9369 Diag((*Param)->getDefaultArgRange().getBegin(),
9370 diag::err_literal_operator_default_argument)
9371 << (*Param)->getDefaultArgRange();
9372 break;
9373 }
9374 }
9375
Richard Smith2fb4ae32012-03-08 02:39:21 +00009376 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009377 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9378 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009379 // C++11 [usrlit.suffix]p1:
9380 // Literal suffix identifiers that do not start with an underscore
9381 // are reserved for future standardization.
9382 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009383 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009384
Sean Hunta6c058d2010-01-13 09:01:02 +00009385 return false;
9386}
9387
Douglas Gregor074149e2009-01-05 19:45:36 +00009388/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9389/// linkage specification, including the language and (if present)
9390/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9391/// the location of the language string literal, which is provided
9392/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9393/// the '{' brace. Otherwise, this linkage specification does not
9394/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009395Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9396 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009397 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009398 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009399 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009400 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009401 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009402 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009403 Language = LinkageSpecDecl::lang_cxx;
9404 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009405 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009406 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009407 }
Mike Stump1eb44332009-09-09 15:08:12 +00009408
Chris Lattnercc98eac2008-12-17 07:13:27 +00009409 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009410
Douglas Gregor074149e2009-01-05 19:45:36 +00009411 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009412 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009413 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009414 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009415 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009416}
9417
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009418/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009419/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9420/// valid, it's the position of the closing '}' brace in a linkage
9421/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009422Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009423 Decl *LinkageSpec,
9424 SourceLocation RBraceLoc) {
9425 if (LinkageSpec) {
9426 if (RBraceLoc.isValid()) {
9427 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9428 LSDecl->setRBraceLoc(RBraceLoc);
9429 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009430 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009431 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009432 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009433}
9434
Douglas Gregord308e622009-05-18 20:51:54 +00009435/// \brief Perform semantic analysis for the variable declaration that
9436/// occurs within a C++ catch clause, returning the newly-created
9437/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009438VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009439 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009440 SourceLocation StartLoc,
9441 SourceLocation Loc,
9442 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009443 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009444 QualType ExDeclType = TInfo->getType();
9445
Sebastian Redl4b07b292008-12-22 19:15:10 +00009446 // Arrays and functions decay.
9447 if (ExDeclType->isArrayType())
9448 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9449 else if (ExDeclType->isFunctionType())
9450 ExDeclType = Context.getPointerType(ExDeclType);
9451
9452 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9453 // The exception-declaration shall not denote a pointer or reference to an
9454 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009455 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009456 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009457 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009458 Invalid = true;
9459 }
Douglas Gregord308e622009-05-18 20:51:54 +00009460
Sebastian Redl4b07b292008-12-22 19:15:10 +00009461 QualType BaseType = ExDeclType;
9462 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009463 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009464 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009465 BaseType = Ptr->getPointeeType();
9466 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009467 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009468 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009469 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009470 BaseType = Ref->getPointeeType();
9471 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009472 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009473 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009474 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009475 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009476 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009477
Mike Stump1eb44332009-09-09 15:08:12 +00009478 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009479 RequireNonAbstractType(Loc, ExDeclType,
9480 diag::err_abstract_type_in_decl,
9481 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009482 Invalid = true;
9483
John McCall5a180392010-07-24 00:37:23 +00009484 // Only the non-fragile NeXT runtime currently supports C++ catches
9485 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009486 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009487 QualType T = ExDeclType;
9488 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9489 T = RT->getPointeeType();
9490
9491 if (T->isObjCObjectType()) {
9492 Diag(Loc, diag::err_objc_object_catch);
9493 Invalid = true;
9494 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009495 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009496 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009497 }
9498 }
9499
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009500 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9501 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009502 ExDecl->setExceptionVariable(true);
9503
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009504 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009505 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009506 Invalid = true;
9507
Douglas Gregorc41b8782011-07-06 18:14:43 +00009508 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009509 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009510 // C++ [except.handle]p16:
9511 // The object declared in an exception-declaration or, if the
9512 // exception-declaration does not specify a name, a temporary (12.2) is
9513 // copy-initialized (8.5) from the exception object. [...]
9514 // The object is destroyed when the handler exits, after the destruction
9515 // of any automatic objects initialized within the handler.
9516 //
9517 // We just pretend to initialize the object with itself, then make sure
9518 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009519 QualType initType = ExDeclType;
9520
9521 InitializedEntity entity =
9522 InitializedEntity::InitializeVariable(ExDecl);
9523 InitializationKind initKind =
9524 InitializationKind::CreateCopy(Loc, SourceLocation());
9525
9526 Expr *opaqueValue =
9527 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9528 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9529 ExprResult result = sequence.Perform(*this, entity, initKind,
9530 MultiExprArg(&opaqueValue, 1));
9531 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009532 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009533 else {
9534 // If the constructor used was non-trivial, set this as the
9535 // "initializer".
9536 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9537 if (!construct->getConstructor()->isTrivial()) {
9538 Expr *init = MaybeCreateExprWithCleanups(construct);
9539 ExDecl->setInit(init);
9540 }
9541
9542 // And make sure it's destructable.
9543 FinalizeVarWithDestructor(ExDecl, recordType);
9544 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009545 }
9546 }
9547
Douglas Gregord308e622009-05-18 20:51:54 +00009548 if (Invalid)
9549 ExDecl->setInvalidDecl();
9550
9551 return ExDecl;
9552}
9553
9554/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9555/// handler.
John McCalld226f652010-08-21 09:40:31 +00009556Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009557 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009558 bool Invalid = D.isInvalidType();
9559
9560 // Check for unexpanded parameter packs.
9561 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9562 UPPC_ExceptionType)) {
9563 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9564 D.getIdentifierLoc());
9565 Invalid = true;
9566 }
9567
Sebastian Redl4b07b292008-12-22 19:15:10 +00009568 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009569 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009570 LookupOrdinaryName,
9571 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009572 // The scope should be freshly made just for us. There is just no way
9573 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009574 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009575 if (PrevDecl->isTemplateParameter()) {
9576 // Maybe we will complain about the shadowed template parameter.
9577 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009578 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009579 }
9580 }
9581
Chris Lattnereaaebc72009-04-25 08:06:05 +00009582 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009583 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9584 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009585 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009586 }
9587
Douglas Gregor83cb9422010-09-09 17:09:21 +00009588 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009589 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009590 D.getIdentifierLoc(),
9591 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009592 if (Invalid)
9593 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009594
Sebastian Redl4b07b292008-12-22 19:15:10 +00009595 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009596 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009597 PushOnScopeChains(ExDecl, S);
9598 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009599 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009600
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009601 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009602 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009603}
Anders Carlssonfb311762009-03-14 00:25:26 +00009604
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009605Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009606 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009607 Expr *AssertMessageExpr_,
9608 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009609 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009610
Anders Carlssonc3082412009-03-14 00:33:21 +00009611 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009612 // In a static_assert-declaration, the constant-expression shall be a
9613 // constant expression that can be contextually converted to bool.
9614 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9615 if (Converted.isInvalid())
9616 return 0;
9617
Richard Smithdaaefc52011-12-14 23:32:26 +00009618 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009619 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9620 PDiag(diag::err_static_assert_expression_is_not_constant),
9621 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009622 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009623
Richard Smith0cc323c2012-03-05 23:20:05 +00009624 if (!Cond) {
9625 llvm::SmallString<256> MsgBuffer;
9626 llvm::raw_svector_ostream Msg(MsgBuffer);
9627 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009628 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009629 << Msg.str() << AssertExpr->getSourceRange();
9630 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009631 }
Mike Stump1eb44332009-09-09 15:08:12 +00009632
Douglas Gregor399ad972010-12-15 23:55:21 +00009633 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9634 return 0;
9635
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009636 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9637 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009638
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009639 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009640 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009641}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009642
Douglas Gregor1d869352010-04-07 16:53:43 +00009643/// \brief Perform semantic analysis of the given friend type declaration.
9644///
9645/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009646FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9647 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009648 TypeSourceInfo *TSInfo) {
9649 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9650
9651 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009652 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009653
Richard Smith6b130222011-10-18 21:39:00 +00009654 // C++03 [class.friend]p2:
9655 // An elaborated-type-specifier shall be used in a friend declaration
9656 // for a class.*
9657 //
9658 // * The class-key of the elaborated-type-specifier is required.
9659 if (!ActiveTemplateInstantiations.empty()) {
9660 // Do not complain about the form of friend template types during
9661 // template instantiation; we will already have complained when the
9662 // template was declared.
9663 } else if (!T->isElaboratedTypeSpecifier()) {
9664 // If we evaluated the type to a record type, suggest putting
9665 // a tag in front.
9666 if (const RecordType *RT = T->getAs<RecordType>()) {
9667 RecordDecl *RD = RT->getDecl();
9668
9669 std::string InsertionText = std::string(" ") + RD->getKindName();
9670
9671 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009672 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009673 diag::warn_cxx98_compat_unelaborated_friend_type :
9674 diag::ext_unelaborated_friend_type)
9675 << (unsigned) RD->getTagKind()
9676 << T
9677 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9678 InsertionText);
9679 } else {
9680 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009681 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009682 diag::warn_cxx98_compat_nonclass_type_friend :
9683 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009684 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009685 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009686 }
Richard Smith6b130222011-10-18 21:39:00 +00009687 } else if (T->getAs<EnumType>()) {
9688 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009689 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009690 diag::warn_cxx98_compat_enum_friend :
9691 diag::ext_enum_friend)
9692 << T
9693 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009694 }
9695
Douglas Gregor06245bf2010-04-07 17:57:12 +00009696 // C++0x [class.friend]p3:
9697 // If the type specifier in a friend declaration designates a (possibly
9698 // cv-qualified) class type, that class is declared as a friend; otherwise,
9699 // the friend declaration is ignored.
9700
9701 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9702 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009703
Abramo Bagnara0216df82011-10-29 20:52:52 +00009704 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009705}
9706
John McCall9a34edb2010-10-19 01:40:49 +00009707/// Handle a friend tag declaration where the scope specifier was
9708/// templated.
9709Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9710 unsigned TagSpec, SourceLocation TagLoc,
9711 CXXScopeSpec &SS,
9712 IdentifierInfo *Name, SourceLocation NameLoc,
9713 AttributeList *Attr,
9714 MultiTemplateParamsArg TempParamLists) {
9715 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9716
9717 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009718 bool Invalid = false;
9719
9720 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009721 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009722 TempParamLists.get(),
9723 TempParamLists.size(),
9724 /*friend*/ true,
9725 isExplicitSpecialization,
9726 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009727 if (TemplateParams->size() > 0) {
9728 // This is a declaration of a class template.
9729 if (Invalid)
9730 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009731
Eric Christopher4110e132011-07-21 05:34:24 +00009732 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9733 SS, Name, NameLoc, Attr,
9734 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009735 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009736 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009737 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009738 } else {
9739 // The "template<>" header is extraneous.
9740 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9741 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9742 isExplicitSpecialization = true;
9743 }
9744 }
9745
9746 if (Invalid) return 0;
9747
John McCall9a34edb2010-10-19 01:40:49 +00009748 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009749 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009750 if (TempParamLists.get()[I]->size()) {
9751 isAllExplicitSpecializations = false;
9752 break;
9753 }
9754 }
9755
9756 // FIXME: don't ignore attributes.
9757
9758 // If it's explicit specializations all the way down, just forget
9759 // about the template header and build an appropriate non-templated
9760 // friend. TODO: for source fidelity, remember the headers.
9761 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009762 if (SS.isEmpty()) {
9763 bool Owned = false;
9764 bool IsDependent = false;
9765 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9766 Attr, AS_public,
9767 /*ModulePrivateLoc=*/SourceLocation(),
9768 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009769 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009770 /*ScopedEnumUsesClassTag=*/false,
9771 /*UnderlyingType=*/TypeResult());
9772 }
9773
Douglas Gregor2494dd02011-03-01 01:34:45 +00009774 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009775 ElaboratedTypeKeyword Keyword
9776 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009777 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009778 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009779 if (T.isNull())
9780 return 0;
9781
9782 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9783 if (isa<DependentNameType>(T)) {
9784 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009785 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009786 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009787 TL.setNameLoc(NameLoc);
9788 } else {
9789 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009790 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009791 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009792 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9793 }
9794
9795 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9796 TSI, FriendLoc);
9797 Friend->setAccess(AS_public);
9798 CurContext->addDecl(Friend);
9799 return Friend;
9800 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009801
9802 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9803
9804
John McCall9a34edb2010-10-19 01:40:49 +00009805
9806 // Handle the case of a templated-scope friend class. e.g.
9807 // template <class T> class A<T>::B;
9808 // FIXME: we don't support these right now.
9809 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9810 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9811 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9812 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009813 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009814 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009815 TL.setNameLoc(NameLoc);
9816
9817 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9818 TSI, FriendLoc);
9819 Friend->setAccess(AS_public);
9820 Friend->setUnsupportedFriend(true);
9821 CurContext->addDecl(Friend);
9822 return Friend;
9823}
9824
9825
John McCalldd4a3b02009-09-16 22:47:08 +00009826/// Handle a friend type declaration. This works in tandem with
9827/// ActOnTag.
9828///
9829/// Notes on friend class templates:
9830///
9831/// We generally treat friend class declarations as if they were
9832/// declaring a class. So, for example, the elaborated type specifier
9833/// in a friend declaration is required to obey the restrictions of a
9834/// class-head (i.e. no typedefs in the scope chain), template
9835/// parameters are required to match up with simple template-ids, &c.
9836/// However, unlike when declaring a template specialization, it's
9837/// okay to refer to a template specialization without an empty
9838/// template parameter declaration, e.g.
9839/// friend class A<T>::B<unsigned>;
9840/// We permit this as a special case; if there are any template
9841/// parameters present at all, require proper matching, i.e.
9842/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009843Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009844 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009845 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009846
9847 assert(DS.isFriendSpecified());
9848 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9849
John McCalldd4a3b02009-09-16 22:47:08 +00009850 // Try to convert the decl specifier to a type. This works for
9851 // friend templates because ActOnTag never produces a ClassTemplateDecl
9852 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009853 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009854 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9855 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009856 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009857 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009858
Douglas Gregor6ccab972010-12-16 01:14:37 +00009859 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9860 return 0;
9861
John McCalldd4a3b02009-09-16 22:47:08 +00009862 // This is definitely an error in C++98. It's probably meant to
9863 // be forbidden in C++0x, too, but the specification is just
9864 // poorly written.
9865 //
9866 // The problem is with declarations like the following:
9867 // template <T> friend A<T>::foo;
9868 // where deciding whether a class C is a friend or not now hinges
9869 // on whether there exists an instantiation of A that causes
9870 // 'foo' to equal C. There are restrictions on class-heads
9871 // (which we declare (by fiat) elaborated friend declarations to
9872 // be) that makes this tractable.
9873 //
9874 // FIXME: handle "template <> friend class A<T>;", which
9875 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009876 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009877 Diag(Loc, diag::err_tagless_friend_type_template)
9878 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009879 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009880 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009881
John McCall02cace72009-08-28 07:59:38 +00009882 // C++98 [class.friend]p1: A friend of a class is a function
9883 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009884 // This is fixed in DR77, which just barely didn't make the C++03
9885 // deadline. It's also a very silly restriction that seriously
9886 // affects inner classes and which nobody else seems to implement;
9887 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009888 //
9889 // But note that we could warn about it: it's always useless to
9890 // friend one of your own members (it's not, however, worthless to
9891 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009892
John McCalldd4a3b02009-09-16 22:47:08 +00009893 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009894 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009895 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009896 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009897 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009898 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009899 DS.getFriendSpecLoc());
9900 else
Abramo Bagnara0216df82011-10-29 20:52:52 +00009901 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +00009902
9903 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009904 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009905
John McCalldd4a3b02009-09-16 22:47:08 +00009906 D->setAccess(AS_public);
9907 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009908
John McCalld226f652010-08-21 09:40:31 +00009909 return D;
John McCall02cace72009-08-28 07:59:38 +00009910}
9911
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009912Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +00009913 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009914 const DeclSpec &DS = D.getDeclSpec();
9915
9916 assert(DS.isFriendSpecified());
9917 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9918
9919 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009920 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +00009921
9922 // C++ [class.friend]p1
9923 // A friend of a class is a function or class....
9924 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009925 // It *doesn't* see through dependent types, which is correct
9926 // according to [temp.arg.type]p3:
9927 // If a declaration acquires a function type through a
9928 // type dependent on a template-parameter and this causes
9929 // a declaration that does not use the syntactic form of a
9930 // function declarator to have a function type, the program
9931 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009932 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +00009933 Diag(Loc, diag::err_unexpected_friend);
9934
9935 // It might be worthwhile to try to recover by creating an
9936 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009937 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009938 }
9939
9940 // C++ [namespace.memdef]p3
9941 // - If a friend declaration in a non-local class first declares a
9942 // class or function, the friend class or function is a member
9943 // of the innermost enclosing namespace.
9944 // - The name of the friend is not found by simple name lookup
9945 // until a matching declaration is provided in that namespace
9946 // scope (either before or after the class declaration granting
9947 // friendship).
9948 // - If a friend function is called, its name may be found by the
9949 // name lookup that considers functions from namespaces and
9950 // classes associated with the types of the function arguments.
9951 // - When looking for a prior declaration of a class or a function
9952 // declared as a friend, scopes outside the innermost enclosing
9953 // namespace scope are not considered.
9954
John McCall337ec3d2010-10-12 23:13:28 +00009955 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009956 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9957 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009958 assert(Name);
9959
Douglas Gregor6ccab972010-12-16 01:14:37 +00009960 // Check for unexpanded parameter packs.
9961 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9962 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9963 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9964 return 0;
9965
John McCall67d1a672009-08-06 02:15:43 +00009966 // The context we found the declaration in, or in which we should
9967 // create the declaration.
9968 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009969 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009970 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009971 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009972
John McCall337ec3d2010-10-12 23:13:28 +00009973 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009974
John McCall337ec3d2010-10-12 23:13:28 +00009975 // There are four cases here.
9976 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009977 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009978 // there as appropriate.
9979 // Recover from invalid scope qualifiers as if they just weren't there.
9980 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009981 // C++0x [namespace.memdef]p3:
9982 // If the name in a friend declaration is neither qualified nor
9983 // a template-id and the declaration is a function or an
9984 // elaborated-type-specifier, the lookup to determine whether
9985 // the entity has been previously declared shall not consider
9986 // any scopes outside the innermost enclosing namespace.
9987 // C++0x [class.friend]p11:
9988 // If a friend declaration appears in a local class and the name
9989 // specified is an unqualified name, a prior declaration is
9990 // looked up without considering scopes that are outside the
9991 // innermost enclosing non-class scope. For a friend function
9992 // declaration, if there is no prior declaration, the program is
9993 // ill-formed.
9994 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009995 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009996
John McCall29ae6e52010-10-13 05:45:15 +00009997 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009998 DC = CurContext;
9999 while (true) {
10000 // Skip class contexts. If someone can cite chapter and verse
10001 // for this behavior, that would be nice --- it's what GCC and
10002 // EDG do, and it seems like a reasonable intent, but the spec
10003 // really only says that checks for unqualified existing
10004 // declarations should stop at the nearest enclosing namespace,
10005 // not that they should only consider the nearest enclosing
10006 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010007 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010008 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010009
John McCall68263142009-11-18 22:49:29 +000010010 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010011
10012 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010013 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010014 break;
John McCall29ae6e52010-10-13 05:45:15 +000010015
John McCall8a407372010-10-14 22:22:28 +000010016 if (isTemplateId) {
10017 if (isa<TranslationUnitDecl>(DC)) break;
10018 } else {
10019 if (DC->isFileContext()) break;
10020 }
John McCall67d1a672009-08-06 02:15:43 +000010021 DC = DC->getParent();
10022 }
10023
10024 // C++ [class.friend]p1: A friend of a class is a function or
10025 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010026 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010027 // Most C++ 98 compilers do seem to give an error here, so
10028 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010029 if (!Previous.empty() && DC->Equals(CurContext))
10030 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010031 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010032 diag::warn_cxx98_compat_friend_is_member :
10033 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010034
John McCall380aaa42010-10-13 06:22:15 +000010035 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010036
Douglas Gregor883af832011-10-10 01:11:59 +000010037 // C++ [class.friend]p6:
10038 // A function can be defined in a friend declaration of a class if and
10039 // only if the class is a non-local class (9.8), the function name is
10040 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010041 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010042 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10043 }
10044
John McCall337ec3d2010-10-12 23:13:28 +000010045 // - There's a non-dependent scope specifier, in which case we
10046 // compute it and do a previous lookup there for a function
10047 // or function template.
10048 } else if (!SS.getScopeRep()->isDependent()) {
10049 DC = computeDeclContext(SS);
10050 if (!DC) return 0;
10051
10052 if (RequireCompleteDeclContext(SS, DC)) return 0;
10053
10054 LookupQualifiedName(Previous, DC);
10055
10056 // Ignore things found implicitly in the wrong scope.
10057 // TODO: better diagnostics for this case. Suggesting the right
10058 // qualified scope would be nice...
10059 LookupResult::Filter F = Previous.makeFilter();
10060 while (F.hasNext()) {
10061 NamedDecl *D = F.next();
10062 if (!DC->InEnclosingNamespaceSetOf(
10063 D->getDeclContext()->getRedeclContext()))
10064 F.erase();
10065 }
10066 F.done();
10067
10068 if (Previous.empty()) {
10069 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010070 Diag(Loc, diag::err_qualified_friend_not_found)
10071 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010072 return 0;
10073 }
10074
10075 // C++ [class.friend]p1: A friend of a class is a function or
10076 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010077 if (DC->Equals(CurContext))
10078 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010079 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010080 diag::warn_cxx98_compat_friend_is_member :
10081 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010082
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010083 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010084 // C++ [class.friend]p6:
10085 // A function can be defined in a friend declaration of a class if and
10086 // only if the class is a non-local class (9.8), the function name is
10087 // unqualified, and the function has namespace scope.
10088 SemaDiagnosticBuilder DB
10089 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10090
10091 DB << SS.getScopeRep();
10092 if (DC->isFileContext())
10093 DB << FixItHint::CreateRemoval(SS.getRange());
10094 SS.clear();
10095 }
John McCall337ec3d2010-10-12 23:13:28 +000010096
10097 // - There's a scope specifier that does not match any template
10098 // parameter lists, in which case we use some arbitrary context,
10099 // create a method or method template, and wait for instantiation.
10100 // - There's a scope specifier that does match some template
10101 // parameter lists, which we don't handle right now.
10102 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010103 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010104 // C++ [class.friend]p6:
10105 // A function can be defined in a friend declaration of a class if and
10106 // only if the class is a non-local class (9.8), the function name is
10107 // unqualified, and the function has namespace scope.
10108 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10109 << SS.getScopeRep();
10110 }
10111
John McCall337ec3d2010-10-12 23:13:28 +000010112 DC = CurContext;
10113 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010114 }
Douglas Gregor883af832011-10-10 01:11:59 +000010115
John McCall29ae6e52010-10-13 05:45:15 +000010116 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010117 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010118 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10119 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10120 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010121 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010122 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10123 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010124 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010125 }
John McCall67d1a672009-08-06 02:15:43 +000010126 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010127
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010128 // FIXME: This is an egregious hack to cope with cases where the scope stack
10129 // does not contain the declaration context, i.e., in an out-of-line
10130 // definition of a class.
10131 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10132 if (!DCScope) {
10133 FakeDCScope.setEntity(DC);
10134 DCScope = &FakeDCScope;
10135 }
10136
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010137 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010138 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10139 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010140 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010141
Douglas Gregor182ddf02009-09-28 00:08:27 +000010142 assert(ND->getDeclContext() == DC);
10143 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010144
John McCallab88d972009-08-31 22:39:49 +000010145 // Add the function declaration to the appropriate lookup tables,
10146 // adjusting the redeclarations list as necessary. We don't
10147 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010148 //
John McCallab88d972009-08-31 22:39:49 +000010149 // Also update the scope-based lookup if the target context's
10150 // lookup context is in lexical scope.
10151 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010152 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010153 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010154 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010155 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010156 }
John McCall02cace72009-08-28 07:59:38 +000010157
10158 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010159 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010160 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010161 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010162 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010163
John McCall337ec3d2010-10-12 23:13:28 +000010164 if (ND->isInvalidDecl())
10165 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010166 else {
10167 FunctionDecl *FD;
10168 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10169 FD = FTD->getTemplatedDecl();
10170 else
10171 FD = cast<FunctionDecl>(ND);
10172
10173 // Mark templated-scope function declarations as unsupported.
10174 if (FD->getNumTemplateParameterLists())
10175 FrD->setUnsupportedFriend(true);
10176 }
John McCall337ec3d2010-10-12 23:13:28 +000010177
John McCalld226f652010-08-21 09:40:31 +000010178 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010179}
10180
John McCalld226f652010-08-21 09:40:31 +000010181void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10182 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010183
Sebastian Redl50de12f2009-03-24 22:27:57 +000010184 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10185 if (!Fn) {
10186 Diag(DelLoc, diag::err_deleted_non_function);
10187 return;
10188 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010189 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010190 Diag(DelLoc, diag::err_deleted_decl_not_first);
10191 Diag(Prev->getLocation(), diag::note_previous_declaration);
10192 // If the declaration wasn't the first, we delete the function anyway for
10193 // recovery.
10194 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010195 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010196
10197 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10198 if (!MD)
10199 return;
10200
10201 // A deleted special member function is trivial if the corresponding
10202 // implicitly-declared function would have been.
10203 switch (getSpecialMember(MD)) {
10204 case CXXInvalid:
10205 break;
10206 case CXXDefaultConstructor:
10207 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10208 break;
10209 case CXXCopyConstructor:
10210 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10211 break;
10212 case CXXMoveConstructor:
10213 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10214 break;
10215 case CXXCopyAssignment:
10216 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10217 break;
10218 case CXXMoveAssignment:
10219 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10220 break;
10221 case CXXDestructor:
10222 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10223 break;
10224 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010225}
Sebastian Redl13e88542009-04-27 21:33:24 +000010226
Sean Hunte4246a62011-05-12 06:15:49 +000010227void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10229
10230 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010231 if (MD->getParent()->isDependentType()) {
10232 MD->setDefaulted();
10233 MD->setExplicitlyDefaulted();
10234 return;
10235 }
10236
Sean Hunte4246a62011-05-12 06:15:49 +000010237 CXXSpecialMember Member = getSpecialMember(MD);
10238 if (Member == CXXInvalid) {
10239 Diag(DefaultLoc, diag::err_default_special_members);
10240 return;
10241 }
10242
10243 MD->setDefaulted();
10244 MD->setExplicitlyDefaulted();
10245
Sean Huntcd10dec2011-05-23 23:14:04 +000010246 // If this definition appears within the record, do the checking when
10247 // the record is complete.
10248 const FunctionDecl *Primary = MD;
10249 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10250 // Find the uninstantiated declaration that actually had the '= default'
10251 // on it.
10252 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10253
10254 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010255 return;
10256
10257 switch (Member) {
10258 case CXXDefaultConstructor: {
10259 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10260 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010261 if (!CD->isInvalidDecl())
10262 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10263 break;
10264 }
10265
10266 case CXXCopyConstructor: {
10267 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10268 CheckExplicitlyDefaultedCopyConstructor(CD);
10269 if (!CD->isInvalidDecl())
10270 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010271 break;
10272 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010273
Sean Hunt2b188082011-05-14 05:23:28 +000010274 case CXXCopyAssignment: {
10275 CheckExplicitlyDefaultedCopyAssignment(MD);
10276 if (!MD->isInvalidDecl())
10277 DefineImplicitCopyAssignment(DefaultLoc, MD);
10278 break;
10279 }
10280
Sean Huntcb45a0f2011-05-12 22:46:25 +000010281 case CXXDestructor: {
10282 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10283 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010284 if (!DD->isInvalidDecl())
10285 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010286 break;
10287 }
10288
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010289 case CXXMoveConstructor: {
10290 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10291 CheckExplicitlyDefaultedMoveConstructor(CD);
10292 if (!CD->isInvalidDecl())
10293 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010294 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010295 }
Sean Hunt82713172011-05-25 23:16:36 +000010296
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010297 case CXXMoveAssignment: {
10298 CheckExplicitlyDefaultedMoveAssignment(MD);
10299 if (!MD->isInvalidDecl())
10300 DefineImplicitMoveAssignment(DefaultLoc, MD);
10301 break;
10302 }
10303
10304 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010305 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010306 }
10307 } else {
10308 Diag(DefaultLoc, diag::err_default_special_members);
10309 }
10310}
10311
Sebastian Redl13e88542009-04-27 21:33:24 +000010312static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010313 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010314 Stmt *SubStmt = *CI;
10315 if (!SubStmt)
10316 continue;
10317 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010318 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010319 diag::err_return_in_constructor_handler);
10320 if (!isa<Expr>(SubStmt))
10321 SearchForReturnInStmt(Self, SubStmt);
10322 }
10323}
10324
10325void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10326 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10327 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10328 SearchForReturnInStmt(*this, Handler);
10329 }
10330}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010331
Mike Stump1eb44332009-09-09 15:08:12 +000010332bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010333 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010334 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10335 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010336
Chandler Carruth73857792010-02-15 11:53:20 +000010337 if (Context.hasSameType(NewTy, OldTy) ||
10338 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010339 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010340
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010341 // Check if the return types are covariant
10342 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010343
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010344 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010345 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10346 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010347 NewClassTy = NewPT->getPointeeType();
10348 OldClassTy = OldPT->getPointeeType();
10349 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010350 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10351 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10352 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10353 NewClassTy = NewRT->getPointeeType();
10354 OldClassTy = OldRT->getPointeeType();
10355 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010356 }
10357 }
Mike Stump1eb44332009-09-09 15:08:12 +000010358
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010359 // The return types aren't either both pointers or references to a class type.
10360 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010361 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010362 diag::err_different_return_type_for_overriding_virtual_function)
10363 << New->getDeclName() << NewTy << OldTy;
10364 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010365
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010366 return true;
10367 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010368
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010369 // C++ [class.virtual]p6:
10370 // If the return type of D::f differs from the return type of B::f, the
10371 // class type in the return type of D::f shall be complete at the point of
10372 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010373 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10374 if (!RT->isBeingDefined() &&
10375 RequireCompleteType(New->getLocation(), NewClassTy,
10376 PDiag(diag::err_covariant_return_incomplete)
10377 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010378 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010379 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010380
Douglas Gregora4923eb2009-11-16 21:35:15 +000010381 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010382 // Check if the new class derives from the old class.
10383 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10384 Diag(New->getLocation(),
10385 diag::err_covariant_return_not_derived)
10386 << New->getDeclName() << NewTy << OldTy;
10387 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10388 return true;
10389 }
Mike Stump1eb44332009-09-09 15:08:12 +000010390
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010391 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010392 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010393 diag::err_covariant_return_inaccessible_base,
10394 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10395 // FIXME: Should this point to the return type?
10396 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010397 // FIXME: this note won't trigger for delayed access control
10398 // diagnostics, and it's impossible to get an undelayed error
10399 // here from access control during the original parse because
10400 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010401 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10402 return true;
10403 }
10404 }
Mike Stump1eb44332009-09-09 15:08:12 +000010405
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010406 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010407 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010408 Diag(New->getLocation(),
10409 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010410 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010411 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10412 return true;
10413 };
Mike Stump1eb44332009-09-09 15:08:12 +000010414
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010415
10416 // The new class type must have the same or less qualifiers as the old type.
10417 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10418 Diag(New->getLocation(),
10419 diag::err_covariant_return_type_class_type_more_qualified)
10420 << New->getDeclName() << NewTy << OldTy;
10421 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10422 return true;
10423 };
Mike Stump1eb44332009-09-09 15:08:12 +000010424
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010425 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010426}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010427
Douglas Gregor4ba31362009-12-01 17:24:26 +000010428/// \brief Mark the given method pure.
10429///
10430/// \param Method the method to be marked pure.
10431///
10432/// \param InitRange the source range that covers the "0" initializer.
10433bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010434 SourceLocation EndLoc = InitRange.getEnd();
10435 if (EndLoc.isValid())
10436 Method->setRangeEnd(EndLoc);
10437
Douglas Gregor4ba31362009-12-01 17:24:26 +000010438 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10439 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010440 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010441 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010442
10443 if (!Method->isInvalidDecl())
10444 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10445 << Method->getDeclName() << InitRange;
10446 return true;
10447}
10448
Douglas Gregor552e2992012-02-21 02:22:07 +000010449/// \brief Determine whether the given declaration is a static data member.
10450static bool isStaticDataMember(Decl *D) {
10451 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10452 if (!Var)
10453 return false;
10454
10455 return Var->isStaticDataMember();
10456}
John McCall731ad842009-12-19 09:28:58 +000010457/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10458/// an initializer for the out-of-line declaration 'Dcl'. The scope
10459/// is a fresh scope pushed for just this purpose.
10460///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010461/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10462/// static data member of class X, names should be looked up in the scope of
10463/// class X.
John McCalld226f652010-08-21 09:40:31 +000010464void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010465 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010466 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010467
John McCall731ad842009-12-19 09:28:58 +000010468 // We should only get called for declarations with scope specifiers, like:
10469 // int foo::bar;
10470 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010471 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010472
10473 // If we are parsing the initializer for a static data member, push a
10474 // new expression evaluation context that is associated with this static
10475 // data member.
10476 if (isStaticDataMember(D))
10477 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010478}
10479
10480/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010481/// initializer for the out-of-line declaration 'D'.
10482void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010483 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010484 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010485
Douglas Gregor552e2992012-02-21 02:22:07 +000010486 if (isStaticDataMember(D))
10487 PopExpressionEvaluationContext();
10488
John McCall731ad842009-12-19 09:28:58 +000010489 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010490 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010491}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010492
10493/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10494/// C++ if/switch/while/for statement.
10495/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010496DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010497 // C++ 6.4p2:
10498 // The declarator shall not specify a function or an array.
10499 // The type-specifier-seq shall not contain typedef and shall not declare a
10500 // new class or enumeration.
10501 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10502 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010503
10504 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010505 if (!Dcl)
10506 return true;
10507
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010508 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10509 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010510 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010511 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010512 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010513
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010514 return Dcl;
10515}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010516
Douglas Gregordfe65432011-07-28 19:11:31 +000010517void Sema::LoadExternalVTableUses() {
10518 if (!ExternalSource)
10519 return;
10520
10521 SmallVector<ExternalVTableUse, 4> VTables;
10522 ExternalSource->ReadUsedVTables(VTables);
10523 SmallVector<VTableUse, 4> NewUses;
10524 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10525 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10526 = VTablesUsed.find(VTables[I].Record);
10527 // Even if a definition wasn't required before, it may be required now.
10528 if (Pos != VTablesUsed.end()) {
10529 if (!Pos->second && VTables[I].DefinitionRequired)
10530 Pos->second = true;
10531 continue;
10532 }
10533
10534 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10535 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10536 }
10537
10538 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10539}
10540
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010541void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10542 bool DefinitionRequired) {
10543 // Ignore any vtable uses in unevaluated operands or for classes that do
10544 // not have a vtable.
10545 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10546 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010547 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010548 return;
10549
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010550 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010551 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010552 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10553 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10554 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10555 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010556 // If we already had an entry, check to see if we are promoting this vtable
10557 // to required a definition. If so, we need to reappend to the VTableUses
10558 // list, since we may have already processed the first entry.
10559 if (DefinitionRequired && !Pos.first->second) {
10560 Pos.first->second = true;
10561 } else {
10562 // Otherwise, we can early exit.
10563 return;
10564 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010565 }
10566
10567 // Local classes need to have their virtual members marked
10568 // immediately. For all other classes, we mark their virtual members
10569 // at the end of the translation unit.
10570 if (Class->isLocalClass())
10571 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010572 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010573 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010574}
10575
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010576bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010577 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010578 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010579 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010580
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010581 // Note: The VTableUses vector could grow as a result of marking
10582 // the members of a class as "used", so we check the size each
10583 // time through the loop and prefer indices (with are stable) to
10584 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010585 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010586 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010587 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010588 if (!Class)
10589 continue;
10590
10591 SourceLocation Loc = VTableUses[I].second;
10592
10593 // If this class has a key function, but that key function is
10594 // defined in another translation unit, we don't need to emit the
10595 // vtable even though we're using it.
10596 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010597 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010598 switch (KeyFunction->getTemplateSpecializationKind()) {
10599 case TSK_Undeclared:
10600 case TSK_ExplicitSpecialization:
10601 case TSK_ExplicitInstantiationDeclaration:
10602 // The key function is in another translation unit.
10603 continue;
10604
10605 case TSK_ExplicitInstantiationDefinition:
10606 case TSK_ImplicitInstantiation:
10607 // We will be instantiating the key function.
10608 break;
10609 }
10610 } else if (!KeyFunction) {
10611 // If we have a class with no key function that is the subject
10612 // of an explicit instantiation declaration, suppress the
10613 // vtable; it will live with the explicit instantiation
10614 // definition.
10615 bool IsExplicitInstantiationDeclaration
10616 = Class->getTemplateSpecializationKind()
10617 == TSK_ExplicitInstantiationDeclaration;
10618 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10619 REnd = Class->redecls_end();
10620 R != REnd; ++R) {
10621 TemplateSpecializationKind TSK
10622 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10623 if (TSK == TSK_ExplicitInstantiationDeclaration)
10624 IsExplicitInstantiationDeclaration = true;
10625 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10626 IsExplicitInstantiationDeclaration = false;
10627 break;
10628 }
10629 }
10630
10631 if (IsExplicitInstantiationDeclaration)
10632 continue;
10633 }
10634
10635 // Mark all of the virtual members of this class as referenced, so
10636 // that we can build a vtable. Then, tell the AST consumer that a
10637 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010638 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010639 MarkVirtualMembersReferenced(Loc, Class);
10640 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10641 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10642
10643 // Optionally warn if we're emitting a weak vtable.
10644 if (Class->getLinkage() == ExternalLinkage &&
10645 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010646 const FunctionDecl *KeyFunctionDef = 0;
10647 if (!KeyFunction ||
10648 (KeyFunction->hasBody(KeyFunctionDef) &&
10649 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010650 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10651 TSK_ExplicitInstantiationDefinition
10652 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10653 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010654 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010655 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010656 VTableUses.clear();
10657
Douglas Gregor78844032011-04-22 22:25:37 +000010658 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010659}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010660
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010661void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10662 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010663 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10664 e = RD->method_end(); i != e; ++i) {
10665 CXXMethodDecl *MD = *i;
10666
10667 // C++ [basic.def.odr]p2:
10668 // [...] A virtual member function is used if it is not pure. [...]
10669 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010670 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010671 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010672
10673 // Only classes that have virtual bases need a VTT.
10674 if (RD->getNumVBases() == 0)
10675 return;
10676
10677 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10678 e = RD->bases_end(); i != e; ++i) {
10679 const CXXRecordDecl *Base =
10680 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010681 if (Base->getNumVBases() == 0)
10682 continue;
10683 MarkVirtualMembersReferenced(Loc, Base);
10684 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010685}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010686
10687/// SetIvarInitializers - This routine builds initialization ASTs for the
10688/// Objective-C implementation whose ivars need be initialized.
10689void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010690 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010691 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010692 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010693 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010694 CollectIvarsToConstructOrDestruct(OID, ivars);
10695 if (ivars.empty())
10696 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010697 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010698 for (unsigned i = 0; i < ivars.size(); i++) {
10699 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010700 if (Field->isInvalidDecl())
10701 continue;
10702
Sean Huntcbb67482011-01-08 20:30:50 +000010703 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010704 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10705 InitializationKind InitKind =
10706 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10707
10708 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010709 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010710 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010711 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010712 // Note, MemberInit could actually come back empty if no initialization
10713 // is required (e.g., because it would call a trivial default constructor)
10714 if (!MemberInit.get() || MemberInit.isInvalid())
10715 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010716
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010717 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010718 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10719 SourceLocation(),
10720 MemberInit.takeAs<Expr>(),
10721 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010722 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010723
10724 // Be sure that the destructor is accessible and is marked as referenced.
10725 if (const RecordType *RecordTy
10726 = Context.getBaseElementType(Field->getType())
10727 ->getAs<RecordType>()) {
10728 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010729 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010730 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010731 CheckDestructorAccess(Field->getLocation(), Destructor,
10732 PDiag(diag::err_access_dtor_ivar)
10733 << Context.getBaseElementType(Field->getType()));
10734 }
10735 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010736 }
10737 ObjCImplementation->setIvarInitializers(Context,
10738 AllToInit.data(), AllToInit.size());
10739 }
10740}
Sean Huntfe57eef2011-05-04 05:57:24 +000010741
Sean Huntebcbe1d2011-05-04 23:29:54 +000010742static
10743void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10744 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10745 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10746 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10747 Sema &S) {
10748 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10749 CE = Current.end();
10750 if (Ctor->isInvalidDecl())
10751 return;
10752
10753 const FunctionDecl *FNTarget = 0;
10754 CXXConstructorDecl *Target;
10755
10756 // We ignore the result here since if we don't have a body, Target will be
10757 // null below.
10758 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10759 Target
10760= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10761
10762 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10763 // Avoid dereferencing a null pointer here.
10764 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10765
10766 if (!Current.insert(Canonical))
10767 return;
10768
10769 // We know that beyond here, we aren't chaining into a cycle.
10770 if (!Target || !Target->isDelegatingConstructor() ||
10771 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10772 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10773 Valid.insert(*CI);
10774 Current.clear();
10775 // We've hit a cycle.
10776 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10777 Current.count(TCanonical)) {
10778 // If we haven't diagnosed this cycle yet, do so now.
10779 if (!Invalid.count(TCanonical)) {
10780 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010781 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010782 << Ctor;
10783
10784 // Don't add a note for a function delegating directo to itself.
10785 if (TCanonical != Canonical)
10786 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10787
10788 CXXConstructorDecl *C = Target;
10789 while (C->getCanonicalDecl() != Canonical) {
10790 (void)C->getTargetConstructor()->hasBody(FNTarget);
10791 assert(FNTarget && "Ctor cycle through bodiless function");
10792
10793 C
10794 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10795 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10796 }
10797 }
10798
10799 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10800 Invalid.insert(*CI);
10801 Current.clear();
10802 } else {
10803 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10804 }
10805}
10806
10807
Sean Huntfe57eef2011-05-04 05:57:24 +000010808void Sema::CheckDelegatingCtorCycles() {
10809 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10810
Sean Huntebcbe1d2011-05-04 23:29:54 +000010811 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10812 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010813
Douglas Gregor0129b562011-07-27 21:57:17 +000010814 for (DelegatingCtorDeclsType::iterator
10815 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010816 E = DelegatingCtorDecls.end();
10817 I != E; ++I) {
10818 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010819 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010820
10821 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10822 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010823}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010824
10825/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10826Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10827 // Implicitly declared functions (e.g. copy constructors) are
10828 // __host__ __device__
10829 if (D->isImplicit())
10830 return CFT_HostDevice;
10831
10832 if (D->hasAttr<CUDAGlobalAttr>())
10833 return CFT_Global;
10834
10835 if (D->hasAttr<CUDADeviceAttr>()) {
10836 if (D->hasAttr<CUDAHostAttr>())
10837 return CFT_HostDevice;
10838 else
10839 return CFT_Device;
10840 }
10841
10842 return CFT_Host;
10843}
10844
10845bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10846 CUDAFunctionTarget CalleeTarget) {
10847 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10848 // Callable from the device only."
10849 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10850 return true;
10851
10852 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10853 // Callable from the host only."
10854 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10855 // Callable from the host only."
10856 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10857 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10858 return true;
10859
10860 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10861 return true;
10862
10863 return false;
10864}