blob: c8c3af3cd5417dd8444e55d15c6ab13c7b182f28 [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 // };
1541 DeclContext *DC = 0;
1542 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1543 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001544 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001545 else
1546 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1547 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001548
Douglas Gregor922fff22010-10-13 22:19:53 +00001549 SS.clear();
1550 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001551
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001552 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001553 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001554 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001555 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001556 assert(!HasDeferredInit);
1557
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001558 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001559 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001560 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001561 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001562
1563 // Non-instance-fields can't have a bitfield.
1564 if (BitWidth) {
1565 if (Member->isInvalidDecl()) {
1566 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001567 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001568 // C++ 9.6p3: A bit-field shall not be a static member.
1569 // "static member 'A' cannot be a bit-field"
1570 Diag(Loc, diag::err_static_not_bitfield)
1571 << Name << BitWidth->getSourceRange();
1572 } else if (isa<TypedefDecl>(Member)) {
1573 // "typedef member 'x' cannot be a bit-field"
1574 Diag(Loc, diag::err_typedef_not_bitfield)
1575 << Name << BitWidth->getSourceRange();
1576 } else {
1577 // A function typedef ("typedef int f(); f a;").
1578 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1579 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001580 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001581 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Chris Lattner8b963ef2009-03-05 23:01:03 +00001584 BitWidth = 0;
1585 Member->setInvalidDecl();
1586 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001587
1588 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Douglas Gregor37b372b2009-08-20 22:52:58 +00001590 // If we have declared a member function template, set the access of the
1591 // templated declaration as well.
1592 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1593 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001594 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001595
Anders Carlssonaae5af22011-01-20 04:34:22 +00001596 if (VS.isOverrideSpecified()) {
1597 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1598 if (!MD || !MD->isVirtual()) {
1599 Diag(Member->getLocStart(),
1600 diag::override_keyword_only_allowed_on_virtual_member_functions)
1601 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001602 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001603 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001604 }
1605 if (VS.isFinalSpecified()) {
1606 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1607 if (!MD || !MD->isVirtual()) {
1608 Diag(Member->getLocStart(),
1609 diag::override_keyword_only_allowed_on_virtual_member_functions)
1610 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001611 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001612 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001613 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001614
Douglas Gregorf5251602011-03-08 17:10:18 +00001615 if (VS.getLastLocation().isValid()) {
1616 // Update the end location of a method that has a virt-specifiers.
1617 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1618 MD->setRangeEnd(VS.getLastLocation());
1619 }
1620
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001621 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001622
Douglas Gregor10bd3682008-11-17 22:58:34 +00001623 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001624
John McCallb25b2952011-02-15 07:12:36 +00001625 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001626 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001627 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001628}
1629
Richard Smith7a614d82011-06-11 17:19:42 +00001630/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001631/// in-class initializer for a non-static C++ class member, and after
1632/// instantiating an in-class initializer in a class template. Such actions
1633/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001634void
1635Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1636 Expr *InitExpr) {
1637 FieldDecl *FD = cast<FieldDecl>(D);
1638
1639 if (!InitExpr) {
1640 FD->setInvalidDecl();
1641 FD->removeInClassInitializer();
1642 return;
1643 }
1644
Peter Collingbournefef21892011-10-23 18:59:44 +00001645 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1646 FD->setInvalidDecl();
1647 FD->removeInClassInitializer();
1648 return;
1649 }
1650
Richard Smith7a614d82011-06-11 17:19:42 +00001651 ExprResult Init = InitExpr;
1652 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001653 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001654 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001655 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1656 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001657 Expr **Inits = &InitExpr;
1658 unsigned NumInits = 1;
1659 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1660 InitializationKind Kind = EqualLoc.isInvalid()
1661 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1662 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1663 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1664 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001665 if (Init.isInvalid()) {
1666 FD->setInvalidDecl();
1667 return;
1668 }
1669
1670 CheckImplicitConversions(Init.get(), EqualLoc);
1671 }
1672
1673 // C++0x [class.base.init]p7:
1674 // The initialization of each base and member constitutes a
1675 // full-expression.
1676 Init = MaybeCreateExprWithCleanups(Init);
1677 if (Init.isInvalid()) {
1678 FD->setInvalidDecl();
1679 return;
1680 }
1681
1682 InitExpr = Init.release();
1683
1684 FD->setInClassInitializer(InitExpr);
1685}
1686
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001687/// \brief Find the direct and/or virtual base specifiers that
1688/// correspond to the given base type, for use in base initialization
1689/// within a constructor.
1690static bool FindBaseInitializer(Sema &SemaRef,
1691 CXXRecordDecl *ClassDecl,
1692 QualType BaseType,
1693 const CXXBaseSpecifier *&DirectBaseSpec,
1694 const CXXBaseSpecifier *&VirtualBaseSpec) {
1695 // First, check for a direct base class.
1696 DirectBaseSpec = 0;
1697 for (CXXRecordDecl::base_class_const_iterator Base
1698 = ClassDecl->bases_begin();
1699 Base != ClassDecl->bases_end(); ++Base) {
1700 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1701 // We found a direct base of this type. That's what we're
1702 // initializing.
1703 DirectBaseSpec = &*Base;
1704 break;
1705 }
1706 }
1707
1708 // Check for a virtual base class.
1709 // FIXME: We might be able to short-circuit this if we know in advance that
1710 // there are no virtual bases.
1711 VirtualBaseSpec = 0;
1712 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1713 // We haven't found a base yet; search the class hierarchy for a
1714 // virtual base class.
1715 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1716 /*DetectVirtual=*/false);
1717 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1718 BaseType, Paths)) {
1719 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1720 Path != Paths.end(); ++Path) {
1721 if (Path->back().Base->isVirtual()) {
1722 VirtualBaseSpec = Path->back().Base;
1723 break;
1724 }
1725 }
1726 }
1727 }
1728
1729 return DirectBaseSpec || VirtualBaseSpec;
1730}
1731
Sebastian Redl6df65482011-09-24 17:48:25 +00001732/// \brief Handle a C++ member initializer using braced-init-list syntax.
1733MemInitResult
1734Sema::ActOnMemInitializer(Decl *ConstructorD,
1735 Scope *S,
1736 CXXScopeSpec &SS,
1737 IdentifierInfo *MemberOrBase,
1738 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001739 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001740 SourceLocation IdLoc,
1741 Expr *InitList,
1742 SourceLocation EllipsisLoc) {
1743 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001744 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001745 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001746}
1747
1748/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001749MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001750Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001751 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001752 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001753 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001754 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001755 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001756 SourceLocation IdLoc,
1757 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001758 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001759 SourceLocation RParenLoc,
1760 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001761 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1762 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001763 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001764 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001765}
1766
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001767namespace {
1768
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001769// Callback to only accept typo corrections that can be a valid C++ member
1770// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001771class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1772 public:
1773 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1774 : ClassDecl(ClassDecl) {}
1775
1776 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1777 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1778 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1779 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1780 else
1781 return isa<TypeDecl>(ND);
1782 }
1783 return false;
1784 }
1785
1786 private:
1787 CXXRecordDecl *ClassDecl;
1788};
1789
1790}
1791
Sebastian Redl6df65482011-09-24 17:48:25 +00001792/// \brief Handle a C++ member initializer.
1793MemInitResult
1794Sema::BuildMemInitializer(Decl *ConstructorD,
1795 Scope *S,
1796 CXXScopeSpec &SS,
1797 IdentifierInfo *MemberOrBase,
1798 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001799 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001801 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001802 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001803 if (!ConstructorD)
1804 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001806 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
1808 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001809 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001810 if (!Constructor) {
1811 // The user wrote a constructor initializer on a function that is
1812 // not a C++ constructor. Ignore the error for now, because we may
1813 // have more member initializers coming; we'll diagnose it just
1814 // once in ActOnMemInitializers.
1815 return true;
1816 }
1817
1818 CXXRecordDecl *ClassDecl = Constructor->getParent();
1819
1820 // C++ [class.base.init]p2:
1821 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001822 // constructor's class and, if not found in that scope, are looked
1823 // up in the scope containing the constructor's definition.
1824 // [Note: if the constructor's class contains a member with the
1825 // same name as a direct or virtual base class of the class, a
1826 // mem-initializer-id naming the member or base class and composed
1827 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001828 // mem-initializer-id for the hidden base class may be specified
1829 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001830 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001831 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001832 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001833 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001834 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001835 ValueDecl *Member;
1836 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1837 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001838 if (EllipsisLoc.isValid())
1839 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001840 << MemberOrBase
1841 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001842
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001843 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001844 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001845 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001846 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001848 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001849 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001850
1851 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001852 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001853 } else if (DS.getTypeSpecType() == TST_decltype) {
1854 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001855 } else {
1856 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1857 LookupParsedName(R, S, &SS);
1858
1859 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1860 if (!TyD) {
1861 if (R.isAmbiguous()) return true;
1862
John McCallfd225442010-04-09 19:01:14 +00001863 // We don't want access-control diagnostics here.
1864 R.suppressDiagnostics();
1865
Douglas Gregor7a886e12010-01-19 06:46:48 +00001866 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1867 bool NotUnknownSpecialization = false;
1868 DeclContext *DC = computeDeclContext(SS, false);
1869 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1870 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1871
1872 if (!NotUnknownSpecialization) {
1873 // When the scope specifier can refer to a member of an unknown
1874 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001875 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1876 SS.getWithLocInContext(Context),
1877 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001878 if (BaseType.isNull())
1879 return true;
1880
Douglas Gregor7a886e12010-01-19 06:46:48 +00001881 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001882 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001883 }
1884 }
1885
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001886 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001887 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001888 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001889 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001890 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001891 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001892 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1893 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001894 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001895 // We have found a non-static data member with a similar
1896 // name to what was typed; complain and initialize that
1897 // member.
1898 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1899 << MemberOrBase << true << CorrectedQuotedStr
1900 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1901 Diag(Member->getLocation(), diag::note_previous_decl)
1902 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001903
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001904 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001905 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001906 const CXXBaseSpecifier *DirectBaseSpec;
1907 const CXXBaseSpecifier *VirtualBaseSpec;
1908 if (FindBaseInitializer(*this, ClassDecl,
1909 Context.getTypeDeclType(Type),
1910 DirectBaseSpec, VirtualBaseSpec)) {
1911 // We have found a direct or virtual base class with a
1912 // similar name to what was typed; complain and initialize
1913 // that base class.
1914 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001915 << MemberOrBase << false << CorrectedQuotedStr
1916 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001917
1918 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1919 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001920 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001921 diag::note_base_class_specified_here)
1922 << BaseSpec->getType()
1923 << BaseSpec->getSourceRange();
1924
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001925 TyD = Type;
1926 }
1927 }
1928 }
1929
Douglas Gregor7a886e12010-01-19 06:46:48 +00001930 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001931 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001932 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001933 return true;
1934 }
John McCall2b194412009-12-21 10:41:20 +00001935 }
1936
Douglas Gregor7a886e12010-01-19 06:46:48 +00001937 if (BaseType.isNull()) {
1938 BaseType = Context.getTypeDeclType(TyD);
1939 if (SS.isSet()) {
1940 NestedNameSpecifier *Qualifier =
1941 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001942
Douglas Gregor7a886e12010-01-19 06:46:48 +00001943 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001944 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001945 }
John McCall2b194412009-12-21 10:41:20 +00001946 }
1947 }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
John McCalla93c9342009-12-07 02:54:59 +00001949 if (!TInfo)
1950 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001951
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001952 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001953}
1954
Chandler Carruth81c64772011-09-03 01:14:15 +00001955/// Checks a member initializer expression for cases where reference (or
1956/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001957static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1958 Expr *Init,
1959 SourceLocation IdLoc) {
1960 QualType MemberTy = Member->getType();
1961
1962 // We only handle pointers and references currently.
1963 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1964 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1965 return;
1966
1967 const bool IsPointer = MemberTy->isPointerType();
1968 if (IsPointer) {
1969 if (const UnaryOperator *Op
1970 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1971 // The only case we're worried about with pointers requires taking the
1972 // address.
1973 if (Op->getOpcode() != UO_AddrOf)
1974 return;
1975
1976 Init = Op->getSubExpr();
1977 } else {
1978 // We only handle address-of expression initializers for pointers.
1979 return;
1980 }
1981 }
1982
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001983 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1984 // Taking the address of a temporary will be diagnosed as a hard error.
1985 if (IsPointer)
1986 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001987
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001988 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1989 << Member << Init->getSourceRange();
1990 } else if (const DeclRefExpr *DRE
1991 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1992 // We only warn when referring to a non-reference parameter declaration.
1993 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1994 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001995 return;
1996
1997 S.Diag(Init->getExprLoc(),
1998 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1999 : diag::warn_bind_ref_member_to_parameter)
2000 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002001 } else {
2002 // Other initializers are fine.
2003 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002004 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002005
2006 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2007 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002008}
2009
John McCallb4190042009-11-04 23:02:40 +00002010/// Checks an initializer expression for use of uninitialized fields, such as
2011/// containing the field that is being initialized. Returns true if there is an
2012/// uninitialized field was used an updates the SourceLocation parameter; false
2013/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002014static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002015 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002016 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002017 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2018
Nick Lewycky43ad1822010-06-15 07:32:55 +00002019 if (isa<CallExpr>(S)) {
2020 // Do not descend into function calls or constructors, as the use
2021 // of an uninitialized field may be valid. One would have to inspect
2022 // the contents of the function/ctor to determine if it is safe or not.
2023 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2024 // may be safe, depending on what the function/ctor does.
2025 return false;
2026 }
2027 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2028 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002029
2030 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2031 // The member expression points to a static data member.
2032 assert(VD->isStaticDataMember() &&
2033 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002034 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002035 return false;
2036 }
2037
2038 if (isa<EnumConstantDecl>(RhsField)) {
2039 // The member expression points to an enum.
2040 return false;
2041 }
2042
John McCallb4190042009-11-04 23:02:40 +00002043 if (RhsField == LhsField) {
2044 // Initializing a field with itself. Throw a warning.
2045 // But wait; there are exceptions!
2046 // Exception #1: The field may not belong to this record.
2047 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002048 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002049 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2050 // Even though the field matches, it does not belong to this record.
2051 return false;
2052 }
2053 // None of the exceptions triggered; return true to indicate an
2054 // uninitialized field was used.
2055 *L = ME->getMemberLoc();
2056 return true;
2057 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002058 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002059 // sizeof/alignof doesn't reference contents, do not warn.
2060 return false;
2061 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2062 // address-of doesn't reference contents (the pointer may be dereferenced
2063 // in the same expression but it would be rare; and weird).
2064 if (UOE->getOpcode() == UO_AddrOf)
2065 return false;
John McCallb4190042009-11-04 23:02:40 +00002066 }
John McCall7502c1d2011-02-13 04:07:26 +00002067 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002068 if (!*it) {
2069 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002070 continue;
2071 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002072 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2073 return true;
John McCallb4190042009-11-04 23:02:40 +00002074 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002075 return false;
John McCallb4190042009-11-04 23:02:40 +00002076}
2077
John McCallf312b1e2010-08-26 23:41:50 +00002078MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002079Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002080 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002081 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2082 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2083 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002084 "Member must be a FieldDecl or IndirectFieldDecl");
2085
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002086 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002087 return true;
2088
Douglas Gregor464b2f02010-11-05 22:21:31 +00002089 if (Member->isInvalidDecl())
2090 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002091
John McCallb4190042009-11-04 23:02:40 +00002092 // Diagnose value-uses of fields to initialize themselves, e.g.
2093 // foo(foo)
2094 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002095 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002096 Expr **Args;
2097 unsigned NumArgs;
2098 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2099 Args = ParenList->getExprs();
2100 NumArgs = ParenList->getNumExprs();
2101 } else {
2102 InitListExpr *InitList = cast<InitListExpr>(Init);
2103 Args = InitList->getInits();
2104 NumArgs = InitList->getNumInits();
2105 }
2106 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002107 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002108 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002109 // FIXME: Return true in the case when other fields are used before being
2110 // uninitialized. For example, let this field be the i'th field. When
2111 // initializing the i'th field, throw a warning if any of the >= i'th
2112 // fields are used, as they are not yet initialized.
2113 // Right now we are only handling the case where the i'th field uses
2114 // itself in its initializer.
2115 Diag(L, diag::warn_field_is_uninit);
2116 }
2117 }
2118
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002119 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002120
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002121 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002122 // Can't check initialization for a member of dependent type or when
2123 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002124 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002125 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002126 bool InitList = false;
2127 if (isa<InitListExpr>(Init)) {
2128 InitList = true;
2129 Args = &Init;
2130 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002131
2132 if (isStdInitializerList(Member->getType(), 0)) {
2133 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2134 << /*at end of ctor*/1 << InitRange;
2135 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002136 }
2137
Chandler Carruth894aed92010-12-06 09:23:57 +00002138 // Initialize the member.
2139 InitializedEntity MemberEntity =
2140 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2141 : InitializedEntity::InitializeMember(IndirectMember, 0);
2142 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002143 InitList ? InitializationKind::CreateDirectList(IdLoc)
2144 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2145 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002146
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002147 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2148 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2149 MultiExprArg(*this, Args, NumArgs),
2150 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002151 if (MemberInit.isInvalid())
2152 return true;
2153
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002154 CheckImplicitConversions(MemberInit.get(),
2155 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002156
2157 // C++0x [class.base.init]p7:
2158 // The initialization of each base and member constitutes a
2159 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002160 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002161 if (MemberInit.isInvalid())
2162 return true;
2163
2164 // If we are in a dependent context, template instantiation will
2165 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002166 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002167 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2168 // of the information that we have about the member
2169 // initializer. However, deconstructing the ASTs is a dicey process,
2170 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002171 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002172 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002173 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002174 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002175 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2176 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002177 }
2178
Chandler Carruth894aed92010-12-06 09:23:57 +00002179 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002180 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2181 InitRange.getBegin(), Init,
2182 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002183 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002184 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2185 InitRange.getBegin(), Init,
2186 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002187 }
Eli Friedman59c04372009-07-29 19:44:27 +00002188}
2189
John McCallf312b1e2010-08-26 23:41:50 +00002190MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002191Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002192 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002193 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002194 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002195 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002196 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002197 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002198
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002199 bool InitList = true;
2200 Expr **Args = &Init;
2201 unsigned NumArgs = 1;
2202 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2203 InitList = false;
2204 Args = ParenList->getExprs();
2205 NumArgs = ParenList->getNumExprs();
2206 }
2207
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002208 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002209 // Initialize the object.
2210 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2211 QualType(ClassDecl->getTypeForDecl(), 0));
2212 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002213 InitList ? InitializationKind::CreateDirectList(NameLoc)
2214 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2215 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002216 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2217 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2218 MultiExprArg(*this, Args,NumArgs),
2219 0);
Sean Hunt41717662011-02-26 19:13:13 +00002220 if (DelegationInit.isInvalid())
2221 return true;
2222
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002223 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2224 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002225
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002226 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002227
2228 // C++0x [class.base.init]p7:
2229 // The initialization of each base and member constitutes a
2230 // full-expression.
2231 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2232 if (DelegationInit.isInvalid())
2233 return true;
2234
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002235 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002236 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002237 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002238}
2239
2240MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002241Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002242 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002243 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002244 SourceLocation BaseLoc
2245 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002246
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002247 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2248 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2249 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2250
2251 // C++ [class.base.init]p2:
2252 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002253 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002254 // of that class, the mem-initializer is ill-formed. A
2255 // mem-initializer-list can initialize a base class using any
2256 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002258
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002259 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002260 if (EllipsisLoc.isValid()) {
2261 // This is a pack expansion.
2262 if (!BaseType->containsUnexpandedParameterPack()) {
2263 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002265
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002266 EllipsisLoc = SourceLocation();
2267 }
2268 } else {
2269 // Check for any unexpanded parameter packs.
2270 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2271 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002272
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002273 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002274 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002275 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002276
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002277 // Check for direct and virtual base classes.
2278 const CXXBaseSpecifier *DirectBaseSpec = 0;
2279 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2280 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002281 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2282 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002283 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002284
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002285 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2286 VirtualBaseSpec);
2287
2288 // C++ [base.class.init]p2:
2289 // Unless the mem-initializer-id names a nonstatic data member of the
2290 // constructor's class or a direct or virtual base of that class, the
2291 // mem-initializer is ill-formed.
2292 if (!DirectBaseSpec && !VirtualBaseSpec) {
2293 // If the class has any dependent bases, then it's possible that
2294 // one of those types will resolve to the same type as
2295 // BaseType. Therefore, just treat this as a dependent base
2296 // class initialization. FIXME: Should we try to check the
2297 // initialization anyway? It seems odd.
2298 if (ClassDecl->hasAnyDependentBases())
2299 Dependent = true;
2300 else
2301 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2302 << BaseType << Context.getTypeDeclType(ClassDecl)
2303 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2304 }
2305 }
2306
2307 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002308 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Sebastian Redl6df65482011-09-24 17:48:25 +00002310 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2311 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002312 InitRange.getBegin(), Init,
2313 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002314 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002315
2316 // C++ [base.class.init]p2:
2317 // If a mem-initializer-id is ambiguous because it designates both
2318 // a direct non-virtual base class and an inherited virtual base
2319 // class, the mem-initializer is ill-formed.
2320 if (DirectBaseSpec && VirtualBaseSpec)
2321 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002322 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002323
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002325 if (!BaseSpec)
2326 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2327
2328 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002329 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002330 Expr **Args = &Init;
2331 unsigned NumArgs = 1;
2332 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002333 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 Args = ParenList->getExprs();
2335 NumArgs = ParenList->getNumExprs();
2336 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002337
2338 InitializedEntity BaseEntity =
2339 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2340 InitializationKind Kind =
2341 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2342 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2343 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002344 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2345 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2346 MultiExprArg(*this, Args, NumArgs),
2347 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002348 if (BaseInit.isInvalid())
2349 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002350
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002351 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002352
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002353 // C++0x [class.base.init]p7:
2354 // The initialization of each base and member constitutes a
2355 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002356 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002357 if (BaseInit.isInvalid())
2358 return true;
2359
2360 // If we are in a dependent context, template instantiation will
2361 // perform this type-checking again. Just save the arguments that we
2362 // received in a ParenListExpr.
2363 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2364 // of the information that we have about the base
2365 // initializer. However, deconstructing the ASTs is a dicey process,
2366 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002367 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002369
Sean Huntcbb67482011-01-08 20:30:50 +00002370 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002371 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002372 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002373 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002374 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002375}
2376
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002377// Create a static_cast\<T&&>(expr).
2378static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2379 QualType ExprType = E->getType();
2380 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2381 SourceLocation ExprLoc = E->getLocStart();
2382 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2383 TargetType, ExprLoc);
2384
2385 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2386 SourceRange(ExprLoc, ExprLoc),
2387 E->getSourceRange()).take();
2388}
2389
Anders Carlssone5ef7402010-04-23 03:10:23 +00002390/// ImplicitInitializerKind - How an implicit base or member initializer should
2391/// initialize its base or member.
2392enum ImplicitInitializerKind {
2393 IIK_Default,
2394 IIK_Copy,
2395 IIK_Move
2396};
2397
Anders Carlssondefefd22010-04-23 02:00:02 +00002398static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002399BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002400 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002401 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002402 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002403 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002404 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002405 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2406 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002407
John McCall60d7b3a2010-08-24 06:29:42 +00002408 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002409
2410 switch (ImplicitInitKind) {
2411 case IIK_Default: {
2412 InitializationKind InitKind
2413 = InitializationKind::CreateDefault(Constructor->getLocation());
2414 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2415 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002416 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002417 break;
2418 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002419
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002420 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002421 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002422 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002423 ParmVarDecl *Param = Constructor->getParamDecl(0);
2424 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002425
Anders Carlssone5ef7402010-04-23 03:10:23 +00002426 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002427 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002428 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002429 Constructor->getLocation(), ParamType,
2430 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002431
Eli Friedman5f2987c2012-02-02 03:46:19 +00002432 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2433
Anders Carlssonc7957502010-04-24 22:02:54 +00002434 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002435 QualType ArgTy =
2436 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2437 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002438
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002439 if (Moving) {
2440 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2441 }
2442
John McCallf871d0c2010-08-07 06:22:56 +00002443 CXXCastPath BasePath;
2444 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002445 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2446 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002447 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002448 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002449
Anders Carlssone5ef7402010-04-23 03:10:23 +00002450 InitializationKind InitKind
2451 = InitializationKind::CreateDirect(Constructor->getLocation(),
2452 SourceLocation(), SourceLocation());
2453 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2454 &CopyCtorArg, 1);
2455 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002456 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002457 break;
2458 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002459 }
John McCall9ae2f072010-08-23 23:25:46 +00002460
Douglas Gregor53c374f2010-12-07 00:41:46 +00002461 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002462 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002463 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002464
Anders Carlssondefefd22010-04-23 02:00:02 +00002465 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002466 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002467 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2468 SourceLocation()),
2469 BaseSpec->isVirtual(),
2470 SourceLocation(),
2471 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002472 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002473 SourceLocation());
2474
Anders Carlssondefefd22010-04-23 02:00:02 +00002475 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002476}
2477
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002478static bool RefersToRValueRef(Expr *MemRef) {
2479 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2480 return Referenced->getType()->isRValueReferenceType();
2481}
2482
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002483static bool
2484BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002485 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002486 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002487 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002488 if (Field->isInvalidDecl())
2489 return true;
2490
Chandler Carruthf186b542010-06-29 23:50:44 +00002491 SourceLocation Loc = Constructor->getLocation();
2492
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2494 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002495 ParmVarDecl *Param = Constructor->getParamDecl(0);
2496 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002497
2498 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002499 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2500 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002501
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002502 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002503 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002504 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002505 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002506
Eli Friedman5f2987c2012-02-02 03:46:19 +00002507 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2508
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002509 if (Moving) {
2510 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2511 }
2512
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002513 // Build a reference to this field within the parameter.
2514 CXXScopeSpec SS;
2515 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2516 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002517 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2518 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002519 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002520 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002521 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002522 ParamType, Loc,
2523 /*IsArrow=*/false,
2524 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002525 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002526 /*FirstQualifierInScope=*/0,
2527 MemberLookup,
2528 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002529 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002530 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002531
2532 // C++11 [class.copy]p15:
2533 // - if a member m has rvalue reference type T&&, it is direct-initialized
2534 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002535 if (RefersToRValueRef(CtorArg.get())) {
2536 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002537 }
2538
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002539 // When the field we are copying is an array, create index variables for
2540 // each dimension of the array. We use these index variables to subscript
2541 // the source array, and other clients (e.g., CodeGen) will perform the
2542 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 QualType BaseType = Field->getType();
2545 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002546 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002547 while (const ConstantArrayType *Array
2548 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002549 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002550 // Create the iteration variable for this array index.
2551 IdentifierInfo *IterationVarName = 0;
2552 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002553 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002554 llvm::raw_svector_ostream OS(Str);
2555 OS << "__i" << IndexVariables.size();
2556 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2557 }
2558 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002559 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002560 IterationVarName, SizeType,
2561 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002562 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002563 IndexVariables.push_back(IterationVar);
2564
2565 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002566 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002567 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002568 assert(!IterationVarRef.isInvalid() &&
2569 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002570 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2571 assert(!IterationVarRef.isInvalid() &&
2572 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002573
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002574 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002575 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002576 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002577 Loc);
2578 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002579 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002580
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002581 BaseType = Array->getElementType();
2582 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002583
2584 // The array subscript expression is an lvalue, which is wrong for moving.
2585 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002586 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002587
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002588 // Construct the entity that we will be initializing. For an array, this
2589 // will be first element in the array, which may require several levels
2590 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002591 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002592 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002593 if (Indirect)
2594 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2595 else
2596 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002597 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2598 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2599 0,
2600 Entities.back()));
2601
2602 // Direct-initialize to use the copy constructor.
2603 InitializationKind InitKind =
2604 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2605
Sebastian Redl74e611a2011-09-04 18:14:28 +00002606 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002608 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002609
John McCall60d7b3a2010-08-24 06:29:42 +00002610 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002611 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002612 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002613 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002614 if (MemberInit.isInvalid())
2615 return true;
2616
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002617 if (Indirect) {
2618 assert(IndexVariables.size() == 0 &&
2619 "Indirect field improperly initialized");
2620 CXXMemberInit
2621 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2622 Loc, Loc,
2623 MemberInit.takeAs<Expr>(),
2624 Loc);
2625 } else
2626 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2627 Loc, MemberInit.takeAs<Expr>(),
2628 Loc,
2629 IndexVariables.data(),
2630 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002631 return false;
2632 }
2633
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002634 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2635
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002636 QualType FieldBaseElementType =
2637 SemaRef.Context.getBaseElementType(Field->getType());
2638
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002639 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002640 InitializedEntity InitEntity
2641 = Indirect? InitializedEntity::InitializeMember(Indirect)
2642 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002643 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002644 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002645
2646 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002647 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002648 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002649
Douglas Gregor53c374f2010-12-07 00:41:46 +00002650 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002651 if (MemberInit.isInvalid())
2652 return true;
2653
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002654 if (Indirect)
2655 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2656 Indirect, Loc,
2657 Loc,
2658 MemberInit.get(),
2659 Loc);
2660 else
2661 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2662 Field, Loc, Loc,
2663 MemberInit.get(),
2664 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002665 return false;
2666 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002667
Sean Hunt1f2f3842011-05-17 00:19:05 +00002668 if (!Field->getParent()->isUnion()) {
2669 if (FieldBaseElementType->isReferenceType()) {
2670 SemaRef.Diag(Constructor->getLocation(),
2671 diag::err_uninitialized_member_in_ctor)
2672 << (int)Constructor->isImplicit()
2673 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2674 << 0 << Field->getDeclName();
2675 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2676 return true;
2677 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002678
Sean Hunt1f2f3842011-05-17 00:19:05 +00002679 if (FieldBaseElementType.isConstQualified()) {
2680 SemaRef.Diag(Constructor->getLocation(),
2681 diag::err_uninitialized_member_in_ctor)
2682 << (int)Constructor->isImplicit()
2683 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2684 << 1 << Field->getDeclName();
2685 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2686 return true;
2687 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002688 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002689
David Blaikie4e4d0842012-03-11 07:00:24 +00002690 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002691 FieldBaseElementType->isObjCRetainableType() &&
2692 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2693 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2694 // Instant objects:
2695 // Default-initialize Objective-C pointers to NULL.
2696 CXXMemberInit
2697 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2698 Loc, Loc,
2699 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2700 Loc);
2701 return false;
2702 }
2703
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002704 // Nothing to initialize.
2705 CXXMemberInit = 0;
2706 return false;
2707}
John McCallf1860e52010-05-20 23:23:51 +00002708
2709namespace {
2710struct BaseAndFieldInfo {
2711 Sema &S;
2712 CXXConstructorDecl *Ctor;
2713 bool AnyErrorsInInits;
2714 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002715 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002716 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002717
2718 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2719 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002720 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2721 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002722 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002723 else if (Generated && Ctor->isMoveConstructor())
2724 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002725 else
2726 IIK = IIK_Default;
2727 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002728
2729 bool isImplicitCopyOrMove() const {
2730 switch (IIK) {
2731 case IIK_Copy:
2732 case IIK_Move:
2733 return true;
2734
2735 case IIK_Default:
2736 return false;
2737 }
David Blaikie30263482012-01-20 21:50:17 +00002738
2739 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002740 }
John McCallf1860e52010-05-20 23:23:51 +00002741};
2742}
2743
Richard Smitha4950662011-09-19 13:34:43 +00002744/// \brief Determine whether the given indirect field declaration is somewhere
2745/// within an anonymous union.
2746static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2747 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2748 CEnd = F->chain_end();
2749 C != CEnd; ++C)
2750 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2751 if (Record->isUnion())
2752 return true;
2753
2754 return false;
2755}
2756
Douglas Gregorddb21472011-11-02 23:04:16 +00002757/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2758/// array type.
2759static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2760 if (T->isIncompleteArrayType())
2761 return true;
2762
2763 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2764 if (!ArrayT->getSize())
2765 return true;
2766
2767 T = ArrayT->getElementType();
2768 }
2769
2770 return false;
2771}
2772
Richard Smith7a614d82011-06-11 17:19:42 +00002773static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002774 FieldDecl *Field,
2775 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002776
Chandler Carruthe861c602010-06-30 02:59:29 +00002777 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002778 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002779 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002780 return false;
2781 }
2782
Richard Smith7a614d82011-06-11 17:19:42 +00002783 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2784 // has a brace-or-equal-initializer, the entity is initialized as specified
2785 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002786 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002787 CXXCtorInitializer *Init;
2788 if (Indirect)
2789 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2790 SourceLocation(),
2791 SourceLocation(), 0,
2792 SourceLocation());
2793 else
2794 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2795 SourceLocation(),
2796 SourceLocation(), 0,
2797 SourceLocation());
2798 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002799 return false;
2800 }
2801
Richard Smithc115f632011-09-18 11:14:50 +00002802 // Don't build an implicit initializer for union members if none was
2803 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002804 if (Field->getParent()->isUnion() ||
2805 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002806 return false;
2807
Douglas Gregorddb21472011-11-02 23:04:16 +00002808 // Don't initialize incomplete or zero-length arrays.
2809 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2810 return false;
2811
John McCallf1860e52010-05-20 23:23:51 +00002812 // Don't try to build an implicit initializer if there were semantic
2813 // errors in any of the initializers (and therefore we might be
2814 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002815 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002816 return false;
2817
Sean Huntcbb67482011-01-08 20:30:50 +00002818 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002819 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2820 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002821 return true;
John McCallf1860e52010-05-20 23:23:51 +00002822
Francois Pichet00eb3f92010-12-04 09:14:42 +00002823 if (Init)
2824 Info.AllToInit.push_back(Init);
2825
John McCallf1860e52010-05-20 23:23:51 +00002826 return false;
2827}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002828
2829bool
2830Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2831 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002832 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002833 Constructor->setNumCtorInitializers(1);
2834 CXXCtorInitializer **initializer =
2835 new (Context) CXXCtorInitializer*[1];
2836 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2837 Constructor->setCtorInitializers(initializer);
2838
Sean Huntb76af9c2011-05-03 23:05:34 +00002839 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002840 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002841 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2842 }
2843
Sean Huntc1598702011-05-05 00:05:47 +00002844 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002845
Sean Hunt059ce0d2011-05-01 07:04:31 +00002846 return false;
2847}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002848
John McCallb77115d2011-06-17 00:18:42 +00002849bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2850 CXXCtorInitializer **Initializers,
2851 unsigned NumInitializers,
2852 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002853 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002854 // Just store the initializers as written, they will be checked during
2855 // instantiation.
2856 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002857 Constructor->setNumCtorInitializers(NumInitializers);
2858 CXXCtorInitializer **baseOrMemberInitializers =
2859 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002860 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002861 NumInitializers * sizeof(CXXCtorInitializer*));
2862 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002863 }
2864
2865 return false;
2866 }
2867
John McCallf1860e52010-05-20 23:23:51 +00002868 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002869
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002870 // We need to build the initializer AST according to order of construction
2871 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002872 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002873 if (!ClassDecl)
2874 return true;
2875
Eli Friedman80c30da2009-11-09 19:20:36 +00002876 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002877
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002878 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002879 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002880
2881 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002882 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002883 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002884 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002885 }
2886
Anders Carlsson711f34a2010-04-21 19:52:01 +00002887 // Keep track of the direct virtual bases.
2888 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2889 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2890 E = ClassDecl->bases_end(); I != E; ++I) {
2891 if (I->isVirtual())
2892 DirectVBases.insert(I);
2893 }
2894
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002895 // Push virtual bases before others.
2896 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2897 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2898
Sean Huntcbb67482011-01-08 20:30:50 +00002899 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002900 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2901 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002902 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002903 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002904 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002905 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002906 VBase, IsInheritedVirtualBase,
2907 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002908 HadError = true;
2909 continue;
2910 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002911
John McCallf1860e52010-05-20 23:23:51 +00002912 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002913 }
2914 }
Mike Stump1eb44332009-09-09 15:08:12 +00002915
John McCallf1860e52010-05-20 23:23:51 +00002916 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002917 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2918 E = ClassDecl->bases_end(); Base != E; ++Base) {
2919 // Virtuals are in the virtual base list and already constructed.
2920 if (Base->isVirtual())
2921 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Sean Huntcbb67482011-01-08 20:30:50 +00002923 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002924 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2925 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002926 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002927 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002928 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002929 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002930 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002931 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002932 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002933 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002934
John McCallf1860e52010-05-20 23:23:51 +00002935 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002936 }
2937 }
Mike Stump1eb44332009-09-09 15:08:12 +00002938
John McCallf1860e52010-05-20 23:23:51 +00002939 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002940 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2941 MemEnd = ClassDecl->decls_end();
2942 Mem != MemEnd; ++Mem) {
2943 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002944 // C++ [class.bit]p2:
2945 // A declaration for a bit-field that omits the identifier declares an
2946 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2947 // initialized.
2948 if (F->isUnnamedBitfield())
2949 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002950
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002951 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952 // handle anonymous struct/union fields based on their individual
2953 // indirect fields.
2954 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2955 continue;
2956
2957 if (CollectFieldInitializer(*this, Info, F))
2958 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002959 continue;
2960 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002961
2962 // Beyond this point, we only consider default initialization.
2963 if (Info.IIK != IIK_Default)
2964 continue;
2965
2966 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2967 if (F->getType()->isIncompleteArrayType()) {
2968 assert(ClassDecl->hasFlexibleArrayMember() &&
2969 "Incomplete array type is not valid");
2970 continue;
2971 }
2972
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002973 // Initialize each field of an anonymous struct individually.
2974 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2975 HadError = true;
2976
2977 continue;
2978 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002979 }
Mike Stump1eb44332009-09-09 15:08:12 +00002980
John McCallf1860e52010-05-20 23:23:51 +00002981 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002982 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002983 Constructor->setNumCtorInitializers(NumInitializers);
2984 CXXCtorInitializer **baseOrMemberInitializers =
2985 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002986 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002987 NumInitializers * sizeof(CXXCtorInitializer*));
2988 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002989
John McCallef027fe2010-03-16 21:39:52 +00002990 // Constructors implicitly reference the base and member
2991 // destructors.
2992 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2993 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002994 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002995
2996 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002997}
2998
Eli Friedman6347f422009-07-21 19:28:10 +00002999static void *GetKeyForTopLevelField(FieldDecl *Field) {
3000 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003001 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003002 if (RT->getDecl()->isAnonymousStructOrUnion())
3003 return static_cast<void *>(RT->getDecl());
3004 }
3005 return static_cast<void *>(Field);
3006}
3007
Anders Carlssonea356fb2010-04-02 05:42:15 +00003008static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003009 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003010}
3011
Anders Carlssonea356fb2010-04-02 05:42:15 +00003012static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003013 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003014 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003015 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003016
Eli Friedman6347f422009-07-21 19:28:10 +00003017 // For fields injected into the class via declaration of an anonymous union,
3018 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003019 FieldDecl *Field = Member->getAnyMember();
3020
John McCall3c3ccdb2010-04-10 09:28:51 +00003021 // If the field is a member of an anonymous struct or union, our key
3022 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003023 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003024 if (RD->isAnonymousStructOrUnion()) {
3025 while (true) {
3026 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3027 if (Parent->isAnonymousStructOrUnion())
3028 RD = Parent;
3029 else
3030 break;
3031 }
3032
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003033 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003036 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003037}
3038
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003039static void
3040DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003041 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003042 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003043 unsigned NumInits) {
3044 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003045 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003047 // Don't check initializers order unless the warning is enabled at the
3048 // location of at least one initializer.
3049 bool ShouldCheckOrder = false;
3050 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003051 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003052 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3053 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003054 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003055 ShouldCheckOrder = true;
3056 break;
3057 }
3058 }
3059 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003060 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003061
John McCalld6ca8da2010-04-10 07:37:23 +00003062 // Build the list of bases and members in the order that they'll
3063 // actually be initialized. The explicit initializers should be in
3064 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003065 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Anders Carlsson071d6102010-04-02 03:38:04 +00003067 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3068
John McCalld6ca8da2010-04-10 07:37:23 +00003069 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003070 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003071 ClassDecl->vbases_begin(),
3072 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003073 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003074
John McCalld6ca8da2010-04-10 07:37:23 +00003075 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003076 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003077 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003078 if (Base->isVirtual())
3079 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003080 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003081 }
Mike Stump1eb44332009-09-09 15:08:12 +00003082
John McCalld6ca8da2010-04-10 07:37:23 +00003083 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003084 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003085 E = ClassDecl->field_end(); Field != E; ++Field) {
3086 if (Field->isUnnamedBitfield())
3087 continue;
3088
John McCalld6ca8da2010-04-10 07:37:23 +00003089 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003090 }
3091
John McCalld6ca8da2010-04-10 07:37:23 +00003092 unsigned NumIdealInits = IdealInitKeys.size();
3093 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003094
Sean Huntcbb67482011-01-08 20:30:50 +00003095 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003096 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003097 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003098 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003099
3100 // Scan forward to try to find this initializer in the idealized
3101 // initializers list.
3102 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3103 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003104 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003105
3106 // If we didn't find this initializer, it must be because we
3107 // scanned past it on a previous iteration. That can only
3108 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003109 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003110 Sema::SemaDiagnosticBuilder D =
3111 SemaRef.Diag(PrevInit->getSourceLocation(),
3112 diag::warn_initializer_out_of_order);
3113
Francois Pichet00eb3f92010-12-04 09:14:42 +00003114 if (PrevInit->isAnyMemberInitializer())
3115 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003116 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003117 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003118
Francois Pichet00eb3f92010-12-04 09:14:42 +00003119 if (Init->isAnyMemberInitializer())
3120 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003121 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003122 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003123
3124 // Move back to the initializer's location in the ideal list.
3125 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3126 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003127 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003128
3129 assert(IdealIndex != NumIdealInits &&
3130 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003131 }
John McCalld6ca8da2010-04-10 07:37:23 +00003132
3133 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003134 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003135}
3136
John McCall3c3ccdb2010-04-10 09:28:51 +00003137namespace {
3138bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003139 CXXCtorInitializer *Init,
3140 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003141 if (!PrevInit) {
3142 PrevInit = Init;
3143 return false;
3144 }
3145
3146 if (FieldDecl *Field = Init->getMember())
3147 S.Diag(Init->getSourceLocation(),
3148 diag::err_multiple_mem_initialization)
3149 << Field->getDeclName()
3150 << Init->getSourceRange();
3151 else {
John McCallf4c73712011-01-19 06:33:43 +00003152 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003153 assert(BaseClass && "neither field nor base");
3154 S.Diag(Init->getSourceLocation(),
3155 diag::err_multiple_base_initialization)
3156 << QualType(BaseClass, 0)
3157 << Init->getSourceRange();
3158 }
3159 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3160 << 0 << PrevInit->getSourceRange();
3161
3162 return true;
3163}
3164
Sean Huntcbb67482011-01-08 20:30:50 +00003165typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003166typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3167
3168bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003169 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003170 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003171 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003172 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003173 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003174
3175 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003176 if (Parent->isUnion()) {
3177 UnionEntry &En = Unions[Parent];
3178 if (En.first && En.first != Child) {
3179 S.Diag(Init->getSourceLocation(),
3180 diag::err_multiple_mem_union_initialization)
3181 << Field->getDeclName()
3182 << Init->getSourceRange();
3183 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3184 << 0 << En.second->getSourceRange();
3185 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003186 }
3187 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003188 En.first = Child;
3189 En.second = Init;
3190 }
David Blaikie6fe29652011-11-17 06:01:57 +00003191 if (!Parent->isAnonymousStructOrUnion())
3192 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003193 }
3194
3195 Child = Parent;
3196 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003197 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003198
3199 return false;
3200}
3201}
3202
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003203/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003204void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003205 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003206 CXXCtorInitializer **meminits,
3207 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003208 bool AnyErrors) {
3209 if (!ConstructorDecl)
3210 return;
3211
3212 AdjustDeclIfTemplate(ConstructorDecl);
3213
3214 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003215 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003216
3217 if (!Constructor) {
3218 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3219 return;
3220 }
3221
Sean Huntcbb67482011-01-08 20:30:50 +00003222 CXXCtorInitializer **MemInits =
3223 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003224
3225 // Mapping for the duplicate initializers check.
3226 // For member initializers, this is keyed with a FieldDecl*.
3227 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003228 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003229
3230 // Mapping for the inconsistent anonymous-union initializers check.
3231 RedundantUnionMap MemberUnions;
3232
Anders Carlssonea356fb2010-04-02 05:42:15 +00003233 bool HadError = false;
3234 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003235 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003236
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003237 // Set the source order index.
3238 Init->setSourceOrder(i);
3239
Francois Pichet00eb3f92010-12-04 09:14:42 +00003240 if (Init->isAnyMemberInitializer()) {
3241 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003242 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3243 CheckRedundantUnionInit(*this, Init, MemberUnions))
3244 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003245 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003246 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3247 if (CheckRedundantInit(*this, Init, Members[Key]))
3248 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003249 } else {
3250 assert(Init->isDelegatingInitializer());
3251 // This must be the only initializer
3252 if (i != 0 || NumMemInits > 1) {
3253 Diag(MemInits[0]->getSourceLocation(),
3254 diag::err_delegating_initializer_alone)
3255 << MemInits[0]->getSourceRange();
3256 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003257 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003258 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003259 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003260 // Return immediately as the initializer is set.
3261 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003262 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003263 }
3264
Anders Carlssonea356fb2010-04-02 05:42:15 +00003265 if (HadError)
3266 return;
3267
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003268 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003269
Sean Huntcbb67482011-01-08 20:30:50 +00003270 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003271}
3272
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003273void
John McCallef027fe2010-03-16 21:39:52 +00003274Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3275 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003276 // Ignore dependent contexts. Also ignore unions, since their members never
3277 // have destructors implicitly called.
3278 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003279 return;
John McCall58e6f342010-03-16 05:22:47 +00003280
3281 // FIXME: all the access-control diagnostics are positioned on the
3282 // field/base declaration. That's probably good; that said, the
3283 // user might reasonably want to know why the destructor is being
3284 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003285
Anders Carlsson9f853df2009-11-17 04:44:12 +00003286 // Non-static data members.
3287 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3288 E = ClassDecl->field_end(); I != E; ++I) {
3289 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003290 if (Field->isInvalidDecl())
3291 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003292
3293 // Don't destroy incomplete or zero-length arrays.
3294 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3295 continue;
3296
Anders Carlsson9f853df2009-11-17 04:44:12 +00003297 QualType FieldType = Context.getBaseElementType(Field->getType());
3298
3299 const RecordType* RT = FieldType->getAs<RecordType>();
3300 if (!RT)
3301 continue;
3302
3303 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003304 if (FieldClassDecl->isInvalidDecl())
3305 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003306 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003307 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003308 // The destructor for an implicit anonymous union member is never invoked.
3309 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3310 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003311
Douglas Gregordb89f282010-07-01 22:47:18 +00003312 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003313 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003314 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003315 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003316 << Field->getDeclName()
3317 << FieldType);
3318
Eli Friedman5f2987c2012-02-02 03:46:19 +00003319 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003320 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003321 }
3322
John McCall58e6f342010-03-16 05:22:47 +00003323 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3324
Anders Carlsson9f853df2009-11-17 04:44:12 +00003325 // Bases.
3326 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3327 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003328 // Bases are always records in a well-formed non-dependent class.
3329 const RecordType *RT = Base->getType()->getAs<RecordType>();
3330
3331 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003332 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003333 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003334
John McCall58e6f342010-03-16 05:22:47 +00003335 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003336 // If our base class is invalid, we probably can't get its dtor anyway.
3337 if (BaseClassDecl->isInvalidDecl())
3338 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003339 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003340 continue;
John McCall58e6f342010-03-16 05:22:47 +00003341
Douglas Gregordb89f282010-07-01 22:47:18 +00003342 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003343 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003344
3345 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003346 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003347 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003348 << Base->getType()
3349 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003350
Eli Friedman5f2987c2012-02-02 03:46:19 +00003351 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003352 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003353 }
3354
3355 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003356 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3357 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003358
3359 // Bases are always records in a well-formed non-dependent class.
3360 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3361
3362 // Ignore direct virtual bases.
3363 if (DirectVirtualBases.count(RT))
3364 continue;
3365
John McCall58e6f342010-03-16 05:22:47 +00003366 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003367 // If our base class is invalid, we probably can't get its dtor anyway.
3368 if (BaseClassDecl->isInvalidDecl())
3369 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003370 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003371 continue;
John McCall58e6f342010-03-16 05:22:47 +00003372
Douglas Gregordb89f282010-07-01 22:47:18 +00003373 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003374 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003375 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003376 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003377 << VBase->getType());
3378
Eli Friedman5f2987c2012-02-02 03:46:19 +00003379 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003380 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003381 }
3382}
3383
John McCalld226f652010-08-21 09:40:31 +00003384void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003385 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003386 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003387
Mike Stump1eb44332009-09-09 15:08:12 +00003388 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003389 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003390 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003391}
3392
Mike Stump1eb44332009-09-09 15:08:12 +00003393bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003394 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003395 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003396 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003397 else
John McCall94c3b562010-08-18 09:41:07 +00003398 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003399}
3400
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003401bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003402 const PartialDiagnostic &PD) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003403 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Anders Carlsson11f21a02009-03-23 19:10:31 +00003406 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003407 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Ted Kremenek6217b802009-07-29 21:53:49 +00003409 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003410 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003411 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003412 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003414 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003415 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003416 }
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Ted Kremenek6217b802009-07-29 21:53:49 +00003418 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003419 if (!RT)
3420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003421
John McCall86ff3082010-02-04 22:26:26 +00003422 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003423
John McCall94c3b562010-08-18 09:41:07 +00003424 // We can't answer whether something is abstract until it has a
3425 // definition. If it's currently being defined, we'll walk back
3426 // over all the declarations when we have a full definition.
3427 const CXXRecordDecl *Def = RD->getDefinition();
3428 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003429 return false;
3430
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003431 if (!RD->isAbstract())
3432 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003434 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003435 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003436
John McCall94c3b562010-08-18 09:41:07 +00003437 return true;
3438}
3439
3440void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3441 // Check if we've already emitted the list of pure virtual functions
3442 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003443 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003444 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003446 CXXFinalOverriderMap FinalOverriders;
3447 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003449 // Keep a set of seen pure methods so we won't diagnose the same method
3450 // more than once.
3451 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3452
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003453 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3454 MEnd = FinalOverriders.end();
3455 M != MEnd;
3456 ++M) {
3457 for (OverridingMethods::iterator SO = M->second.begin(),
3458 SOEnd = M->second.end();
3459 SO != SOEnd; ++SO) {
3460 // C++ [class.abstract]p4:
3461 // A class is abstract if it contains or inherits at least one
3462 // pure virtual function for which the final overrider is pure
3463 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003465 //
3466 if (SO->second.size() != 1)
3467 continue;
3468
3469 if (!SO->second.front().Method->isPure())
3470 continue;
3471
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003472 if (!SeenPureMethods.insert(SO->second.front().Method))
3473 continue;
3474
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003475 Diag(SO->second.front().Method->getLocation(),
3476 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003477 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003478 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003479 }
3480
3481 if (!PureVirtualClassDiagSet)
3482 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3483 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003484}
3485
Anders Carlsson8211eff2009-03-24 01:19:16 +00003486namespace {
John McCall94c3b562010-08-18 09:41:07 +00003487struct AbstractUsageInfo {
3488 Sema &S;
3489 CXXRecordDecl *Record;
3490 CanQualType AbstractType;
3491 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003492
John McCall94c3b562010-08-18 09:41:07 +00003493 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3494 : S(S), Record(Record),
3495 AbstractType(S.Context.getCanonicalType(
3496 S.Context.getTypeDeclType(Record))),
3497 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003498
John McCall94c3b562010-08-18 09:41:07 +00003499 void DiagnoseAbstractType() {
3500 if (Invalid) return;
3501 S.DiagnoseAbstractType(Record);
3502 Invalid = true;
3503 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003504
John McCall94c3b562010-08-18 09:41:07 +00003505 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3506};
3507
3508struct CheckAbstractUsage {
3509 AbstractUsageInfo &Info;
3510 const NamedDecl *Ctx;
3511
3512 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3513 : Info(Info), Ctx(Ctx) {}
3514
3515 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3516 switch (TL.getTypeLocClass()) {
3517#define ABSTRACT_TYPELOC(CLASS, PARENT)
3518#define TYPELOC(CLASS, PARENT) \
3519 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3520#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003521 }
John McCall94c3b562010-08-18 09:41:07 +00003522 }
Mike Stump1eb44332009-09-09 15:08:12 +00003523
John McCall94c3b562010-08-18 09:41:07 +00003524 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3525 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3526 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003527 if (!TL.getArg(I))
3528 continue;
3529
John McCall94c3b562010-08-18 09:41:07 +00003530 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3531 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003532 }
John McCall94c3b562010-08-18 09:41:07 +00003533 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003534
John McCall94c3b562010-08-18 09:41:07 +00003535 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3536 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3537 }
Mike Stump1eb44332009-09-09 15:08:12 +00003538
John McCall94c3b562010-08-18 09:41:07 +00003539 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3540 // Visit the type parameters from a permissive context.
3541 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3542 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3543 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3544 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3545 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3546 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003547 }
John McCall94c3b562010-08-18 09:41:07 +00003548 }
Mike Stump1eb44332009-09-09 15:08:12 +00003549
John McCall94c3b562010-08-18 09:41:07 +00003550 // Visit pointee types from a permissive context.
3551#define CheckPolymorphic(Type) \
3552 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3553 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3554 }
3555 CheckPolymorphic(PointerTypeLoc)
3556 CheckPolymorphic(ReferenceTypeLoc)
3557 CheckPolymorphic(MemberPointerTypeLoc)
3558 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003559 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003560
John McCall94c3b562010-08-18 09:41:07 +00003561 /// Handle all the types we haven't given a more specific
3562 /// implementation for above.
3563 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3564 // Every other kind of type that we haven't called out already
3565 // that has an inner type is either (1) sugar or (2) contains that
3566 // inner type in some way as a subobject.
3567 if (TypeLoc Next = TL.getNextTypeLoc())
3568 return Visit(Next, Sel);
3569
3570 // If there's no inner type and we're in a permissive context,
3571 // don't diagnose.
3572 if (Sel == Sema::AbstractNone) return;
3573
3574 // Check whether the type matches the abstract type.
3575 QualType T = TL.getType();
3576 if (T->isArrayType()) {
3577 Sel = Sema::AbstractArrayType;
3578 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003579 }
John McCall94c3b562010-08-18 09:41:07 +00003580 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3581 if (CT != Info.AbstractType) return;
3582
3583 // It matched; do some magic.
3584 if (Sel == Sema::AbstractArrayType) {
3585 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3586 << T << TL.getSourceRange();
3587 } else {
3588 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3589 << Sel << T << TL.getSourceRange();
3590 }
3591 Info.DiagnoseAbstractType();
3592 }
3593};
3594
3595void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3596 Sema::AbstractDiagSelID Sel) {
3597 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3598}
3599
3600}
3601
3602/// Check for invalid uses of an abstract type in a method declaration.
3603static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3604 CXXMethodDecl *MD) {
3605 // No need to do the check on definitions, which require that
3606 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003607 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003608 return;
3609
3610 // For safety's sake, just ignore it if we don't have type source
3611 // information. This should never happen for non-implicit methods,
3612 // but...
3613 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3614 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3615}
3616
3617/// Check for invalid uses of an abstract type within a class definition.
3618static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3619 CXXRecordDecl *RD) {
3620 for (CXXRecordDecl::decl_iterator
3621 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3622 Decl *D = *I;
3623 if (D->isImplicit()) continue;
3624
3625 // Methods and method templates.
3626 if (isa<CXXMethodDecl>(D)) {
3627 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3628 } else if (isa<FunctionTemplateDecl>(D)) {
3629 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3630 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3631
3632 // Fields and static variables.
3633 } else if (isa<FieldDecl>(D)) {
3634 FieldDecl *FD = cast<FieldDecl>(D);
3635 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3636 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3637 } else if (isa<VarDecl>(D)) {
3638 VarDecl *VD = cast<VarDecl>(D);
3639 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3640 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3641
3642 // Nested classes and class templates.
3643 } else if (isa<CXXRecordDecl>(D)) {
3644 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3645 } else if (isa<ClassTemplateDecl>(D)) {
3646 CheckAbstractClassUsage(Info,
3647 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3648 }
3649 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003650}
3651
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003652/// \brief Perform semantic checks on a class definition that has been
3653/// completing, introducing implicitly-declared members, checking for
3654/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003655void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003656 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003657 return;
3658
John McCall94c3b562010-08-18 09:41:07 +00003659 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3660 AbstractUsageInfo Info(*this, Record);
3661 CheckAbstractClassUsage(Info, Record);
3662 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003663
3664 // If this is not an aggregate type and has no user-declared constructor,
3665 // complain about any non-static data members of reference or const scalar
3666 // type, since they will never get initializers.
3667 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003668 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3669 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003670 bool Complained = false;
3671 for (RecordDecl::field_iterator F = Record->field_begin(),
3672 FEnd = Record->field_end();
3673 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003674 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003675 continue;
3676
Douglas Gregor325e5932010-04-15 00:00:53 +00003677 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003678 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003679 if (!Complained) {
3680 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3681 << Record->getTagKind() << Record;
3682 Complained = true;
3683 }
3684
3685 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3686 << F->getType()->isReferenceType()
3687 << F->getDeclName();
3688 }
3689 }
3690 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003691
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003692 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003693 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003694
3695 if (Record->getIdentifier()) {
3696 // C++ [class.mem]p13:
3697 // If T is the name of a class, then each of the following shall have a
3698 // name different from T:
3699 // - every member of every anonymous union that is a member of class T.
3700 //
3701 // C++ [class.mem]p14:
3702 // In addition, if class T has a user-declared constructor (12.1), every
3703 // non-static data member of class T shall have a name different from T.
3704 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003705 R.first != R.second; ++R.first) {
3706 NamedDecl *D = *R.first;
3707 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3708 isa<IndirectFieldDecl>(D)) {
3709 Diag(D->getLocation(), diag::err_member_name_of_class)
3710 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003711 break;
3712 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003713 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003714 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003715
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003716 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003717 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003718 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003719 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003720 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3721 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3722 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003723
3724 // See if a method overloads virtual methods in a base
3725 /// class without overriding any.
3726 if (!Record->isDependentType()) {
3727 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3728 MEnd = Record->method_end();
3729 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003730 if (!(*M)->isStatic())
3731 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003732 }
3733 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003734
Richard Smith9f569cc2011-10-01 02:31:28 +00003735 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3736 // function that is not a constructor declares that member function to be
3737 // const. [...] The class of which that function is a member shall be
3738 // a literal type.
3739 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003740 // If the class has virtual bases, any constexpr members will already have
3741 // been diagnosed by the checks performed on the member declaration, so
3742 // suppress this (less useful) diagnostic.
3743 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3744 !Record->isLiteral() && !Record->getNumVBases()) {
3745 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3746 MEnd = Record->method_end();
3747 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003748 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003749 switch (Record->getTemplateSpecializationKind()) {
3750 case TSK_ImplicitInstantiation:
3751 case TSK_ExplicitInstantiationDeclaration:
3752 case TSK_ExplicitInstantiationDefinition:
3753 // If a template instantiates to a non-literal type, but its members
3754 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003755 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003756 continue;
3757
3758 case TSK_Undeclared:
3759 case TSK_ExplicitSpecialization:
3760 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3761 PDiag(diag::err_constexpr_method_non_literal));
3762 break;
3763 }
3764
3765 // Only produce one error per class.
3766 break;
3767 }
3768 }
3769 }
3770
Sebastian Redlf677ea32011-02-05 19:23:19 +00003771 // Declare inherited constructors. We do this eagerly here because:
3772 // - The standard requires an eager diagnostic for conflicting inherited
3773 // constructors from different classes.
3774 // - The lazy declaration of the other implicit constructors is so as to not
3775 // waste space and performance on classes that are not meant to be
3776 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3777 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003778 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003779
Sean Hunteb88ae52011-05-23 21:07:59 +00003780 if (!Record->isDependentType())
3781 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003782}
3783
3784void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003785 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3786 ME = Record->method_end();
3787 MI != ME; ++MI) {
3788 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3789 switch (getSpecialMember(*MI)) {
3790 case CXXDefaultConstructor:
3791 CheckExplicitlyDefaultedDefaultConstructor(
3792 cast<CXXConstructorDecl>(*MI));
3793 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003794
Sean Huntcb45a0f2011-05-12 22:46:25 +00003795 case CXXDestructor:
3796 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3797 break;
3798
3799 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003800 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3801 break;
3802
Sean Huntcb45a0f2011-05-12 22:46:25 +00003803 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003804 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003805 break;
3806
Sean Hunt82713172011-05-25 23:16:36 +00003807 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003808 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003809 break;
3810
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003811 case CXXMoveAssignment:
3812 CheckExplicitlyDefaultedMoveAssignment(*MI);
3813 break;
3814
3815 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003816 llvm_unreachable("non-special member explicitly defaulted!");
3817 }
Sean Hunt001cad92011-05-10 00:49:42 +00003818 }
3819 }
3820
Sean Hunt001cad92011-05-10 00:49:42 +00003821}
3822
3823void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3824 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3825
3826 // Whether this was the first-declared instance of the constructor.
3827 // This affects whether we implicitly add an exception spec (and, eventually,
3828 // constexpr). It is also ill-formed to explicitly default a constructor such
3829 // that it would be deleted. (C++0x [decl.fct.def.default])
3830 bool First = CD == CD->getCanonicalDecl();
3831
Sean Hunt49634cf2011-05-13 06:10:58 +00003832 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003833 if (CD->getNumParams() != 0) {
3834 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3835 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003836 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003837 }
3838
3839 ImplicitExceptionSpecification Spec
3840 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3841 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003842 if (EPI.ExceptionSpecType == EST_Delayed) {
3843 // Exception specification depends on some deferred part of the class. We'll
3844 // try again when the class's definition has been fully processed.
3845 return;
3846 }
Sean Hunt001cad92011-05-10 00:49:42 +00003847 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3848 *ExceptionType = Context.getFunctionType(
3849 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3850
Richard Smith61802452011-12-22 02:22:31 +00003851 // C++11 [dcl.fct.def.default]p2:
3852 // An explicitly-defaulted function may be declared constexpr only if it
3853 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003854 // Do not apply this rule to templates, since core issue 1358 makes such
3855 // functions always instantiate to constexpr functions.
3856 if (CD->isConstexpr() &&
3857 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003858 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3859 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3860 << CXXDefaultConstructor;
3861 HadError = true;
3862 }
3863 }
3864 // and may have an explicit exception-specification only if it is compatible
3865 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003866 if (CtorType->hasExceptionSpec()) {
3867 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003868 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003869 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003870 PDiag(),
3871 ExceptionType, SourceLocation(),
3872 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003873 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003874 }
Richard Smith61802452011-12-22 02:22:31 +00003875 }
3876
3877 // If a function is explicitly defaulted on its first declaration,
3878 if (First) {
3879 // -- it is implicitly considered to be constexpr if the implicit
3880 // definition would be,
3881 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3882
3883 // -- it is implicitly considered to have the same
3884 // exception-specification as if it had been implicitly declared
3885 //
3886 // FIXME: a compatible, but different, explicit exception specification
3887 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003888 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithe653ba22012-02-26 00:31:33 +00003889
3890 // Such a function is also trivial if the implicitly-declared function
3891 // would have been.
3892 CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
Sean Hunt001cad92011-05-10 00:49:42 +00003893 }
Sean Huntca46d132011-05-12 03:51:48 +00003894
Sean Hunt49634cf2011-05-13 06:10:58 +00003895 if (HadError) {
3896 CD->setInvalidDecl();
3897 return;
3898 }
3899
Sean Hunte16da072011-10-10 06:18:57 +00003900 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003901 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003902 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003903 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003904 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003905 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003906 CD->setInvalidDecl();
3907 }
3908 }
3909}
3910
3911void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3912 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3913
3914 // Whether this was the first-declared instance of the constructor.
3915 bool First = CD == CD->getCanonicalDecl();
3916
3917 bool HadError = false;
3918 if (CD->getNumParams() != 1) {
3919 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3920 << CD->getSourceRange();
3921 HadError = true;
3922 }
3923
3924 ImplicitExceptionSpecification Spec(Context);
3925 bool Const;
3926 llvm::tie(Spec, Const) =
3927 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3928
3929 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3930 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3931 *ExceptionType = Context.getFunctionType(
3932 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3933
3934 // Check for parameter type matching.
3935 // This is a copy ctor so we know it's a cv-qualified reference to T.
3936 QualType ArgType = CtorType->getArgType(0);
3937 if (ArgType->getPointeeType().isVolatileQualified()) {
3938 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3939 HadError = true;
3940 }
3941 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3942 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3943 HadError = true;
3944 }
3945
Richard Smith61802452011-12-22 02:22:31 +00003946 // C++11 [dcl.fct.def.default]p2:
3947 // An explicitly-defaulted function may be declared constexpr only if it
3948 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003949 // Do not apply this rule to templates, since core issue 1358 makes such
3950 // functions always instantiate to constexpr functions.
3951 if (CD->isConstexpr() &&
3952 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003953 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3954 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3955 << CXXCopyConstructor;
3956 HadError = true;
3957 }
3958 }
3959 // and may have an explicit exception-specification only if it is compatible
3960 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003961 if (CtorType->hasExceptionSpec()) {
3962 if (CheckEquivalentExceptionSpec(
3963 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003964 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003965 PDiag(),
3966 ExceptionType, SourceLocation(),
3967 CtorType, CD->getLocation())) {
3968 HadError = true;
3969 }
Richard Smith61802452011-12-22 02:22:31 +00003970 }
3971
3972 // If a function is explicitly defaulted on its first declaration,
3973 if (First) {
3974 // -- it is implicitly considered to be constexpr if the implicit
3975 // definition would be,
3976 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3977
3978 // -- it is implicitly considered to have the same
3979 // exception-specification as if it had been implicitly declared, and
3980 //
3981 // FIXME: a compatible, but different, explicit exception specification
3982 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003983 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003984
3985 // -- [...] it shall have the same parameter type as if it had been
3986 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003987 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00003988
3989 // Such a function is also trivial if the implicitly-declared function
3990 // would have been.
3991 CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00003992 }
3993
3994 if (HadError) {
3995 CD->setInvalidDecl();
3996 return;
3997 }
3998
Sean Huntc32d6842011-10-11 04:55:36 +00003999 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004000 if (First) {
4001 CD->setDeletedAsWritten();
4002 } else {
4003 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004004 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004005 CD->setInvalidDecl();
4006 }
Sean Huntca46d132011-05-12 03:51:48 +00004007 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004008}
Sean Hunt001cad92011-05-10 00:49:42 +00004009
Sean Hunt2b188082011-05-14 05:23:28 +00004010void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4011 assert(MD->isExplicitlyDefaulted());
4012
4013 // Whether this was the first-declared instance of the operator
4014 bool First = MD == MD->getCanonicalDecl();
4015
4016 bool HadError = false;
4017 if (MD->getNumParams() != 1) {
4018 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4019 << MD->getSourceRange();
4020 HadError = true;
4021 }
4022
4023 QualType ReturnType =
4024 MD->getType()->getAs<FunctionType>()->getResultType();
4025 if (!ReturnType->isLValueReferenceType() ||
4026 !Context.hasSameType(
4027 Context.getCanonicalType(ReturnType->getPointeeType()),
4028 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4029 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4030 HadError = true;
4031 }
4032
4033 ImplicitExceptionSpecification Spec(Context);
4034 bool Const;
4035 llvm::tie(Spec, Const) =
4036 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4037
4038 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4039 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4040 *ExceptionType = Context.getFunctionType(
4041 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4042
Sean Hunt2b188082011-05-14 05:23:28 +00004043 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004044 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004045 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004046 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004047 } else {
4048 if (ArgType->getPointeeType().isVolatileQualified()) {
4049 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4050 HadError = true;
4051 }
4052 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4053 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4054 HadError = true;
4055 }
Sean Hunt2b188082011-05-14 05:23:28 +00004056 }
Sean Huntbe631222011-05-17 20:44:43 +00004057
Sean Hunt2b188082011-05-14 05:23:28 +00004058 if (OperType->getTypeQuals()) {
4059 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4060 HadError = true;
4061 }
4062
4063 if (OperType->hasExceptionSpec()) {
4064 if (CheckEquivalentExceptionSpec(
4065 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004066 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004067 PDiag(),
4068 ExceptionType, SourceLocation(),
4069 OperType, MD->getLocation())) {
4070 HadError = true;
4071 }
Richard Smith61802452011-12-22 02:22:31 +00004072 }
4073 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004074 // We set the declaration to have the computed exception spec here.
4075 // We duplicate the one parameter type.
4076 EPI.RefQualifier = OperType->getRefQualifier();
4077 EPI.ExtInfo = OperType->getExtInfo();
4078 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004079
4080 // Such a function is also trivial if the implicitly-declared function
4081 // would have been.
4082 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
Sean Hunt2b188082011-05-14 05:23:28 +00004083 }
4084
4085 if (HadError) {
4086 MD->setInvalidDecl();
4087 return;
4088 }
4089
Richard Smith7d5088a2012-02-18 02:02:13 +00004090 if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
Sean Hunt2b188082011-05-14 05:23:28 +00004091 if (First) {
4092 MD->setDeletedAsWritten();
4093 } else {
4094 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004095 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004096 MD->setInvalidDecl();
4097 }
4098 }
4099}
4100
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004101void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4102 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4103
4104 // Whether this was the first-declared instance of the constructor.
4105 bool First = CD == CD->getCanonicalDecl();
4106
4107 bool HadError = false;
4108 if (CD->getNumParams() != 1) {
4109 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4110 << CD->getSourceRange();
4111 HadError = true;
4112 }
4113
4114 ImplicitExceptionSpecification Spec(
4115 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4116
4117 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4118 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4119 *ExceptionType = Context.getFunctionType(
4120 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4121
4122 // Check for parameter type matching.
4123 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4124 QualType ArgType = CtorType->getArgType(0);
4125 if (ArgType->getPointeeType().isVolatileQualified()) {
4126 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4127 HadError = true;
4128 }
4129 if (ArgType->getPointeeType().isConstQualified()) {
4130 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4131 HadError = true;
4132 }
4133
Richard Smith61802452011-12-22 02:22:31 +00004134 // C++11 [dcl.fct.def.default]p2:
4135 // An explicitly-defaulted function may be declared constexpr only if it
4136 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004137 // Do not apply this rule to templates, since core issue 1358 makes such
4138 // functions always instantiate to constexpr functions.
4139 if (CD->isConstexpr() &&
4140 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004141 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4142 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4143 << CXXMoveConstructor;
4144 HadError = true;
4145 }
4146 }
4147 // and may have an explicit exception-specification only if it is compatible
4148 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004149 if (CtorType->hasExceptionSpec()) {
4150 if (CheckEquivalentExceptionSpec(
4151 PDiag(diag::err_incorrect_defaulted_exception_spec)
4152 << CXXMoveConstructor,
4153 PDiag(),
4154 ExceptionType, SourceLocation(),
4155 CtorType, CD->getLocation())) {
4156 HadError = true;
4157 }
Richard Smith61802452011-12-22 02:22:31 +00004158 }
4159
4160 // If a function is explicitly defaulted on its first declaration,
4161 if (First) {
4162 // -- it is implicitly considered to be constexpr if the implicit
4163 // definition would be,
4164 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4165
4166 // -- it is implicitly considered to have the same
4167 // exception-specification as if it had been implicitly declared, and
4168 //
4169 // FIXME: a compatible, but different, explicit exception specification
4170 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004171 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004172
4173 // -- [...] it shall have the same parameter type as if it had been
4174 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004175 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004176
4177 // Such a function is also trivial if the implicitly-declared function
4178 // would have been.
4179 CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004180 }
4181
4182 if (HadError) {
4183 CD->setInvalidDecl();
4184 return;
4185 }
4186
Sean Hunt769bb2d2011-10-11 06:43:29 +00004187 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004188 if (First) {
4189 CD->setDeletedAsWritten();
4190 } else {
4191 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4192 << CXXMoveConstructor;
4193 CD->setInvalidDecl();
4194 }
4195 }
4196}
4197
4198void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4199 assert(MD->isExplicitlyDefaulted());
4200
4201 // Whether this was the first-declared instance of the operator
4202 bool First = MD == MD->getCanonicalDecl();
4203
4204 bool HadError = false;
4205 if (MD->getNumParams() != 1) {
4206 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4207 << MD->getSourceRange();
4208 HadError = true;
4209 }
4210
4211 QualType ReturnType =
4212 MD->getType()->getAs<FunctionType>()->getResultType();
4213 if (!ReturnType->isLValueReferenceType() ||
4214 !Context.hasSameType(
4215 Context.getCanonicalType(ReturnType->getPointeeType()),
4216 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4217 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4218 HadError = true;
4219 }
4220
4221 ImplicitExceptionSpecification Spec(
4222 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4223
4224 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4225 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4226 *ExceptionType = Context.getFunctionType(
4227 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4228
4229 QualType ArgType = OperType->getArgType(0);
4230 if (!ArgType->isRValueReferenceType()) {
4231 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4232 HadError = true;
4233 } else {
4234 if (ArgType->getPointeeType().isVolatileQualified()) {
4235 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4236 HadError = true;
4237 }
4238 if (ArgType->getPointeeType().isConstQualified()) {
4239 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4240 HadError = true;
4241 }
4242 }
4243
4244 if (OperType->getTypeQuals()) {
4245 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4246 HadError = true;
4247 }
4248
4249 if (OperType->hasExceptionSpec()) {
4250 if (CheckEquivalentExceptionSpec(
4251 PDiag(diag::err_incorrect_defaulted_exception_spec)
4252 << CXXMoveAssignment,
4253 PDiag(),
4254 ExceptionType, SourceLocation(),
4255 OperType, MD->getLocation())) {
4256 HadError = true;
4257 }
Richard Smith61802452011-12-22 02:22:31 +00004258 }
4259 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004260 // We set the declaration to have the computed exception spec here.
4261 // We duplicate the one parameter type.
4262 EPI.RefQualifier = OperType->getRefQualifier();
4263 EPI.ExtInfo = OperType->getExtInfo();
4264 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004265
4266 // Such a function is also trivial if the implicitly-declared function
4267 // would have been.
4268 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004269 }
4270
4271 if (HadError) {
4272 MD->setInvalidDecl();
4273 return;
4274 }
4275
Richard Smith7d5088a2012-02-18 02:02:13 +00004276 if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004277 if (First) {
4278 MD->setDeletedAsWritten();
4279 } else {
4280 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4281 << CXXMoveAssignment;
4282 MD->setInvalidDecl();
4283 }
4284 }
4285}
4286
Sean Huntcb45a0f2011-05-12 22:46:25 +00004287void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4288 assert(DD->isExplicitlyDefaulted());
4289
4290 // Whether this was the first-declared instance of the destructor.
4291 bool First = DD == DD->getCanonicalDecl();
4292
4293 ImplicitExceptionSpecification Spec
4294 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4295 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4296 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4297 *ExceptionType = Context.getFunctionType(
4298 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4299
4300 if (DtorType->hasExceptionSpec()) {
4301 if (CheckEquivalentExceptionSpec(
4302 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004303 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004304 PDiag(),
4305 ExceptionType, SourceLocation(),
4306 DtorType, DD->getLocation())) {
4307 DD->setInvalidDecl();
4308 return;
4309 }
Richard Smith61802452011-12-22 02:22:31 +00004310 }
4311 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004312 // We set the declaration to have the computed exception spec here.
4313 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004314 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004315 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004316
4317 // Such a function is also trivial if the implicitly-declared function
4318 // would have been.
4319 DD->setTrivial(DD->getParent()->hasTrivialDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00004320 }
4321
Richard Smith7d5088a2012-02-18 02:02:13 +00004322 if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004323 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004324 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004325 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004326 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004327 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004328 DD->setInvalidDecl();
4329 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004330 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004331}
4332
Richard Smith7d5088a2012-02-18 02:02:13 +00004333namespace {
4334struct SpecialMemberDeletionInfo {
4335 Sema &S;
4336 CXXMethodDecl *MD;
4337 Sema::CXXSpecialMember CSM;
4338
4339 // Properties of the special member, computed for convenience.
4340 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4341 SourceLocation Loc;
4342
4343 bool AllFieldsAreConst;
4344
4345 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4346 Sema::CXXSpecialMember CSM)
4347 : S(S), MD(MD), CSM(CSM),
4348 IsConstructor(false), IsAssignment(false), IsMove(false),
4349 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4350 AllFieldsAreConst(true) {
4351 switch (CSM) {
4352 case Sema::CXXDefaultConstructor:
4353 case Sema::CXXCopyConstructor:
4354 IsConstructor = true;
4355 break;
4356 case Sema::CXXMoveConstructor:
4357 IsConstructor = true;
4358 IsMove = true;
4359 break;
4360 case Sema::CXXCopyAssignment:
4361 IsAssignment = true;
4362 break;
4363 case Sema::CXXMoveAssignment:
4364 IsAssignment = true;
4365 IsMove = true;
4366 break;
4367 case Sema::CXXDestructor:
4368 break;
4369 case Sema::CXXInvalid:
4370 llvm_unreachable("invalid special member kind");
4371 }
4372
4373 if (MD->getNumParams()) {
4374 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4375 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4376 }
4377 }
4378
4379 bool inUnion() const { return MD->getParent()->isUnion(); }
4380
4381 /// Look up the corresponding special member in the given class.
4382 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4383 unsigned TQ = MD->getTypeQualifiers();
4384 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4385 MD->getRefQualifier() == RQ_RValue,
4386 TQ & Qualifiers::Const,
4387 TQ & Qualifiers::Volatile);
4388 }
4389
Richard Smith9a561d52012-02-26 09:11:52 +00004390 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, FieldDecl *Field);
4391
Richard Smith7d5088a2012-02-18 02:02:13 +00004392 bool shouldDeleteForBase(CXXRecordDecl *BaseDecl, bool IsVirtualBase);
4393 bool shouldDeleteForField(FieldDecl *FD);
4394 bool shouldDeleteForAllConstMembers();
4395};
4396}
4397
Richard Smith9a561d52012-02-26 09:11:52 +00004398/// Check whether we should delete a special member function due to having a
4399/// direct or virtual base class or static data member of class type M.
4400bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4401 CXXRecordDecl *Class, FieldDecl *Field) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004402 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
4403 // -- any direct or virtual base class [...] has a type with a destructor
4404 // that is deleted or inaccessible
4405 if (!IsAssignment) {
Richard Smith9a561d52012-02-26 09:11:52 +00004406 CXXDestructorDecl *Dtor = S.LookupDestructor(Class);
4407 if (Dtor->isDeleted())
Richard Smith7d5088a2012-02-18 02:02:13 +00004408 return true;
Richard Smith9a561d52012-02-26 09:11:52 +00004409 if (S.CheckDestructorAccess(Loc, Dtor, S.PDiag()) != Sema::AR_accessible)
4410 return true;
4411
4412 // C++11 [class.dtor]p5:
4413 // -- X is a union-like class that has a variant member with a non-trivial
4414 // destructor
4415 if (CSM == Sema::CXXDestructor && Field && Field->getParent()->isUnion() &&
4416 !Dtor->isTrivial())
Richard Smith7d5088a2012-02-18 02:02:13 +00004417 return true;
4418 }
4419
4420 // C++11 [class.ctor]p5:
4421 // -- any direct or virtual base class [...] has class type M [...] and
4422 // either M has no default constructor or overload resolution as applied
4423 // to M's default constructor results in an ambiguity or in a function
4424 // that is deleted or inaccessible
4425 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4426 // -- a direct or virtual base class B that cannot be copied/moved because
4427 // overload resolution, as applied to B's corresponding special member,
4428 // results in an ambiguity or a function that is deleted or inaccessible
4429 // from the defaulted special member
Richard Smith9a561d52012-02-26 09:11:52 +00004430 // FIXME: in-class initializers should be handled here
Richard Smith7d5088a2012-02-18 02:02:13 +00004431 if (CSM != Sema::CXXDestructor) {
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
4526 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4527 UE = FieldRecord->field_end();
4528 UI != UE; ++UI) {
4529 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004530
4531 if (!UnionFieldType.isConstQualified())
4532 AllVariantFieldsAreConst = false;
4533
Richard Smith9a561d52012-02-26 09:11:52 +00004534 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4535 if (UnionFieldRecord &&
4536 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4537 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004538 }
4539
4540 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004541 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4542 FieldRecord->field_begin() != FieldRecord->field_end())
Richard Smith7d5088a2012-02-18 02:02:13 +00004543 return true;
4544
4545 // Don't try to initialize the anonymous union
4546 // This is technically non-conformant, but sanity demands it.
4547 return false;
4548 }
4549
Richard Smith9a561d52012-02-26 09:11:52 +00004550 // When checking a constructor, the field's destructor must be accessible
4551 // and not deleted.
4552 if (IsConstructor) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004553 CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4554 if (FieldDtor->isDeleted())
4555 return true;
4556 if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4557 Sema::AR_accessible)
4558 return true;
4559 }
4560
4561 // Check that the corresponding member of the field is accessible,
4562 // unique, and non-deleted. We don't do this if it has an explicit
4563 // initialization when default-constructing.
Richard Smith9a561d52012-02-26 09:11:52 +00004564 if (!(CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004565 Sema::SpecialMemberOverloadResult *SMOR = lookupIn(FieldRecord);
4566 if (!SMOR->hasSuccess())
4567 return true;
4568
4569 CXXMethodDecl *FieldMember = SMOR->getMethod();
Richard Smith9a561d52012-02-26 09:11:52 +00004570
4571 // We need the corresponding member of a union to be trivial so that
4572 // we can safely process all members simultaneously.
4573 if (inUnion() && !FieldMember->isTrivial())
4574 return true;
4575
Richard Smith7d5088a2012-02-18 02:02:13 +00004576 if (IsConstructor) {
4577 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4578 if (S.CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4579 S.PDiag()) != Sema::AR_accessible)
4580 return true;
4581
4582 // For a move operation, the corresponding operation must actually
4583 // be a move operation (and not a copy selected by overload
4584 // resolution) unless we are working on a trivially copyable class.
4585 if (IsMove && !FieldCtor->isMoveConstructor() &&
4586 !FieldRecord->isTriviallyCopyable())
4587 return true;
Richard Smith9a561d52012-02-26 09:11:52 +00004588 } else if (CSM == Sema::CXXDestructor) {
4589 CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4590 if (FieldDtor->isDeleted())
4591 return true;
4592 if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4593 Sema::AR_accessible)
4594 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004595 } else {
4596 assert(IsAssignment && "unexpected kind of special member");
4597 if (S.CheckDirectMemberAccess(Loc, FieldMember, S.PDiag())
4598 != Sema::AR_accessible)
4599 return true;
4600
4601 // -- for the move assignment operator, a non-static data member with a
4602 // type that does not have a move assignment operator and is not
4603 // trivially copyable.
4604 if (IsMove && !FieldMember->isMoveAssignmentOperator() &&
4605 !FieldRecord->isTriviallyCopyable())
4606 return true;
4607 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004608 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004609 } else if (IsAssignment && FieldType.isConstQualified()) {
4610 // C++11 [class.copy]p23:
4611 // -- a non-static data member of const non-class type (or array thereof)
4612 return true;
4613 }
4614
4615 return false;
4616}
4617
4618/// C++11 [class.ctor] p5:
4619/// A defaulted default constructor for a class X is defined as deleted if
4620/// X is a union and all of its variant members are of const-qualified type.
4621bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004622 // This is a silly definition, because it gives an empty union a deleted
4623 // default constructor. Don't do that.
4624 return CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4625 (MD->getParent()->field_begin() != MD->getParent()->field_end());
Richard Smith7d5088a2012-02-18 02:02:13 +00004626}
4627
4628/// Determine whether a defaulted special member function should be defined as
4629/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4630/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Sean Hunte16da072011-10-10 06:18:57 +00004631bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4632 assert(!MD->isInvalidDecl());
4633 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004634 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004635 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004636 return false;
4637
Richard Smith9a561d52012-02-26 09:11:52 +00004638 // FIXME: Provide the ability to diagnose why a special member was deleted.
4639
Richard Smith7d5088a2012-02-18 02:02:13 +00004640 // C++11 [expr.lambda.prim]p19:
4641 // The closure type associated with a lambda-expression has a
4642 // deleted (8.4.3) default constructor and a deleted copy
4643 // assignment operator.
4644 if (RD->isLambda() &&
4645 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment))
4646 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004647
Richard Smith9a561d52012-02-26 09:11:52 +00004648 // C++11 [class.dtor]p5:
4649 // -- for a virtual destructor, lookup of the non-array deallocation function
4650 // results in an ambiguity or in a function that is deleted or inaccessible
4651 if (CSM == Sema::CXXDestructor && MD->isVirtual()) {
4652 FunctionDecl *OperatorDelete = 0;
4653 DeclarationName Name =
4654 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4655 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4656 OperatorDelete, false))
4657 return true;
4658 }
4659
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 // For an anonymous struct or union, the copy and assignment special members
4661 // will never be used, so skip the check. For an anonymous union declared at
4662 // namespace scope, the constructor and destructor are used.
4663 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4664 RD->isAnonymousStructOrUnion())
4665 return false;
Sean Hunt71a682f2011-05-18 03:41:58 +00004666
Sean Huntc32d6842011-10-11 04:55:36 +00004667 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004668 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004669
Richard Smith7d5088a2012-02-18 02:02:13 +00004670 SpecialMemberDeletionInfo SMI(*this, MD, CSM);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004671
Sean Huntcdee3fe2011-05-11 22:34:38 +00004672 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004673 BE = RD->bases_end(); BI != BE; ++BI)
4674 if (!BI->isVirtual() &&
4675 SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), false))
4676 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004677
4678 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004679 BE = RD->vbases_end(); BI != BE; ++BI)
4680 if (SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), true))
4681 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004682
4683 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004684 FE = RD->field_end(); FI != FE; ++FI)
4685 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4686 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004687 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004688
Richard Smith7d5088a2012-02-18 02:02:13 +00004689 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004690 return true;
4691
4692 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004693}
4694
4695/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004696namespace {
4697 struct FindHiddenVirtualMethodData {
4698 Sema *S;
4699 CXXMethodDecl *Method;
4700 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004701 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004702 };
4703}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004704
4705/// \brief Member lookup function that determines whether a given C++
4706/// method overloads virtual methods in a base class without overriding any,
4707/// to be used with CXXRecordDecl::lookupInBases().
4708static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4709 CXXBasePath &Path,
4710 void *UserData) {
4711 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4712
4713 FindHiddenVirtualMethodData &Data
4714 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4715
4716 DeclarationName Name = Data.Method->getDeclName();
4717 assert(Name.getNameKind() == DeclarationName::Identifier);
4718
4719 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004720 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004721 for (Path.Decls = BaseRecord->lookup(Name);
4722 Path.Decls.first != Path.Decls.second;
4723 ++Path.Decls.first) {
4724 NamedDecl *D = *Path.Decls.first;
4725 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004726 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004727 foundSameNameMethod = true;
4728 // Interested only in hidden virtual methods.
4729 if (!MD->isVirtual())
4730 continue;
4731 // If the method we are checking overrides a method from its base
4732 // don't warn about the other overloaded methods.
4733 if (!Data.S->IsOverload(Data.Method, MD, false))
4734 return true;
4735 // Collect the overload only if its hidden.
4736 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4737 overloadedMethods.push_back(MD);
4738 }
4739 }
4740
4741 if (foundSameNameMethod)
4742 Data.OverloadedMethods.append(overloadedMethods.begin(),
4743 overloadedMethods.end());
4744 return foundSameNameMethod;
4745}
4746
4747/// \brief See if a method overloads virtual methods in a base class without
4748/// overriding any.
4749void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4750 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004751 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004752 return;
4753 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4754 return;
4755
4756 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4757 /*bool RecordPaths=*/false,
4758 /*bool DetectVirtual=*/false);
4759 FindHiddenVirtualMethodData Data;
4760 Data.Method = MD;
4761 Data.S = this;
4762
4763 // Keep the base methods that were overriden or introduced in the subclass
4764 // by 'using' in a set. A base method not in this set is hidden.
4765 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4766 res.first != res.second; ++res.first) {
4767 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4768 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4769 E = MD->end_overridden_methods();
4770 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004771 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004772 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4773 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004774 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004775 }
4776
4777 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4778 !Data.OverloadedMethods.empty()) {
4779 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4780 << MD << (Data.OverloadedMethods.size() > 1);
4781
4782 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4783 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4784 Diag(overloadedMD->getLocation(),
4785 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4786 }
4787 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004788}
4789
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004790void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004791 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004792 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004793 SourceLocation RBrac,
4794 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004795 if (!TagDecl)
4796 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004797
Douglas Gregor42af25f2009-05-11 19:58:34 +00004798 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004799
David Blaikie77b6de02011-09-22 02:58:26 +00004800 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004801 // strict aliasing violation!
4802 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004803 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004804
Douglas Gregor23c94db2010-07-02 17:43:08 +00004805 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004806 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004807}
4808
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004809/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4810/// special functions, such as the default constructor, copy
4811/// constructor, or destructor, to the given C++ class (C++
4812/// [special]p1). This routine can only be executed just before the
4813/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004814void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004815 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004816 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004817
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004818 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004819 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004820
David Blaikie4e4d0842012-03-11 07:00:24 +00004821 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004822 ++ASTContext::NumImplicitMoveConstructors;
4823
Douglas Gregora376d102010-07-02 21:50:04 +00004824 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4825 ++ASTContext::NumImplicitCopyAssignmentOperators;
4826
4827 // If we have a dynamic class, then the copy assignment operator may be
4828 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4829 // it shows up in the right place in the vtable and that we diagnose
4830 // problems with the implicit exception specification.
4831 if (ClassDecl->isDynamicClass())
4832 DeclareImplicitCopyAssignment(ClassDecl);
4833 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004834
David Blaikie4e4d0842012-03-11 07:00:24 +00004835 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
Richard Smithb701d3d2011-12-24 21:56:24 +00004836 ++ASTContext::NumImplicitMoveAssignmentOperators;
4837
4838 // Likewise for the move assignment operator.
4839 if (ClassDecl->isDynamicClass())
4840 DeclareImplicitMoveAssignment(ClassDecl);
4841 }
4842
Douglas Gregor4923aa22010-07-02 20:37:36 +00004843 if (!ClassDecl->hasUserDeclaredDestructor()) {
4844 ++ASTContext::NumImplicitDestructors;
4845
4846 // If we have a dynamic class, then the destructor may be virtual, so we
4847 // have to declare the destructor immediately. This ensures that, e.g., it
4848 // shows up in the right place in the vtable and that we diagnose problems
4849 // with the implicit exception specification.
4850 if (ClassDecl->isDynamicClass())
4851 DeclareImplicitDestructor(ClassDecl);
4852 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004853}
4854
Francois Pichet8387e2a2011-04-22 22:18:13 +00004855void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4856 if (!D)
4857 return;
4858
4859 int NumParamList = D->getNumTemplateParameterLists();
4860 for (int i = 0; i < NumParamList; i++) {
4861 TemplateParameterList* Params = D->getTemplateParameterList(i);
4862 for (TemplateParameterList::iterator Param = Params->begin(),
4863 ParamEnd = Params->end();
4864 Param != ParamEnd; ++Param) {
4865 NamedDecl *Named = cast<NamedDecl>(*Param);
4866 if (Named->getDeclName()) {
4867 S->AddDecl(Named);
4868 IdResolver.AddDecl(Named);
4869 }
4870 }
4871 }
4872}
4873
John McCalld226f652010-08-21 09:40:31 +00004874void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004875 if (!D)
4876 return;
4877
4878 TemplateParameterList *Params = 0;
4879 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4880 Params = Template->getTemplateParameters();
4881 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4882 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4883 Params = PartialSpec->getTemplateParameters();
4884 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004885 return;
4886
Douglas Gregor6569d682009-05-27 23:11:45 +00004887 for (TemplateParameterList::iterator Param = Params->begin(),
4888 ParamEnd = Params->end();
4889 Param != ParamEnd; ++Param) {
4890 NamedDecl *Named = cast<NamedDecl>(*Param);
4891 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004892 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004893 IdResolver.AddDecl(Named);
4894 }
4895 }
4896}
4897
John McCalld226f652010-08-21 09:40:31 +00004898void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004899 if (!RecordD) return;
4900 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004901 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004902 PushDeclContext(S, Record);
4903}
4904
John McCalld226f652010-08-21 09:40:31 +00004905void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004906 if (!RecordD) return;
4907 PopDeclContext();
4908}
4909
Douglas Gregor72b505b2008-12-16 21:30:33 +00004910/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4911/// parsing a top-level (non-nested) C++ class, and we are now
4912/// parsing those parts of the given Method declaration that could
4913/// not be parsed earlier (C++ [class.mem]p2), such as default
4914/// arguments. This action should enter the scope of the given
4915/// Method declaration as if we had just parsed the qualified method
4916/// name. However, it should not bring the parameters into scope;
4917/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004918void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004919}
4920
4921/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4922/// C++ method declaration. We're (re-)introducing the given
4923/// function parameter into scope for use in parsing later parts of
4924/// the method declaration. For example, we could see an
4925/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004926void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004927 if (!ParamD)
4928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
John McCalld226f652010-08-21 09:40:31 +00004930 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004931
4932 // If this parameter has an unparsed default argument, clear it out
4933 // to make way for the parsed default argument.
4934 if (Param->hasUnparsedDefaultArg())
4935 Param->setDefaultArg(0);
4936
John McCalld226f652010-08-21 09:40:31 +00004937 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004938 if (Param->getDeclName())
4939 IdResolver.AddDecl(Param);
4940}
4941
4942/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4943/// processing the delayed method declaration for Method. The method
4944/// declaration is now considered finished. There may be a separate
4945/// ActOnStartOfFunctionDef action later (not necessarily
4946/// immediately!) for this method, if it was also defined inside the
4947/// class body.
John McCalld226f652010-08-21 09:40:31 +00004948void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004949 if (!MethodD)
4950 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004951
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004952 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004953
John McCalld226f652010-08-21 09:40:31 +00004954 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004955
4956 // Now that we have our default arguments, check the constructor
4957 // again. It could produce additional diagnostics or affect whether
4958 // the class has implicitly-declared destructors, among other
4959 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004960 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4961 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004962
4963 // Check the default arguments, which we may have added.
4964 if (!Method->isInvalidDecl())
4965 CheckCXXDefaultArguments(Method);
4966}
4967
Douglas Gregor42a552f2008-11-05 20:51:48 +00004968/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004969/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004970/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004971/// emit diagnostics and set the invalid bit to true. In any case, the type
4972/// will be updated to reflect a well-formed type for the constructor and
4973/// returned.
4974QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004975 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004976 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004977
4978 // C++ [class.ctor]p3:
4979 // A constructor shall not be virtual (10.3) or static (9.4). A
4980 // constructor can be invoked for a const, volatile or const
4981 // volatile object. A constructor shall not be declared const,
4982 // volatile, or const volatile (9.3.2).
4983 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004984 if (!D.isInvalidType())
4985 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4986 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4987 << SourceRange(D.getIdentifierLoc());
4988 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004989 }
John McCalld931b082010-08-26 03:08:43 +00004990 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004991 if (!D.isInvalidType())
4992 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4993 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4994 << SourceRange(D.getIdentifierLoc());
4995 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004996 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004997 }
Mike Stump1eb44332009-09-09 15:08:12 +00004998
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005000 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005001 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005002 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5003 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005004 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5006 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005007 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5009 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005010 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005011 }
Mike Stump1eb44332009-09-09 15:08:12 +00005012
Douglas Gregorc938c162011-01-26 05:01:58 +00005013 // C++0x [class.ctor]p4:
5014 // A constructor shall not be declared with a ref-qualifier.
5015 if (FTI.hasRefQualifier()) {
5016 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5017 << FTI.RefQualifierIsLValueRef
5018 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5019 D.setInvalidType();
5020 }
5021
Douglas Gregor42a552f2008-11-05 20:51:48 +00005022 // Rebuild the function type "R" without any type qualifiers (in
5023 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005024 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005025 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005026 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5027 return R;
5028
5029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5030 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005031 EPI.RefQualifier = RQ_None;
5032
Chris Lattner65401802009-04-25 08:28:21 +00005033 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005034 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005035}
5036
Douglas Gregor72b505b2008-12-16 21:30:33 +00005037/// CheckConstructor - Checks a fully-formed constructor for
5038/// well-formedness, issuing any diagnostics required. Returns true if
5039/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005040void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005041 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005042 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5043 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005044 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005045
5046 // C++ [class.copy]p3:
5047 // A declaration of a constructor for a class X is ill-formed if
5048 // its first parameter is of type (optionally cv-qualified) X and
5049 // either there are no other parameters or else all other
5050 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005051 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005052 ((Constructor->getNumParams() == 1) ||
5053 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005054 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5055 Constructor->getTemplateSpecializationKind()
5056 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005057 QualType ParamType = Constructor->getParamDecl(0)->getType();
5058 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5059 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005060 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005061 const char *ConstRef
5062 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5063 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005064 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005065 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005066
5067 // FIXME: Rather that making the constructor invalid, we should endeavor
5068 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005069 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005070 }
5071 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005072}
5073
John McCall15442822010-08-04 01:04:25 +00005074/// CheckDestructor - Checks a fully-formed destructor definition for
5075/// well-formedness, issuing any diagnostics required. Returns true
5076/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005077bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005078 CXXRecordDecl *RD = Destructor->getParent();
5079
5080 if (Destructor->isVirtual()) {
5081 SourceLocation Loc;
5082
5083 if (!Destructor->isImplicit())
5084 Loc = Destructor->getLocation();
5085 else
5086 Loc = RD->getLocation();
5087
5088 // If we have a virtual destructor, look up the deallocation function
5089 FunctionDecl *OperatorDelete = 0;
5090 DeclarationName Name =
5091 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005092 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005093 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005094
Eli Friedman5f2987c2012-02-02 03:46:19 +00005095 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005096
5097 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005098 }
Anders Carlsson37909802009-11-30 21:24:50 +00005099
5100 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005101}
5102
Mike Stump1eb44332009-09-09 15:08:12 +00005103static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005104FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5105 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5106 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005107 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005108}
5109
Douglas Gregor42a552f2008-11-05 20:51:48 +00005110/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5111/// the well-formednes of the destructor declarator @p D with type @p
5112/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005113/// emit diagnostics and set the declarator to invalid. Even if this happens,
5114/// will be updated to reflect a well-formed type for the destructor and
5115/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005116QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005117 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005118 // C++ [class.dtor]p1:
5119 // [...] A typedef-name that names a class is a class-name
5120 // (7.1.3); however, a typedef-name that names a class shall not
5121 // be used as the identifier in the declarator for a destructor
5122 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005123 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005124 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005125 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005126 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005127 else if (const TemplateSpecializationType *TST =
5128 DeclaratorType->getAs<TemplateSpecializationType>())
5129 if (TST->isTypeAlias())
5130 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5131 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005132
5133 // C++ [class.dtor]p2:
5134 // A destructor is used to destroy objects of its class type. A
5135 // destructor takes no parameters, and no return type can be
5136 // specified for it (not even void). The address of a destructor
5137 // shall not be taken. A destructor shall not be static. A
5138 // destructor can be invoked for a const, volatile or const
5139 // volatile object. A destructor shall not be declared const,
5140 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005141 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005142 if (!D.isInvalidType())
5143 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5144 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005145 << SourceRange(D.getIdentifierLoc())
5146 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5147
John McCalld931b082010-08-26 03:08:43 +00005148 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005149 }
Chris Lattner65401802009-04-25 08:28:21 +00005150 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005151 // Destructors don't have return types, but the parser will
5152 // happily parse something like:
5153 //
5154 // class X {
5155 // float ~X();
5156 // };
5157 //
5158 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005159 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5160 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5161 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005162 }
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005164 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005165 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005166 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005167 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5168 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005169 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005170 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5171 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005172 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005173 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5174 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005175 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005176 }
5177
Douglas Gregorc938c162011-01-26 05:01:58 +00005178 // C++0x [class.dtor]p2:
5179 // A destructor shall not be declared with a ref-qualifier.
5180 if (FTI.hasRefQualifier()) {
5181 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5182 << FTI.RefQualifierIsLValueRef
5183 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5184 D.setInvalidType();
5185 }
5186
Douglas Gregor42a552f2008-11-05 20:51:48 +00005187 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005188 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005189 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5190
5191 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005192 FTI.freeArgs();
5193 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005194 }
5195
Mike Stump1eb44332009-09-09 15:08:12 +00005196 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005197 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005198 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005199 D.setInvalidType();
5200 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005201
5202 // Rebuild the function type "R" without any type qualifiers or
5203 // parameters (in case any of the errors above fired) and with
5204 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005205 // types.
John McCalle23cf432010-12-14 08:05:40 +00005206 if (!D.isInvalidType())
5207 return R;
5208
Douglas Gregord92ec472010-07-01 05:10:53 +00005209 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005210 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5211 EPI.Variadic = false;
5212 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005213 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005214 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005215}
5216
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005217/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5218/// well-formednes of the conversion function declarator @p D with
5219/// type @p R. If there are any errors in the declarator, this routine
5220/// will emit diagnostics and return true. Otherwise, it will return
5221/// false. Either way, the type @p R will be updated to reflect a
5222/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005223void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005224 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005225 // C++ [class.conv.fct]p1:
5226 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005227 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005228 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005229 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005230 if (!D.isInvalidType())
5231 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5232 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5233 << SourceRange(D.getIdentifierLoc());
5234 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005235 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005236 }
John McCalla3f81372010-04-13 00:04:31 +00005237
5238 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5239
Chris Lattner6e475012009-04-25 08:35:12 +00005240 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005241 // Conversion functions don't have return types, but the parser will
5242 // happily parse something like:
5243 //
5244 // class X {
5245 // float operator bool();
5246 // };
5247 //
5248 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005249 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5250 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5251 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005252 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005253 }
5254
John McCalla3f81372010-04-13 00:04:31 +00005255 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5256
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005257 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005258 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005259 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5260
5261 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005262 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005263 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005264 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005265 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005266 D.setInvalidType();
5267 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005268
John McCalla3f81372010-04-13 00:04:31 +00005269 // Diagnose "&operator bool()" and other such nonsense. This
5270 // is actually a gcc extension which we don't support.
5271 if (Proto->getResultType() != ConvType) {
5272 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5273 << Proto->getResultType();
5274 D.setInvalidType();
5275 ConvType = Proto->getResultType();
5276 }
5277
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005278 // C++ [class.conv.fct]p4:
5279 // The conversion-type-id shall not represent a function type nor
5280 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005281 if (ConvType->isArrayType()) {
5282 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5283 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005284 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005285 } else if (ConvType->isFunctionType()) {
5286 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5287 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005288 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005289 }
5290
5291 // Rebuild the function type "R" without any parameters (in case any
5292 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005293 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005294 if (D.isInvalidType())
5295 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005296
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005297 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005298 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005299 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005300 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005301 diag::warn_cxx98_compat_explicit_conversion_functions :
5302 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005303 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005304}
5305
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005306/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5307/// the declaration of the given C++ conversion function. This routine
5308/// is responsible for recording the conversion function in the C++
5309/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005310Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005311 assert(Conversion && "Expected to receive a conversion function declaration");
5312
Douglas Gregor9d350972008-12-12 08:25:50 +00005313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005314
5315 // Make sure we aren't redeclaring the conversion function.
5316 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005317
5318 // C++ [class.conv.fct]p1:
5319 // [...] A conversion function is never used to convert a
5320 // (possibly cv-qualified) object to the (possibly cv-qualified)
5321 // same object type (or a reference to it), to a (possibly
5322 // cv-qualified) base class of that type (or a reference to it),
5323 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005324 // FIXME: Suppress this warning if the conversion function ends up being a
5325 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005326 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005328 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005329 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005330 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5331 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005332 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005333 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005334 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5335 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005336 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005337 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005338 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005339 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005340 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005341 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005342 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005343 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005344 }
5345
Douglas Gregore80622f2010-09-29 04:25:11 +00005346 if (FunctionTemplateDecl *ConversionTemplate
5347 = Conversion->getDescribedFunctionTemplate())
5348 return ConversionTemplate;
5349
John McCalld226f652010-08-21 09:40:31 +00005350 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005351}
5352
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005353//===----------------------------------------------------------------------===//
5354// Namespace Handling
5355//===----------------------------------------------------------------------===//
5356
John McCallea318642010-08-26 09:15:37 +00005357
5358
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005359/// ActOnStartNamespaceDef - This is called at the start of a namespace
5360/// definition.
John McCalld226f652010-08-21 09:40:31 +00005361Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005362 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005363 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005364 SourceLocation IdentLoc,
5365 IdentifierInfo *II,
5366 SourceLocation LBrace,
5367 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005368 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5369 // For anonymous namespace, take the location of the left brace.
5370 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005371 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005372 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005373 bool IsStd = false;
5374 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005375 Scope *DeclRegionScope = NamespcScope->getParent();
5376
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005377 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005378 if (II) {
5379 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005380 // The identifier in an original-namespace-definition shall not
5381 // have been previously defined in the declarative region in
5382 // which the original-namespace-definition appears. The
5383 // identifier in an original-namespace-definition is the name of
5384 // the namespace. Subsequently in that declarative region, it is
5385 // treated as an original-namespace-name.
5386 //
5387 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005388 // look through using directives, just look for any ordinary names.
5389
5390 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005391 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5392 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005393 NamedDecl *PrevDecl = 0;
5394 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005395 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005396 R.first != R.second; ++R.first) {
5397 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5398 PrevDecl = *R.first;
5399 break;
5400 }
5401 }
5402
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005403 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5404
5405 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005406 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005407 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005408 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005409 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005410 // The user probably just forgot the 'inline', so suggest that it
5411 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005412 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005413 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5414 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005415 Diag(Loc, diag::err_inline_namespace_mismatch)
5416 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005417 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005418 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5419
5420 IsInline = PrevNS->isInline();
5421 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005422 } else if (PrevDecl) {
5423 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005424 Diag(Loc, diag::err_redefinition_different_kind)
5425 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005426 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005427 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005428 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005429 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005430 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005431 // This is the first "real" definition of the namespace "std", so update
5432 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005433 PrevNS = getStdNamespace();
5434 IsStd = true;
5435 AddToKnown = !IsInline;
5436 } else {
5437 // We've seen this namespace for the first time.
5438 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005439 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005440 } else {
John McCall9aeed322009-10-01 00:25:31 +00005441 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005442
5443 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005444 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005445 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005446 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005447 } else {
5448 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005449 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005450 }
5451
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005452 if (PrevNS && IsInline != PrevNS->isInline()) {
5453 // inline-ness must match
5454 Diag(Loc, diag::err_inline_namespace_mismatch)
5455 << IsInline;
5456 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005457
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005458 // Recover by ignoring the new namespace's inline status.
5459 IsInline = PrevNS->isInline();
5460 }
5461 }
5462
5463 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5464 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005465 if (IsInvalid)
5466 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005467
5468 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005469
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005470 // FIXME: Should we be merging attributes?
5471 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005472 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005473
5474 if (IsStd)
5475 StdNamespace = Namespc;
5476 if (AddToKnown)
5477 KnownNamespaces[Namespc] = false;
5478
5479 if (II) {
5480 PushOnScopeChains(Namespc, DeclRegionScope);
5481 } else {
5482 // Link the anonymous namespace into its parent.
5483 DeclContext *Parent = CurContext->getRedeclContext();
5484 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5485 TU->setAnonymousNamespace(Namespc);
5486 } else {
5487 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005488 }
John McCall9aeed322009-10-01 00:25:31 +00005489
Douglas Gregora4181472010-03-24 00:46:35 +00005490 CurContext->addDecl(Namespc);
5491
John McCall9aeed322009-10-01 00:25:31 +00005492 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5493 // behaves as if it were replaced by
5494 // namespace unique { /* empty body */ }
5495 // using namespace unique;
5496 // namespace unique { namespace-body }
5497 // where all occurrences of 'unique' in a translation unit are
5498 // replaced by the same identifier and this identifier differs
5499 // from all other identifiers in the entire program.
5500
5501 // We just create the namespace with an empty name and then add an
5502 // implicit using declaration, just like the standard suggests.
5503 //
5504 // CodeGen enforces the "universally unique" aspect by giving all
5505 // declarations semantically contained within an anonymous
5506 // namespace internal linkage.
5507
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005508 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005509 UsingDirectiveDecl* UD
5510 = UsingDirectiveDecl::Create(Context, CurContext,
5511 /* 'using' */ LBrace,
5512 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005513 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005514 /* identifier */ SourceLocation(),
5515 Namespc,
5516 /* Ancestor */ CurContext);
5517 UD->setImplicit();
5518 CurContext->addDecl(UD);
5519 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005520 }
5521
5522 // Although we could have an invalid decl (i.e. the namespace name is a
5523 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005524 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5525 // for the namespace has the declarations that showed up in that particular
5526 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005527 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005528 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005529}
5530
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005531/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5532/// is a namespace alias, returns the namespace it points to.
5533static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5534 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5535 return AD->getNamespace();
5536 return dyn_cast_or_null<NamespaceDecl>(D);
5537}
5538
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005539/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5540/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005541void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005542 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5543 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005544 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005545 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005546 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005547 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005548}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005549
John McCall384aff82010-08-25 07:42:41 +00005550CXXRecordDecl *Sema::getStdBadAlloc() const {
5551 return cast_or_null<CXXRecordDecl>(
5552 StdBadAlloc.get(Context.getExternalSource()));
5553}
5554
5555NamespaceDecl *Sema::getStdNamespace() const {
5556 return cast_or_null<NamespaceDecl>(
5557 StdNamespace.get(Context.getExternalSource()));
5558}
5559
Douglas Gregor66992202010-06-29 17:53:46 +00005560/// \brief Retrieve the special "std" namespace, which may require us to
5561/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005562NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005563 if (!StdNamespace) {
5564 // The "std" namespace has not yet been defined, so build one implicitly.
5565 StdNamespace = NamespaceDecl::Create(Context,
5566 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005567 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005568 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005569 &PP.getIdentifierTable().get("std"),
5570 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005571 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005572 }
5573
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005574 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005575}
5576
Sebastian Redl395e04d2012-01-17 22:49:33 +00005577bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005578 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005579 "Looking for std::initializer_list outside of C++.");
5580
5581 // We're looking for implicit instantiations of
5582 // template <typename E> class std::initializer_list.
5583
5584 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5585 return false;
5586
Sebastian Redl84760e32012-01-17 22:49:58 +00005587 ClassTemplateDecl *Template = 0;
5588 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005589
Sebastian Redl84760e32012-01-17 22:49:58 +00005590 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005591
Sebastian Redl84760e32012-01-17 22:49:58 +00005592 ClassTemplateSpecializationDecl *Specialization =
5593 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5594 if (!Specialization)
5595 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005596
Sebastian Redl84760e32012-01-17 22:49:58 +00005597 Template = Specialization->getSpecializedTemplate();
5598 Arguments = Specialization->getTemplateArgs().data();
5599 } else if (const TemplateSpecializationType *TST =
5600 Ty->getAs<TemplateSpecializationType>()) {
5601 Template = dyn_cast_or_null<ClassTemplateDecl>(
5602 TST->getTemplateName().getAsTemplateDecl());
5603 Arguments = TST->getArgs();
5604 }
5605 if (!Template)
5606 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005607
5608 if (!StdInitializerList) {
5609 // Haven't recognized std::initializer_list yet, maybe this is it.
5610 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5611 if (TemplateClass->getIdentifier() !=
5612 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005613 !getStdNamespace()->InEnclosingNamespaceSetOf(
5614 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005615 return false;
5616 // This is a template called std::initializer_list, but is it the right
5617 // template?
5618 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005619 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005620 return false;
5621 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5622 return false;
5623
5624 // It's the right template.
5625 StdInitializerList = Template;
5626 }
5627
5628 if (Template != StdInitializerList)
5629 return false;
5630
5631 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005632 if (Element)
5633 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005634 return true;
5635}
5636
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005637static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5638 NamespaceDecl *Std = S.getStdNamespace();
5639 if (!Std) {
5640 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5641 return 0;
5642 }
5643
5644 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5645 Loc, Sema::LookupOrdinaryName);
5646 if (!S.LookupQualifiedName(Result, Std)) {
5647 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5648 return 0;
5649 }
5650 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5651 if (!Template) {
5652 Result.suppressDiagnostics();
5653 // We found something weird. Complain about the first thing we found.
5654 NamedDecl *Found = *Result.begin();
5655 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5656 return 0;
5657 }
5658
5659 // We found some template called std::initializer_list. Now verify that it's
5660 // correct.
5661 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005662 if (Params->getMinRequiredArguments() != 1 ||
5663 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005664 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5665 return 0;
5666 }
5667
5668 return Template;
5669}
5670
5671QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5672 if (!StdInitializerList) {
5673 StdInitializerList = LookupStdInitializerList(*this, Loc);
5674 if (!StdInitializerList)
5675 return QualType();
5676 }
5677
5678 TemplateArgumentListInfo Args(Loc, Loc);
5679 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5680 Context.getTrivialTypeSourceInfo(Element,
5681 Loc)));
5682 return Context.getCanonicalType(
5683 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5684}
5685
Sebastian Redl98d36062012-01-17 22:50:14 +00005686bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5687 // C++ [dcl.init.list]p2:
5688 // A constructor is an initializer-list constructor if its first parameter
5689 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5690 // std::initializer_list<E> for some type E, and either there are no other
5691 // parameters or else all other parameters have default arguments.
5692 if (Ctor->getNumParams() < 1 ||
5693 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5694 return false;
5695
5696 QualType ArgType = Ctor->getParamDecl(0)->getType();
5697 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5698 ArgType = RT->getPointeeType().getUnqualifiedType();
5699
5700 return isStdInitializerList(ArgType, 0);
5701}
5702
Douglas Gregor9172aa62011-03-26 22:25:30 +00005703/// \brief Determine whether a using statement is in a context where it will be
5704/// apply in all contexts.
5705static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5706 switch (CurContext->getDeclKind()) {
5707 case Decl::TranslationUnit:
5708 return true;
5709 case Decl::LinkageSpec:
5710 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5711 default:
5712 return false;
5713 }
5714}
5715
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005716namespace {
5717
5718// Callback to only accept typo corrections that are namespaces.
5719class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5720 public:
5721 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5722 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5723 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5724 }
5725 return false;
5726 }
5727};
5728
5729}
5730
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005731static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5732 CXXScopeSpec &SS,
5733 SourceLocation IdentLoc,
5734 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005735 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005736 R.clear();
5737 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005738 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005739 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005740 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5741 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005742 if (DeclContext *DC = S.computeDeclContext(SS, false))
5743 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5744 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5745 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5746 else
5747 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5748 << Ident << CorrectedQuotedStr
5749 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005750
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005751 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5752 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005753
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005754 Ident = Corrected.getCorrectionAsIdentifierInfo();
5755 R.addDecl(Corrected.getCorrectionDecl());
5756 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005757 }
5758 return false;
5759}
5760
John McCalld226f652010-08-21 09:40:31 +00005761Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005762 SourceLocation UsingLoc,
5763 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005764 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005765 SourceLocation IdentLoc,
5766 IdentifierInfo *NamespcName,
5767 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005768 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5769 assert(NamespcName && "Invalid NamespcName.");
5770 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005771
5772 // This can only happen along a recovery path.
5773 while (S->getFlags() & Scope::TemplateParamScope)
5774 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005775 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005776
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005777 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005778 NestedNameSpecifier *Qualifier = 0;
5779 if (SS.isSet())
5780 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5781
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005782 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005783 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5784 LookupParsedName(R, S, &SS);
5785 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005786 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005787
Douglas Gregor66992202010-06-29 17:53:46 +00005788 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005789 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005790 // Allow "using namespace std;" or "using namespace ::std;" even if
5791 // "std" hasn't been defined yet, for GCC compatibility.
5792 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5793 NamespcName->isStr("std")) {
5794 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005795 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005796 R.resolveKind();
5797 }
5798 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005799 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005800 }
5801
John McCallf36e02d2009-10-09 21:13:30 +00005802 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005803 NamedDecl *Named = R.getFoundDecl();
5804 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5805 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005806 // C++ [namespace.udir]p1:
5807 // A using-directive specifies that the names in the nominated
5808 // namespace can be used in the scope in which the
5809 // using-directive appears after the using-directive. During
5810 // unqualified name lookup (3.4.1), the names appear as if they
5811 // were declared in the nearest enclosing namespace which
5812 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005813 // namespace. [Note: in this context, "contains" means "contains
5814 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005815
5816 // Find enclosing context containing both using-directive and
5817 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005818 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005819 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5820 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5821 CommonAncestor = CommonAncestor->getParent();
5822
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005823 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005824 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005825 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005826
Douglas Gregor9172aa62011-03-26 22:25:30 +00005827 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005828 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005829 Diag(IdentLoc, diag::warn_using_directive_in_header);
5830 }
5831
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005832 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005833 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005834 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005835 }
5836
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005837 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005838 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005839}
5840
5841void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005842 // If the scope has an associated entity and the using directive is at
5843 // namespace or translation unit scope, add the UsingDirectiveDecl into
5844 // its lookup structure so qualified name lookup can find it.
5845 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5846 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005847 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005848 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005849 // Otherwise, it is at block sope. The using-directives will affect lookup
5850 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005851 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005852}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005853
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005854
John McCalld226f652010-08-21 09:40:31 +00005855Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005856 AccessSpecifier AS,
5857 bool HasUsingKeyword,
5858 SourceLocation UsingLoc,
5859 CXXScopeSpec &SS,
5860 UnqualifiedId &Name,
5861 AttributeList *AttrList,
5862 bool IsTypeName,
5863 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005864 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005865
Douglas Gregor12c118a2009-11-04 16:30:06 +00005866 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005867 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005868 case UnqualifiedId::IK_Identifier:
5869 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005870 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005871 case UnqualifiedId::IK_ConversionFunctionId:
5872 break;
5873
5874 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005875 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005876 // C++0x inherited constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005877 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005878 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005879 diag::warn_cxx98_compat_using_decl_constructor :
5880 diag::err_using_decl_constructor)
5881 << SS.getRange();
5882
David Blaikie4e4d0842012-03-11 07:00:24 +00005883 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005884
John McCalld226f652010-08-21 09:40:31 +00005885 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005886
5887 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005888 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005889 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005890 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005891
5892 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005893 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005894 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005895 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005896 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005897
5898 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5899 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005900 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005901 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005902
John McCall60fa3cf2009-12-11 02:10:03 +00005903 // Warn about using declarations.
5904 // TODO: store that the declaration was written without 'using' and
5905 // talk about access decls instead of using decls in the
5906 // diagnostics.
5907 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005908 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005909
5910 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005911 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005912 }
5913
Douglas Gregor56c04582010-12-16 00:46:58 +00005914 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5915 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5916 return 0;
5917
John McCall9488ea12009-11-17 05:59:44 +00005918 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005919 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005920 /* IsInstantiation */ false,
5921 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005922 if (UD)
5923 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005924
John McCalld226f652010-08-21 09:40:31 +00005925 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005926}
5927
Douglas Gregor09acc982010-07-07 23:08:52 +00005928/// \brief Determine whether a using declaration considers the given
5929/// declarations as "equivalent", e.g., if they are redeclarations of
5930/// the same entity or are both typedefs of the same type.
5931static bool
5932IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5933 bool &SuppressRedeclaration) {
5934 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5935 SuppressRedeclaration = false;
5936 return true;
5937 }
5938
Richard Smith162e1c12011-04-15 14:24:37 +00005939 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5940 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005941 SuppressRedeclaration = true;
5942 return Context.hasSameType(TD1->getUnderlyingType(),
5943 TD2->getUnderlyingType());
5944 }
5945
5946 return false;
5947}
5948
5949
John McCall9f54ad42009-12-10 09:41:52 +00005950/// Determines whether to create a using shadow decl for a particular
5951/// decl, given the set of decls existing prior to this using lookup.
5952bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5953 const LookupResult &Previous) {
5954 // Diagnose finding a decl which is not from a base class of the
5955 // current class. We do this now because there are cases where this
5956 // function will silently decide not to build a shadow decl, which
5957 // will pre-empt further diagnostics.
5958 //
5959 // We don't need to do this in C++0x because we do the check once on
5960 // the qualifier.
5961 //
5962 // FIXME: diagnose the following if we care enough:
5963 // struct A { int foo; };
5964 // struct B : A { using A::foo; };
5965 // template <class T> struct C : A {};
5966 // template <class T> struct D : C<T> { using B::foo; } // <---
5967 // This is invalid (during instantiation) in C++03 because B::foo
5968 // resolves to the using decl in B, which is not a base class of D<T>.
5969 // We can't diagnose it immediately because C<T> is an unknown
5970 // specialization. The UsingShadowDecl in D<T> then points directly
5971 // to A::foo, which will look well-formed when we instantiate.
5972 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005973 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005974 DeclContext *OrigDC = Orig->getDeclContext();
5975
5976 // Handle enums and anonymous structs.
5977 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5978 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5979 while (OrigRec->isAnonymousStructOrUnion())
5980 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5981
5982 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5983 if (OrigDC == CurContext) {
5984 Diag(Using->getLocation(),
5985 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005986 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005987 Diag(Orig->getLocation(), diag::note_using_decl_target);
5988 return true;
5989 }
5990
Douglas Gregordc355712011-02-25 00:36:19 +00005991 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005992 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005993 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005994 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005995 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005996 Diag(Orig->getLocation(), diag::note_using_decl_target);
5997 return true;
5998 }
5999 }
6000
6001 if (Previous.empty()) return false;
6002
6003 NamedDecl *Target = Orig;
6004 if (isa<UsingShadowDecl>(Target))
6005 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6006
John McCalld7533ec2009-12-11 02:33:26 +00006007 // If the target happens to be one of the previous declarations, we
6008 // don't have a conflict.
6009 //
6010 // FIXME: but we might be increasing its access, in which case we
6011 // should redeclare it.
6012 NamedDecl *NonTag = 0, *Tag = 0;
6013 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6014 I != E; ++I) {
6015 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006016 bool Result;
6017 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6018 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006019
6020 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6021 }
6022
John McCall9f54ad42009-12-10 09:41:52 +00006023 if (Target->isFunctionOrFunctionTemplate()) {
6024 FunctionDecl *FD;
6025 if (isa<FunctionTemplateDecl>(Target))
6026 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6027 else
6028 FD = cast<FunctionDecl>(Target);
6029
6030 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006031 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006032 case Ovl_Overload:
6033 return false;
6034
6035 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006036 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006037 break;
6038
6039 // We found a decl with the exact signature.
6040 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006041 // If we're in a record, we want to hide the target, so we
6042 // return true (without a diagnostic) to tell the caller not to
6043 // build a shadow decl.
6044 if (CurContext->isRecord())
6045 return true;
6046
6047 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006048 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006049 break;
6050 }
6051
6052 Diag(Target->getLocation(), diag::note_using_decl_target);
6053 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6054 return true;
6055 }
6056
6057 // Target is not a function.
6058
John McCall9f54ad42009-12-10 09:41:52 +00006059 if (isa<TagDecl>(Target)) {
6060 // No conflict between a tag and a non-tag.
6061 if (!Tag) return false;
6062
John McCall41ce66f2009-12-10 19:51:03 +00006063 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006064 Diag(Target->getLocation(), diag::note_using_decl_target);
6065 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6066 return true;
6067 }
6068
6069 // No conflict between a tag and a non-tag.
6070 if (!NonTag) return false;
6071
John McCall41ce66f2009-12-10 19:51:03 +00006072 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006073 Diag(Target->getLocation(), diag::note_using_decl_target);
6074 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6075 return true;
6076}
6077
John McCall9488ea12009-11-17 05:59:44 +00006078/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006079UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006080 UsingDecl *UD,
6081 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006082
6083 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006084 NamedDecl *Target = Orig;
6085 if (isa<UsingShadowDecl>(Target)) {
6086 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6087 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006088 }
6089
6090 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006091 = UsingShadowDecl::Create(Context, CurContext,
6092 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006093 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006094
6095 Shadow->setAccess(UD->getAccess());
6096 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6097 Shadow->setInvalidDecl();
6098
John McCall9488ea12009-11-17 05:59:44 +00006099 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006100 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006101 else
John McCall604e7f12009-12-08 07:46:18 +00006102 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006103
John McCall604e7f12009-12-08 07:46:18 +00006104
John McCall9f54ad42009-12-10 09:41:52 +00006105 return Shadow;
6106}
John McCall604e7f12009-12-08 07:46:18 +00006107
John McCall9f54ad42009-12-10 09:41:52 +00006108/// Hides a using shadow declaration. This is required by the current
6109/// using-decl implementation when a resolvable using declaration in a
6110/// class is followed by a declaration which would hide or override
6111/// one or more of the using decl's targets; for example:
6112///
6113/// struct Base { void foo(int); };
6114/// struct Derived : Base {
6115/// using Base::foo;
6116/// void foo(int);
6117/// };
6118///
6119/// The governing language is C++03 [namespace.udecl]p12:
6120///
6121/// When a using-declaration brings names from a base class into a
6122/// derived class scope, member functions in the derived class
6123/// override and/or hide member functions with the same name and
6124/// parameter types in a base class (rather than conflicting).
6125///
6126/// There are two ways to implement this:
6127/// (1) optimistically create shadow decls when they're not hidden
6128/// by existing declarations, or
6129/// (2) don't create any shadow decls (or at least don't make them
6130/// visible) until we've fully parsed/instantiated the class.
6131/// The problem with (1) is that we might have to retroactively remove
6132/// a shadow decl, which requires several O(n) operations because the
6133/// decl structures are (very reasonably) not designed for removal.
6134/// (2) avoids this but is very fiddly and phase-dependent.
6135void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006136 if (Shadow->getDeclName().getNameKind() ==
6137 DeclarationName::CXXConversionFunctionName)
6138 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6139
John McCall9f54ad42009-12-10 09:41:52 +00006140 // Remove it from the DeclContext...
6141 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006142
John McCall9f54ad42009-12-10 09:41:52 +00006143 // ...and the scope, if applicable...
6144 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006145 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006146 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006147 }
6148
John McCall9f54ad42009-12-10 09:41:52 +00006149 // ...and the using decl.
6150 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6151
6152 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006153 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006154}
6155
John McCall7ba107a2009-11-18 02:36:19 +00006156/// Builds a using declaration.
6157///
6158/// \param IsInstantiation - Whether this call arises from an
6159/// instantiation of an unresolved using declaration. We treat
6160/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006161NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6162 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006163 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006164 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006165 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006166 bool IsInstantiation,
6167 bool IsTypeName,
6168 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006169 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006170 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006171 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006172
Anders Carlsson550b14b2009-08-28 05:49:21 +00006173 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006174
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006175 if (SS.isEmpty()) {
6176 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006177 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006178 }
Mike Stump1eb44332009-09-09 15:08:12 +00006179
John McCall9f54ad42009-12-10 09:41:52 +00006180 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006181 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006182 ForRedeclaration);
6183 Previous.setHideTags(false);
6184 if (S) {
6185 LookupName(Previous, S);
6186
6187 // It is really dumb that we have to do this.
6188 LookupResult::Filter F = Previous.makeFilter();
6189 while (F.hasNext()) {
6190 NamedDecl *D = F.next();
6191 if (!isDeclInScope(D, CurContext, S))
6192 F.erase();
6193 }
6194 F.done();
6195 } else {
6196 assert(IsInstantiation && "no scope in non-instantiation");
6197 assert(CurContext->isRecord() && "scope not record in instantiation");
6198 LookupQualifiedName(Previous, CurContext);
6199 }
6200
John McCall9f54ad42009-12-10 09:41:52 +00006201 // Check for invalid redeclarations.
6202 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6203 return 0;
6204
6205 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006206 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6207 return 0;
6208
John McCallaf8e6ed2009-11-12 03:15:40 +00006209 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006210 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006211 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006212 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006213 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006214 // FIXME: not all declaration name kinds are legal here
6215 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6216 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006217 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006218 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006219 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006220 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6221 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006222 }
John McCalled976492009-12-04 22:46:56 +00006223 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006224 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6225 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006226 }
John McCalled976492009-12-04 22:46:56 +00006227 D->setAccess(AS);
6228 CurContext->addDecl(D);
6229
6230 if (!LookupContext) return D;
6231 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006232
John McCall77bb1aa2010-05-01 00:40:08 +00006233 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006234 UD->setInvalidDecl();
6235 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006236 }
6237
Sebastian Redlf677ea32011-02-05 19:23:19 +00006238 // Constructor inheriting using decls get special treatment.
6239 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006240 if (CheckInheritedConstructorUsingDecl(UD))
6241 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006242 return UD;
6243 }
6244
6245 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006246
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006247 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006248
John McCall604e7f12009-12-08 07:46:18 +00006249 // Unlike most lookups, we don't always want to hide tag
6250 // declarations: tag names are visible through the using declaration
6251 // even if hidden by ordinary names, *except* in a dependent context
6252 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006253 if (!IsInstantiation)
6254 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006255
John McCalla24dc2e2009-11-17 02:14:36 +00006256 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006257
John McCallf36e02d2009-10-09 21:13:30 +00006258 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006259 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006260 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006261 UD->setInvalidDecl();
6262 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006263 }
6264
John McCalled976492009-12-04 22:46:56 +00006265 if (R.isAmbiguous()) {
6266 UD->setInvalidDecl();
6267 return UD;
6268 }
Mike Stump1eb44332009-09-09 15:08:12 +00006269
John McCall7ba107a2009-11-18 02:36:19 +00006270 if (IsTypeName) {
6271 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006272 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006273 Diag(IdentLoc, diag::err_using_typename_non_type);
6274 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6275 Diag((*I)->getUnderlyingDecl()->getLocation(),
6276 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006277 UD->setInvalidDecl();
6278 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006279 }
6280 } else {
6281 // If we asked for a non-typename and we got a type, error out,
6282 // but only if this is an instantiation of an unresolved using
6283 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006284 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006285 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6286 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006287 UD->setInvalidDecl();
6288 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006289 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006290 }
6291
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006292 // C++0x N2914 [namespace.udecl]p6:
6293 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006294 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006295 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6296 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006297 UD->setInvalidDecl();
6298 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006299 }
Mike Stump1eb44332009-09-09 15:08:12 +00006300
John McCall9f54ad42009-12-10 09:41:52 +00006301 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6302 if (!CheckUsingShadowDecl(UD, *I, Previous))
6303 BuildUsingShadowDecl(S, UD, *I);
6304 }
John McCall9488ea12009-11-17 05:59:44 +00006305
6306 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006307}
6308
Sebastian Redlf677ea32011-02-05 19:23:19 +00006309/// Additional checks for a using declaration referring to a constructor name.
6310bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6311 if (UD->isTypeName()) {
6312 // FIXME: Cannot specify typename when specifying constructor
6313 return true;
6314 }
6315
Douglas Gregordc355712011-02-25 00:36:19 +00006316 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006317 assert(SourceType &&
6318 "Using decl naming constructor doesn't have type in scope spec.");
6319 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6320
6321 // Check whether the named type is a direct base class.
6322 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6323 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6324 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6325 BaseIt != BaseE; ++BaseIt) {
6326 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6327 if (CanonicalSourceType == BaseType)
6328 break;
6329 }
6330
6331 if (BaseIt == BaseE) {
6332 // Did not find SourceType in the bases.
6333 Diag(UD->getUsingLocation(),
6334 diag::err_using_decl_constructor_not_in_direct_base)
6335 << UD->getNameInfo().getSourceRange()
6336 << QualType(SourceType, 0) << TargetClass;
6337 return true;
6338 }
6339
6340 BaseIt->setInheritConstructors();
6341
6342 return false;
6343}
6344
John McCall9f54ad42009-12-10 09:41:52 +00006345/// Checks that the given using declaration is not an invalid
6346/// redeclaration. Note that this is checking only for the using decl
6347/// itself, not for any ill-formedness among the UsingShadowDecls.
6348bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6349 bool isTypeName,
6350 const CXXScopeSpec &SS,
6351 SourceLocation NameLoc,
6352 const LookupResult &Prev) {
6353 // C++03 [namespace.udecl]p8:
6354 // C++0x [namespace.udecl]p10:
6355 // A using-declaration is a declaration and can therefore be used
6356 // repeatedly where (and only where) multiple declarations are
6357 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006358 //
John McCall8a726212010-11-29 18:01:58 +00006359 // That's in non-member contexts.
6360 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006361 return false;
6362
6363 NestedNameSpecifier *Qual
6364 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6365
6366 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6367 NamedDecl *D = *I;
6368
6369 bool DTypename;
6370 NestedNameSpecifier *DQual;
6371 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6372 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006373 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006374 } else if (UnresolvedUsingValueDecl *UD
6375 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6376 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006377 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006378 } else if (UnresolvedUsingTypenameDecl *UD
6379 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6380 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006381 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006382 } else continue;
6383
6384 // using decls differ if one says 'typename' and the other doesn't.
6385 // FIXME: non-dependent using decls?
6386 if (isTypeName != DTypename) continue;
6387
6388 // using decls differ if they name different scopes (but note that
6389 // template instantiation can cause this check to trigger when it
6390 // didn't before instantiation).
6391 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6392 Context.getCanonicalNestedNameSpecifier(DQual))
6393 continue;
6394
6395 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006396 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006397 return true;
6398 }
6399
6400 return false;
6401}
6402
John McCall604e7f12009-12-08 07:46:18 +00006403
John McCalled976492009-12-04 22:46:56 +00006404/// Checks that the given nested-name qualifier used in a using decl
6405/// in the current context is appropriately related to the current
6406/// scope. If an error is found, diagnoses it and returns true.
6407bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6408 const CXXScopeSpec &SS,
6409 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006410 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006411
John McCall604e7f12009-12-08 07:46:18 +00006412 if (!CurContext->isRecord()) {
6413 // C++03 [namespace.udecl]p3:
6414 // C++0x [namespace.udecl]p8:
6415 // A using-declaration for a class member shall be a member-declaration.
6416
6417 // If we weren't able to compute a valid scope, it must be a
6418 // dependent class scope.
6419 if (!NamedContext || NamedContext->isRecord()) {
6420 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6421 << SS.getRange();
6422 return true;
6423 }
6424
6425 // Otherwise, everything is known to be fine.
6426 return false;
6427 }
6428
6429 // The current scope is a record.
6430
6431 // If the named context is dependent, we can't decide much.
6432 if (!NamedContext) {
6433 // FIXME: in C++0x, we can diagnose if we can prove that the
6434 // nested-name-specifier does not refer to a base class, which is
6435 // still possible in some cases.
6436
6437 // Otherwise we have to conservatively report that things might be
6438 // okay.
6439 return false;
6440 }
6441
6442 if (!NamedContext->isRecord()) {
6443 // Ideally this would point at the last name in the specifier,
6444 // but we don't have that level of source info.
6445 Diag(SS.getRange().getBegin(),
6446 diag::err_using_decl_nested_name_specifier_is_not_class)
6447 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6448 return true;
6449 }
6450
Douglas Gregor6fb07292010-12-21 07:41:49 +00006451 if (!NamedContext->isDependentContext() &&
6452 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6453 return true;
6454
David Blaikie4e4d0842012-03-11 07:00:24 +00006455 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006456 // C++0x [namespace.udecl]p3:
6457 // In a using-declaration used as a member-declaration, the
6458 // nested-name-specifier shall name a base class of the class
6459 // being defined.
6460
6461 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6462 cast<CXXRecordDecl>(NamedContext))) {
6463 if (CurContext == NamedContext) {
6464 Diag(NameLoc,
6465 diag::err_using_decl_nested_name_specifier_is_current_class)
6466 << SS.getRange();
6467 return true;
6468 }
6469
6470 Diag(SS.getRange().getBegin(),
6471 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6472 << (NestedNameSpecifier*) SS.getScopeRep()
6473 << cast<CXXRecordDecl>(CurContext)
6474 << SS.getRange();
6475 return true;
6476 }
6477
6478 return false;
6479 }
6480
6481 // C++03 [namespace.udecl]p4:
6482 // A using-declaration used as a member-declaration shall refer
6483 // to a member of a base class of the class being defined [etc.].
6484
6485 // Salient point: SS doesn't have to name a base class as long as
6486 // lookup only finds members from base classes. Therefore we can
6487 // diagnose here only if we can prove that that can't happen,
6488 // i.e. if the class hierarchies provably don't intersect.
6489
6490 // TODO: it would be nice if "definitely valid" results were cached
6491 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6492 // need to be repeated.
6493
6494 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006495 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006496
6497 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6498 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6499 Data->Bases.insert(Base);
6500 return true;
6501 }
6502
6503 bool hasDependentBases(const CXXRecordDecl *Class) {
6504 return !Class->forallBases(collect, this);
6505 }
6506
6507 /// Returns true if the base is dependent or is one of the
6508 /// accumulated base classes.
6509 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6510 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6511 return !Data->Bases.count(Base);
6512 }
6513
6514 bool mightShareBases(const CXXRecordDecl *Class) {
6515 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6516 }
6517 };
6518
6519 UserData Data;
6520
6521 // Returns false if we find a dependent base.
6522 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6523 return false;
6524
6525 // Returns false if the class has a dependent base or if it or one
6526 // of its bases is present in the base set of the current context.
6527 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6528 return false;
6529
6530 Diag(SS.getRange().getBegin(),
6531 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6532 << (NestedNameSpecifier*) SS.getScopeRep()
6533 << cast<CXXRecordDecl>(CurContext)
6534 << SS.getRange();
6535
6536 return true;
John McCalled976492009-12-04 22:46:56 +00006537}
6538
Richard Smith162e1c12011-04-15 14:24:37 +00006539Decl *Sema::ActOnAliasDeclaration(Scope *S,
6540 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006541 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006542 SourceLocation UsingLoc,
6543 UnqualifiedId &Name,
6544 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006545 // Skip up to the relevant declaration scope.
6546 while (S->getFlags() & Scope::TemplateParamScope)
6547 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006548 assert((S->getFlags() & Scope::DeclScope) &&
6549 "got alias-declaration outside of declaration scope");
6550
6551 if (Type.isInvalid())
6552 return 0;
6553
6554 bool Invalid = false;
6555 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6556 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006557 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006558
6559 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6560 return 0;
6561
6562 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006563 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006564 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006565 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6566 TInfo->getTypeLoc().getBeginLoc());
6567 }
Richard Smith162e1c12011-04-15 14:24:37 +00006568
6569 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6570 LookupName(Previous, S);
6571
6572 // Warn about shadowing the name of a template parameter.
6573 if (Previous.isSingleResult() &&
6574 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006575 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006576 Previous.clear();
6577 }
6578
6579 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6580 "name in alias declaration must be an identifier");
6581 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6582 Name.StartLocation,
6583 Name.Identifier, TInfo);
6584
6585 NewTD->setAccess(AS);
6586
6587 if (Invalid)
6588 NewTD->setInvalidDecl();
6589
Richard Smith3e4c6c42011-05-05 21:57:07 +00006590 CheckTypedefForVariablyModifiedType(S, NewTD);
6591 Invalid |= NewTD->isInvalidDecl();
6592
Richard Smith162e1c12011-04-15 14:24:37 +00006593 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006594
6595 NamedDecl *NewND;
6596 if (TemplateParamLists.size()) {
6597 TypeAliasTemplateDecl *OldDecl = 0;
6598 TemplateParameterList *OldTemplateParams = 0;
6599
6600 if (TemplateParamLists.size() != 1) {
6601 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6602 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6603 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6604 }
6605 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6606
6607 // Only consider previous declarations in the same scope.
6608 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6609 /*ExplicitInstantiationOrSpecialization*/false);
6610 if (!Previous.empty()) {
6611 Redeclaration = true;
6612
6613 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6614 if (!OldDecl && !Invalid) {
6615 Diag(UsingLoc, diag::err_redefinition_different_kind)
6616 << Name.Identifier;
6617
6618 NamedDecl *OldD = Previous.getRepresentativeDecl();
6619 if (OldD->getLocation().isValid())
6620 Diag(OldD->getLocation(), diag::note_previous_definition);
6621
6622 Invalid = true;
6623 }
6624
6625 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6626 if (TemplateParameterListsAreEqual(TemplateParams,
6627 OldDecl->getTemplateParameters(),
6628 /*Complain=*/true,
6629 TPL_TemplateMatch))
6630 OldTemplateParams = OldDecl->getTemplateParameters();
6631 else
6632 Invalid = true;
6633
6634 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6635 if (!Invalid &&
6636 !Context.hasSameType(OldTD->getUnderlyingType(),
6637 NewTD->getUnderlyingType())) {
6638 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6639 // but we can't reasonably accept it.
6640 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6641 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6642 if (OldTD->getLocation().isValid())
6643 Diag(OldTD->getLocation(), diag::note_previous_definition);
6644 Invalid = true;
6645 }
6646 }
6647 }
6648
6649 // Merge any previous default template arguments into our parameters,
6650 // and check the parameter list.
6651 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6652 TPC_TypeAliasTemplate))
6653 return 0;
6654
6655 TypeAliasTemplateDecl *NewDecl =
6656 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6657 Name.Identifier, TemplateParams,
6658 NewTD);
6659
6660 NewDecl->setAccess(AS);
6661
6662 if (Invalid)
6663 NewDecl->setInvalidDecl();
6664 else if (OldDecl)
6665 NewDecl->setPreviousDeclaration(OldDecl);
6666
6667 NewND = NewDecl;
6668 } else {
6669 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6670 NewND = NewTD;
6671 }
Richard Smith162e1c12011-04-15 14:24:37 +00006672
6673 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006674 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006675
Richard Smith3e4c6c42011-05-05 21:57:07 +00006676 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006677}
6678
John McCalld226f652010-08-21 09:40:31 +00006679Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006680 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006681 SourceLocation AliasLoc,
6682 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006683 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006684 SourceLocation IdentLoc,
6685 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006686
Anders Carlsson81c85c42009-03-28 23:53:49 +00006687 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006688 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6689 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006690
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006691 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006692 NamedDecl *PrevDecl
6693 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6694 ForRedeclaration);
6695 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6696 PrevDecl = 0;
6697
6698 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006699 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006700 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006701 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006702 // FIXME: At some point, we'll want to create the (redundant)
6703 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006704 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006705 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006706 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006707 }
Mike Stump1eb44332009-09-09 15:08:12 +00006708
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006709 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6710 diag::err_redefinition_different_kind;
6711 Diag(AliasLoc, DiagID) << Alias;
6712 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006713 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006714 }
6715
John McCalla24dc2e2009-11-17 02:14:36 +00006716 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006717 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006718
John McCallf36e02d2009-10-09 21:13:30 +00006719 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006720 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006721 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006722 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006723 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006724 }
Mike Stump1eb44332009-09-09 15:08:12 +00006725
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006726 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006727 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006728 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006729 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006730
John McCall3dbd3d52010-02-16 06:53:13 +00006731 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006732 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006733}
6734
Douglas Gregor39957dc2010-05-01 15:04:51 +00006735namespace {
6736 /// \brief Scoped object used to handle the state changes required in Sema
6737 /// to implicitly define the body of a C++ member function;
6738 class ImplicitlyDefinedFunctionScope {
6739 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006740 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006741
6742 public:
6743 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006744 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006745 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006746 S.PushFunctionScope();
6747 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6748 }
6749
6750 ~ImplicitlyDefinedFunctionScope() {
6751 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006752 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006753 }
6754 };
6755}
6756
Sean Hunt001cad92011-05-10 00:49:42 +00006757Sema::ImplicitExceptionSpecification
6758Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006759 // C++ [except.spec]p14:
6760 // An implicitly declared special member function (Clause 12) shall have an
6761 // exception-specification. [...]
6762 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006763 if (ClassDecl->isInvalidDecl())
6764 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006765
Sebastian Redl60618fa2011-03-12 11:50:43 +00006766 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006767 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6768 BEnd = ClassDecl->bases_end();
6769 B != BEnd; ++B) {
6770 if (B->isVirtual()) // Handled below.
6771 continue;
6772
Douglas Gregor18274032010-07-03 00:47:00 +00006773 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6774 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006775 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6776 // If this is a deleted function, add it anyway. This might be conformant
6777 // with the standard. This might not. I'm not sure. It might not matter.
6778 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006779 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006780 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006781 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006782
6783 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006784 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6785 BEnd = ClassDecl->vbases_end();
6786 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006787 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6788 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006789 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6790 // If this is a deleted function, add it anyway. This might be conformant
6791 // with the standard. This might not. I'm not sure. It might not matter.
6792 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006793 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006794 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006795 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006796
6797 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006798 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6799 FEnd = ClassDecl->field_end();
6800 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006801 if (F->hasInClassInitializer()) {
6802 if (Expr *E = F->getInClassInitializer())
6803 ExceptSpec.CalledExpr(E);
6804 else if (!F->isInvalidDecl())
6805 ExceptSpec.SetDelayed();
6806 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006807 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006808 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6809 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6810 // If this is a deleted function, add it anyway. This might be conformant
6811 // with the standard. This might not. I'm not sure. It might not matter.
6812 // In particular, the problem is that this function never gets called. It
6813 // might just be ill-formed because this function attempts to refer to
6814 // a deleted function here.
6815 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006816 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006817 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006818 }
John McCalle23cf432010-12-14 08:05:40 +00006819
Sean Hunt001cad92011-05-10 00:49:42 +00006820 return ExceptSpec;
6821}
6822
6823CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6824 CXXRecordDecl *ClassDecl) {
6825 // C++ [class.ctor]p5:
6826 // A default constructor for a class X is a constructor of class X
6827 // that can be called without an argument. If there is no
6828 // user-declared constructor for class X, a default constructor is
6829 // implicitly declared. An implicitly-declared default constructor
6830 // is an inline public member of its class.
6831 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6832 "Should not build implicit default constructor!");
6833
6834 ImplicitExceptionSpecification Spec =
6835 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6836 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006837
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006838 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006839 CanQualType ClassType
6840 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006841 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006842 DeclarationName Name
6843 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006844 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006845 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6846 Context, ClassDecl, ClassLoc, NameInfo,
6847 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6848 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6849 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006850 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006851 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006852 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006853 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006854 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006855
6856 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006857 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6858
Douglas Gregor23c94db2010-07-02 17:43:08 +00006859 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006860 PushOnScopeChains(DefaultCon, S, false);
6861 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006862
Sean Hunte16da072011-10-10 06:18:57 +00006863 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006864 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006865
Douglas Gregor32df23e2010-07-01 22:02:46 +00006866 return DefaultCon;
6867}
6868
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006869void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6870 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006871 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006872 !Constructor->doesThisDeclarationHaveABody() &&
6873 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006874 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006875
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006876 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006877 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006878
Douglas Gregor39957dc2010-05-01 15:04:51 +00006879 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006880 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006881 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006882 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006883 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006884 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006885 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006886 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006887 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006888
6889 SourceLocation Loc = Constructor->getLocation();
6890 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6891
6892 Constructor->setUsed();
6893 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006894
6895 if (ASTMutationListener *L = getASTMutationListener()) {
6896 L->CompletedImplicitDefinition(Constructor);
6897 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006898}
6899
Richard Smith7a614d82011-06-11 17:19:42 +00006900/// Get any existing defaulted default constructor for the given class. Do not
6901/// implicitly define one if it does not exist.
6902static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6903 CXXRecordDecl *D) {
6904 ASTContext &Context = Self.Context;
6905 QualType ClassType = Context.getTypeDeclType(D);
6906 DeclarationName ConstructorName
6907 = Context.DeclarationNames.getCXXConstructorName(
6908 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6909
6910 DeclContext::lookup_const_iterator Con, ConEnd;
6911 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6912 Con != ConEnd; ++Con) {
6913 // A function template cannot be defaulted.
6914 if (isa<FunctionTemplateDecl>(*Con))
6915 continue;
6916
6917 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6918 if (Constructor->isDefaultConstructor())
6919 return Constructor->isDefaulted() ? Constructor : 0;
6920 }
6921 return 0;
6922}
6923
6924void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6925 if (!D) return;
6926 AdjustDeclIfTemplate(D);
6927
6928 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6929 CXXConstructorDecl *CtorDecl
6930 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6931
6932 if (!CtorDecl) return;
6933
6934 // Compute the exception specification for the default constructor.
6935 const FunctionProtoType *CtorTy =
6936 CtorDecl->getType()->castAs<FunctionProtoType>();
6937 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6938 ImplicitExceptionSpecification Spec =
6939 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6940 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6941 assert(EPI.ExceptionSpecType != EST_Delayed);
6942
6943 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6944 }
6945
6946 // If the default constructor is explicitly defaulted, checking the exception
6947 // specification is deferred until now.
6948 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6949 !ClassDecl->isDependentType())
6950 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6951}
6952
Sebastian Redlf677ea32011-02-05 19:23:19 +00006953void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6954 // We start with an initial pass over the base classes to collect those that
6955 // inherit constructors from. If there are none, we can forgo all further
6956 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006957 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006958 BasesVector BasesToInheritFrom;
6959 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6960 BaseE = ClassDecl->bases_end();
6961 BaseIt != BaseE; ++BaseIt) {
6962 if (BaseIt->getInheritConstructors()) {
6963 QualType Base = BaseIt->getType();
6964 if (Base->isDependentType()) {
6965 // If we inherit constructors from anything that is dependent, just
6966 // abort processing altogether. We'll get another chance for the
6967 // instantiations.
6968 return;
6969 }
6970 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6971 }
6972 }
6973 if (BasesToInheritFrom.empty())
6974 return;
6975
6976 // Now collect the constructors that we already have in the current class.
6977 // Those take precedence over inherited constructors.
6978 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6979 // unless there is a user-declared constructor with the same signature in
6980 // the class where the using-declaration appears.
6981 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6982 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6983 CtorE = ClassDecl->ctor_end();
6984 CtorIt != CtorE; ++CtorIt) {
6985 ExistingConstructors.insert(
6986 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6987 }
6988
6989 Scope *S = getScopeForContext(ClassDecl);
6990 DeclarationName CreatedCtorName =
6991 Context.DeclarationNames.getCXXConstructorName(
6992 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6993
6994 // Now comes the true work.
6995 // First, we keep a map from constructor types to the base that introduced
6996 // them. Needed for finding conflicting constructors. We also keep the
6997 // actually inserted declarations in there, for pretty diagnostics.
6998 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6999 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7000 ConstructorToSourceMap InheritedConstructors;
7001 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7002 BaseE = BasesToInheritFrom.end();
7003 BaseIt != BaseE; ++BaseIt) {
7004 const RecordType *Base = *BaseIt;
7005 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7006 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7007 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7008 CtorE = BaseDecl->ctor_end();
7009 CtorIt != CtorE; ++CtorIt) {
7010 // Find the using declaration for inheriting this base's constructors.
7011 DeclarationName Name =
7012 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7013 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7014 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7015 SourceLocation UsingLoc = UD ? UD->getLocation() :
7016 ClassDecl->getLocation();
7017
7018 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7019 // from the class X named in the using-declaration consists of actual
7020 // constructors and notional constructors that result from the
7021 // transformation of defaulted parameters as follows:
7022 // - all non-template default constructors of X, and
7023 // - for each non-template constructor of X that has at least one
7024 // parameter with a default argument, the set of constructors that
7025 // results from omitting any ellipsis parameter specification and
7026 // successively omitting parameters with a default argument from the
7027 // end of the parameter-type-list.
7028 CXXConstructorDecl *BaseCtor = *CtorIt;
7029 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7030 const FunctionProtoType *BaseCtorType =
7031 BaseCtor->getType()->getAs<FunctionProtoType>();
7032
7033 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7034 maxParams = BaseCtor->getNumParams();
7035 params <= maxParams; ++params) {
7036 // Skip default constructors. They're never inherited.
7037 if (params == 0)
7038 continue;
7039 // Skip copy and move constructors for the same reason.
7040 if (CanBeCopyOrMove && params == 1)
7041 continue;
7042
7043 // Build up a function type for this particular constructor.
7044 // FIXME: The working paper does not consider that the exception spec
7045 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007046 // source. This code doesn't yet, either. When it does, this code will
7047 // need to be delayed until after exception specifications and in-class
7048 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007049 const Type *NewCtorType;
7050 if (params == maxParams)
7051 NewCtorType = BaseCtorType;
7052 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007053 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007054 for (unsigned i = 0; i < params; ++i) {
7055 Args.push_back(BaseCtorType->getArgType(i));
7056 }
7057 FunctionProtoType::ExtProtoInfo ExtInfo =
7058 BaseCtorType->getExtProtoInfo();
7059 ExtInfo.Variadic = false;
7060 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7061 Args.data(), params, ExtInfo)
7062 .getTypePtr();
7063 }
7064 const Type *CanonicalNewCtorType =
7065 Context.getCanonicalType(NewCtorType);
7066
7067 // Now that we have the type, first check if the class already has a
7068 // constructor with this signature.
7069 if (ExistingConstructors.count(CanonicalNewCtorType))
7070 continue;
7071
7072 // Then we check if we have already declared an inherited constructor
7073 // with this signature.
7074 std::pair<ConstructorToSourceMap::iterator, bool> result =
7075 InheritedConstructors.insert(std::make_pair(
7076 CanonicalNewCtorType,
7077 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7078 if (!result.second) {
7079 // Already in the map. If it came from a different class, that's an
7080 // error. Not if it's from the same.
7081 CanQualType PreviousBase = result.first->second.first;
7082 if (CanonicalBase != PreviousBase) {
7083 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7084 const CXXConstructorDecl *PrevBaseCtor =
7085 PrevCtor->getInheritedConstructor();
7086 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7087
7088 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7089 Diag(BaseCtor->getLocation(),
7090 diag::note_using_decl_constructor_conflict_current_ctor);
7091 Diag(PrevBaseCtor->getLocation(),
7092 diag::note_using_decl_constructor_conflict_previous_ctor);
7093 Diag(PrevCtor->getLocation(),
7094 diag::note_using_decl_constructor_conflict_previous_using);
7095 }
7096 continue;
7097 }
7098
7099 // OK, we're there, now add the constructor.
7100 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007101 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007102 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7103 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007104 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7105 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007106 /*ImplicitlyDeclared=*/true,
7107 // FIXME: Due to a defect in the standard, we treat inherited
7108 // constructors as constexpr even if that makes them ill-formed.
7109 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007110 NewCtor->setAccess(BaseCtor->getAccess());
7111
7112 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007113 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007114 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007115 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7116 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007117 /*IdentifierInfo=*/0,
7118 BaseCtorType->getArgType(i),
7119 /*TInfo=*/0, SC_None,
7120 SC_None, /*DefaultArg=*/0));
7121 }
David Blaikie4278c652011-09-21 18:16:56 +00007122 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007123 NewCtor->setInheritedConstructor(BaseCtor);
7124
7125 PushOnScopeChains(NewCtor, S, false);
7126 ClassDecl->addDecl(NewCtor);
7127 result.first->second.second = NewCtor;
7128 }
7129 }
7130 }
7131}
7132
Sean Huntcb45a0f2011-05-12 22:46:25 +00007133Sema::ImplicitExceptionSpecification
7134Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007135 // C++ [except.spec]p14:
7136 // An implicitly declared special member function (Clause 12) shall have
7137 // an exception-specification.
7138 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007139 if (ClassDecl->isInvalidDecl())
7140 return ExceptSpec;
7141
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007142 // Direct base-class destructors.
7143 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7144 BEnd = ClassDecl->bases_end();
7145 B != BEnd; ++B) {
7146 if (B->isVirtual()) // Handled below.
7147 continue;
7148
7149 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7150 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007151 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007152 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007153
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007154 // Virtual base-class destructors.
7155 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7156 BEnd = ClassDecl->vbases_end();
7157 B != BEnd; ++B) {
7158 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7159 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007160 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007161 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007162
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007163 // Field destructors.
7164 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7165 FEnd = ClassDecl->field_end();
7166 F != FEnd; ++F) {
7167 if (const RecordType *RecordTy
7168 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7169 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007170 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007171 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007172
Sean Huntcb45a0f2011-05-12 22:46:25 +00007173 return ExceptSpec;
7174}
7175
7176CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7177 // C++ [class.dtor]p2:
7178 // If a class has no user-declared destructor, a destructor is
7179 // declared implicitly. An implicitly-declared destructor is an
7180 // inline public member of its class.
7181
7182 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007183 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007184 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7185
Douglas Gregor4923aa22010-07-02 20:37:36 +00007186 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007187 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007188
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007189 CanQualType ClassType
7190 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007191 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007192 DeclarationName Name
7193 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007194 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007195 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007196 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7197 /*isInline=*/true,
7198 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007199 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007200 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007201 Destructor->setImplicit();
7202 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007203
7204 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007205 ++ASTContext::NumImplicitDestructorsDeclared;
7206
7207 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007208 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007209 PushOnScopeChains(Destructor, S, false);
7210 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007211
7212 // This could be uniqued if it ever proves significant.
7213 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007214
Richard Smith9a561d52012-02-26 09:11:52 +00007215 AddOverriddenMethods(ClassDecl, Destructor);
7216
Richard Smith7d5088a2012-02-18 02:02:13 +00007217 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007218 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007219
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007220 return Destructor;
7221}
7222
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007223void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007224 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007225 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007226 !Destructor->doesThisDeclarationHaveABody() &&
7227 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007228 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007229 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007230 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007231
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007232 if (Destructor->isInvalidDecl())
7233 return;
7234
Douglas Gregor39957dc2010-05-01 15:04:51 +00007235 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007236
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007237 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007238 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7239 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007240
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007241 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007242 Diag(CurrentLocation, diag::note_member_synthesized_at)
7243 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7244
7245 Destructor->setInvalidDecl();
7246 return;
7247 }
7248
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007249 SourceLocation Loc = Destructor->getLocation();
7250 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007251 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007252 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007253 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007254
7255 if (ASTMutationListener *L = getASTMutationListener()) {
7256 L->CompletedImplicitDefinition(Destructor);
7257 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007258}
7259
Sebastian Redl0ee33912011-05-19 05:13:44 +00007260void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7261 CXXDestructorDecl *destructor) {
7262 // C++11 [class.dtor]p3:
7263 // A declaration of a destructor that does not have an exception-
7264 // specification is implicitly considered to have the same exception-
7265 // specification as an implicit declaration.
7266 const FunctionProtoType *dtorType = destructor->getType()->
7267 getAs<FunctionProtoType>();
7268 if (dtorType->hasExceptionSpec())
7269 return;
7270
7271 ImplicitExceptionSpecification exceptSpec =
7272 ComputeDefaultedDtorExceptionSpec(classDecl);
7273
Chandler Carruth3f224b22011-09-20 04:55:26 +00007274 // Replace the destructor's type, building off the existing one. Fortunately,
7275 // the only thing of interest in the destructor type is its extended info.
7276 // The return and arguments are fixed.
7277 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007278 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7279 epi.NumExceptions = exceptSpec.size();
7280 epi.Exceptions = exceptSpec.data();
7281 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7282
7283 destructor->setType(ty);
7284
7285 // FIXME: If the destructor has a body that could throw, and the newly created
7286 // spec doesn't allow exceptions, we should emit a warning, because this
7287 // change in behavior can break conforming C++03 programs at runtime.
7288 // However, we don't have a body yet, so it needs to be done somewhere else.
7289}
7290
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007291/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007292/// \c To.
7293///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007294/// This routine is used to copy/move the members of a class with an
7295/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007296/// copied are arrays, this routine builds for loops to copy them.
7297///
7298/// \param S The Sema object used for type-checking.
7299///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007300/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007301///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007302/// \param T The type of the expressions being copied/moved. Both expressions
7303/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007304///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007305/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007306///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007307/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007308///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007309/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007310/// Otherwise, it's a non-static member subobject.
7311///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007312/// \param Copying Whether we're copying or moving.
7313///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007314/// \param Depth Internal parameter recording the depth of the recursion.
7315///
7316/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007317static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007318BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007319 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007320 bool CopyingBaseSubobject, bool Copying,
7321 unsigned Depth = 0) {
7322 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007323 // Each subobject is assigned in the manner appropriate to its type:
7324 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007325 // - if the subobject is of class type, as if by a call to operator= with
7326 // the subobject as the object expression and the corresponding
7327 // subobject of x as a single function argument (as if by explicit
7328 // qualification; that is, ignoring any possible virtual overriding
7329 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007330 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7331 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7332
7333 // Look for operator=.
7334 DeclarationName Name
7335 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7336 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7337 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7338
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007339 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007340 LookupResult::Filter F = OpLookup.makeFilter();
7341 while (F.hasNext()) {
7342 NamedDecl *D = F.next();
7343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007344 if (Copying ? Method->isCopyAssignmentOperator() :
7345 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007346 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007347
Douglas Gregor06a9f362010-05-01 20:49:11 +00007348 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007349 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007350 F.done();
7351
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007352 // Suppress the protected check (C++ [class.protected]) for each of the
7353 // assignment operators we found. This strange dance is required when
7354 // we're assigning via a base classes's copy-assignment operator. To
7355 // ensure that we're getting the right base class subobject (without
7356 // ambiguities), we need to cast "this" to that subobject type; to
7357 // ensure that we don't go through the virtual call mechanism, we need
7358 // to qualify the operator= name with the base class (see below). However,
7359 // this means that if the base class has a protected copy assignment
7360 // operator, the protected member access check will fail. So, we
7361 // rewrite "protected" access to "public" access in this case, since we
7362 // know by construction that we're calling from a derived class.
7363 if (CopyingBaseSubobject) {
7364 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7365 L != LEnd; ++L) {
7366 if (L.getAccess() == AS_protected)
7367 L.setAccess(AS_public);
7368 }
7369 }
7370
Douglas Gregor06a9f362010-05-01 20:49:11 +00007371 // Create the nested-name-specifier that will be used to qualify the
7372 // reference to operator=; this is required to suppress the virtual
7373 // call mechanism.
7374 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007375 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007376 SS.MakeTrivial(S.Context,
7377 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007378 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007379 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007380
7381 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007382 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007383 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007384 /*TemplateKWLoc=*/SourceLocation(),
7385 /*FirstQualifierInScope=*/0,
7386 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007387 /*TemplateArgs=*/0,
7388 /*SuppressQualifierCheck=*/true);
7389 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007390 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007391
7392 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007393
John McCall60d7b3a2010-08-24 06:29:42 +00007394 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007395 OpEqualRef.takeAs<Expr>(),
7396 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007397 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007398 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007399
7400 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007401 }
John McCallb0207482010-03-16 06:11:48 +00007402
Douglas Gregor06a9f362010-05-01 20:49:11 +00007403 // - if the subobject is of scalar type, the built-in assignment
7404 // operator is used.
7405 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7406 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007407 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007409 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007410
7411 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007412 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007413
7414 // - if the subobject is an array, each element is assigned, in the
7415 // manner appropriate to the element type;
7416
7417 // Construct a loop over the array bounds, e.g.,
7418 //
7419 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7420 //
7421 // that will copy each of the array elements.
7422 QualType SizeType = S.Context.getSizeType();
7423
7424 // Create the iteration variable.
7425 IdentifierInfo *IterationVarName = 0;
7426 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007427 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007428 llvm::raw_svector_ostream OS(Str);
7429 OS << "__i" << Depth;
7430 IterationVarName = &S.Context.Idents.get(OS.str());
7431 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007432 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007433 IterationVarName, SizeType,
7434 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007435 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007436
7437 // Initialize the iteration variable to zero.
7438 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007439 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440
7441 // Create a reference to the iteration variable; we'll use this several
7442 // times throughout.
7443 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007444 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007445 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007446 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7447 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7448
Douglas Gregor06a9f362010-05-01 20:49:11 +00007449 // Create the DeclStmt that holds the iteration variable.
7450 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7451
7452 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007453 llvm::APInt Upper
7454 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007455 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007456 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007457 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7458 BO_NE, S.Context.BoolTy,
7459 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007460
7461 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007462 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007463 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7464 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007465
7466 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007467 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007468 IterationVarRefRVal,
7469 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007470 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007471 IterationVarRefRVal,
7472 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007473 if (!Copying) // Cast to rvalue
7474 From = CastForMoving(S, From);
7475
7476 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007477 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7478 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007479 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007480 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007481 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007482
7483 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007484 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007485 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007486 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007487 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007488}
7489
Sean Hunt30de05c2011-05-14 05:23:20 +00007490std::pair<Sema::ImplicitExceptionSpecification, bool>
7491Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7492 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007493 if (ClassDecl->isInvalidDecl())
7494 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7495
Douglas Gregord3c35902010-07-01 16:36:15 +00007496 // C++ [class.copy]p10:
7497 // If the class definition does not explicitly declare a copy
7498 // assignment operator, one is declared implicitly.
7499 // The implicitly-defined copy assignment operator for a class X
7500 // will have the form
7501 //
7502 // X& X::operator=(const X&)
7503 //
7504 // if
7505 bool HasConstCopyAssignment = true;
7506
7507 // -- each direct base class B of X has a copy assignment operator
7508 // whose parameter is of type const B&, const volatile B& or B,
7509 // and
7510 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7511 BaseEnd = ClassDecl->bases_end();
7512 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007513 // We'll handle this below
7514 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7515 continue;
7516
Douglas Gregord3c35902010-07-01 16:36:15 +00007517 assert(!Base->getType()->isDependentType() &&
7518 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007519 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7520 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7521 &HasConstCopyAssignment);
7522 }
7523
Richard Smithebaf0e62011-10-18 20:49:44 +00007524 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007525 if (LangOpts.CPlusPlus0x) {
7526 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7527 BaseEnd = ClassDecl->vbases_end();
7528 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7529 assert(!Base->getType()->isDependentType() &&
7530 "Cannot generate implicit members for class with dependent bases.");
7531 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7532 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7533 &HasConstCopyAssignment);
7534 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007535 }
7536
7537 // -- for all the nonstatic data members of X that are of a class
7538 // type M (or array thereof), each such class type has a copy
7539 // assignment operator whose parameter is of type const M&,
7540 // const volatile M& or M.
7541 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7542 FieldEnd = ClassDecl->field_end();
7543 HasConstCopyAssignment && Field != FieldEnd;
7544 ++Field) {
7545 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007546 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7547 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7548 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007549 }
7550 }
7551
7552 // Otherwise, the implicitly declared copy assignment operator will
7553 // have the form
7554 //
7555 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007556
Douglas Gregorb87786f2010-07-01 17:48:08 +00007557 // C++ [except.spec]p14:
7558 // An implicitly declared special member function (Clause 12) shall have an
7559 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007560
7561 // It is unspecified whether or not an implicit copy assignment operator
7562 // attempts to deduplicate calls to assignment operators of virtual bases are
7563 // made. As such, this exception specification is effectively unspecified.
7564 // Based on a similar decision made for constness in C++0x, we're erring on
7565 // the side of assuming such calls to be made regardless of whether they
7566 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007567 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007568 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7570 BaseEnd = ClassDecl->bases_end();
7571 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007572 if (Base->isVirtual())
7573 continue;
7574
Douglas Gregora376d102010-07-02 21:50:04 +00007575 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007577 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7578 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007579 ExceptSpec.CalledDecl(CopyAssign);
7580 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007581
7582 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7583 BaseEnd = ClassDecl->vbases_end();
7584 Base != BaseEnd; ++Base) {
7585 CXXRecordDecl *BaseClassDecl
7586 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7587 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7588 ArgQuals, false, 0))
7589 ExceptSpec.CalledDecl(CopyAssign);
7590 }
7591
Douglas Gregorb87786f2010-07-01 17:48:08 +00007592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7593 FieldEnd = ClassDecl->field_end();
7594 Field != FieldEnd;
7595 ++Field) {
7596 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007597 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7598 if (CXXMethodDecl *CopyAssign =
7599 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7600 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007601 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007602 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007603
Sean Hunt30de05c2011-05-14 05:23:20 +00007604 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7605}
7606
7607CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7608 // Note: The following rules are largely analoguous to the copy
7609 // constructor rules. Note that virtual bases are not taken into account
7610 // for determining the argument type of the operator. Note also that
7611 // operators taking an object instead of a reference are allowed.
7612
7613 ImplicitExceptionSpecification Spec(Context);
7614 bool Const;
7615 llvm::tie(Spec, Const) =
7616 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7617
7618 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7619 QualType RetType = Context.getLValueReferenceType(ArgType);
7620 if (Const)
7621 ArgType = ArgType.withConst();
7622 ArgType = Context.getLValueReferenceType(ArgType);
7623
Douglas Gregord3c35902010-07-01 16:36:15 +00007624 // An implicitly-declared copy assignment operator is an inline public
7625 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007626 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007627 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007628 SourceLocation ClassLoc = ClassDecl->getLocation();
7629 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007630 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007631 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007632 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007633 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007634 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007635 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007636 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007637 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007638 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007639 CopyAssignment->setImplicit();
7640 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007641
7642 // Add the parameter to the operator.
7643 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007644 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007645 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007646 SC_None,
7647 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007648 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007649
Douglas Gregora376d102010-07-02 21:50:04 +00007650 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007651 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007652
Douglas Gregor23c94db2010-07-02 17:43:08 +00007653 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007654 PushOnScopeChains(CopyAssignment, S, false);
7655 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007656
Nico Weberafcc96a2012-01-23 03:19:29 +00007657 // C++0x [class.copy]p19:
7658 // .... If the class definition does not explicitly declare a copy
7659 // assignment operator, there is no user-declared move constructor, and
7660 // there is no user-declared move assignment operator, a copy assignment
7661 // operator is implicitly declared as defaulted.
7662 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007663 !getLangOpts().MicrosoftMode) ||
Nico Weber28976602012-01-23 04:01:33 +00007664 ClassDecl->hasUserDeclaredMoveAssignment() ||
Richard Smith7d5088a2012-02-18 02:02:13 +00007665 ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007666 CopyAssignment->setDeletedAsWritten();
7667
Douglas Gregord3c35902010-07-01 16:36:15 +00007668 AddOverriddenMethods(ClassDecl, CopyAssignment);
7669 return CopyAssignment;
7670}
7671
Douglas Gregor06a9f362010-05-01 20:49:11 +00007672void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7673 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007674 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007675 CopyAssignOperator->isOverloadedOperator() &&
7676 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007677 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7678 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679 "DefineImplicitCopyAssignment called for wrong function");
7680
7681 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7682
7683 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7684 CopyAssignOperator->setInvalidDecl();
7685 return;
7686 }
7687
7688 CopyAssignOperator->setUsed();
7689
7690 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007691 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007692
7693 // C++0x [class.copy]p30:
7694 // The implicitly-defined or explicitly-defaulted copy assignment operator
7695 // for a non-union class X performs memberwise copy assignment of its
7696 // subobjects. The direct base classes of X are assigned first, in the
7697 // order of their declaration in the base-specifier-list, and then the
7698 // immediate non-static data members of X are assigned, in the order in
7699 // which they were declared in the class definition.
7700
7701 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007702 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007703
7704 // The parameter for the "other" object, which we are copying from.
7705 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7706 Qualifiers OtherQuals = Other->getType().getQualifiers();
7707 QualType OtherRefType = Other->getType();
7708 if (const LValueReferenceType *OtherRef
7709 = OtherRefType->getAs<LValueReferenceType>()) {
7710 OtherRefType = OtherRef->getPointeeType();
7711 OtherQuals = OtherRefType.getQualifiers();
7712 }
7713
7714 // Our location for everything implicitly-generated.
7715 SourceLocation Loc = CopyAssignOperator->getLocation();
7716
7717 // Construct a reference to the "other" object. We'll be using this
7718 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007719 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007720 assert(OtherRef && "Reference to parameter cannot fail!");
7721
7722 // Construct the "this" pointer. We'll be using this throughout the generated
7723 // ASTs.
7724 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7725 assert(This && "Reference to this cannot fail!");
7726
7727 // Assign base classes.
7728 bool Invalid = false;
7729 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7730 E = ClassDecl->bases_end(); Base != E; ++Base) {
7731 // Form the assignment:
7732 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7733 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007734 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007735 Invalid = true;
7736 continue;
7737 }
7738
John McCallf871d0c2010-08-07 06:22:56 +00007739 CXXCastPath BasePath;
7740 BasePath.push_back(Base);
7741
Douglas Gregor06a9f362010-05-01 20:49:11 +00007742 // Construct the "from" expression, which is an implicit cast to the
7743 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007744 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007745 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7746 CK_UncheckedDerivedToBase,
7747 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007748
7749 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007750 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007751
7752 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007753 To = ImpCastExprToType(To.take(),
7754 Context.getCVRQualifiedType(BaseType,
7755 CopyAssignOperator->getTypeQualifiers()),
7756 CK_UncheckedDerivedToBase,
7757 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007758
7759 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007760 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007761 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007762 /*CopyingBaseSubobject=*/true,
7763 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007764 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007765 Diag(CurrentLocation, diag::note_member_synthesized_at)
7766 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7767 CopyAssignOperator->setInvalidDecl();
7768 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007769 }
7770
7771 // Success! Record the copy.
7772 Statements.push_back(Copy.takeAs<Expr>());
7773 }
7774
7775 // \brief Reference to the __builtin_memcpy function.
7776 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007777 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007778 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007779
7780 // Assign non-static members.
7781 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7782 FieldEnd = ClassDecl->field_end();
7783 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007784 if (Field->isUnnamedBitfield())
7785 continue;
7786
Douglas Gregor06a9f362010-05-01 20:49:11 +00007787 // Check for members of reference type; we can't copy those.
7788 if (Field->getType()->isReferenceType()) {
7789 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7790 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7791 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007792 Diag(CurrentLocation, diag::note_member_synthesized_at)
7793 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007794 Invalid = true;
7795 continue;
7796 }
7797
7798 // Check for members of const-qualified, non-class type.
7799 QualType BaseType = Context.getBaseElementType(Field->getType());
7800 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7801 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7802 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7803 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007804 Diag(CurrentLocation, diag::note_member_synthesized_at)
7805 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007806 Invalid = true;
7807 continue;
7808 }
John McCallb77115d2011-06-17 00:18:42 +00007809
7810 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007811 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7812 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007813
7814 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007815 if (FieldType->isIncompleteArrayType()) {
7816 assert(ClassDecl->hasFlexibleArrayMember() &&
7817 "Incomplete array type is not valid");
7818 continue;
7819 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007820
7821 // Build references to the field in the object we're copying from and to.
7822 CXXScopeSpec SS; // Intentionally empty
7823 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7824 LookupMemberName);
7825 MemberLookup.addDecl(*Field);
7826 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007827 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007828 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007829 SS, SourceLocation(), 0,
7830 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007831 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007832 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007833 SS, SourceLocation(), 0,
7834 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007835 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7836 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7837
7838 // If the field should be copied with __builtin_memcpy rather than via
7839 // explicit assignments, do so. This optimization only applies for arrays
7840 // of scalars and arrays of class type with trivial copy-assignment
7841 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007842 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007843 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007844 // Compute the size of the memory buffer to be copied.
7845 QualType SizeType = Context.getSizeType();
7846 llvm::APInt Size(Context.getTypeSize(SizeType),
7847 Context.getTypeSizeInChars(BaseType).getQuantity());
7848 for (const ConstantArrayType *Array
7849 = Context.getAsConstantArrayType(FieldType);
7850 Array;
7851 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007852 llvm::APInt ArraySize
7853 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007854 Size *= ArraySize;
7855 }
7856
7857 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007858 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7859 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007860
7861 bool NeedsCollectableMemCpy =
7862 (BaseType->isRecordType() &&
7863 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7864
7865 if (NeedsCollectableMemCpy) {
7866 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007867 // Create a reference to the __builtin_objc_memmove_collectable function.
7868 LookupResult R(*this,
7869 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007870 Loc, LookupOrdinaryName);
7871 LookupName(R, TUScope, true);
7872
7873 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7874 if (!CollectableMemCpy) {
7875 // Something went horribly wrong earlier, and we will have
7876 // complained about it.
7877 Invalid = true;
7878 continue;
7879 }
7880
7881 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7882 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007883 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007884 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7885 }
7886 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007887 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007888 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007889 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7890 LookupOrdinaryName);
7891 LookupName(R, TUScope, true);
7892
7893 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7894 if (!BuiltinMemCpy) {
7895 // Something went horribly wrong earlier, and we will have complained
7896 // about it.
7897 Invalid = true;
7898 continue;
7899 }
7900
7901 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7902 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007903 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007904 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7905 }
7906
John McCallca0408f2010-08-23 06:44:23 +00007907 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007908 CallArgs.push_back(To.takeAs<Expr>());
7909 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007910 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007911 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007912 if (NeedsCollectableMemCpy)
7913 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007914 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007915 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007916 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007917 else
7918 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007919 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007920 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007921 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007922
Douglas Gregor06a9f362010-05-01 20:49:11 +00007923 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7924 Statements.push_back(Call.takeAs<Expr>());
7925 continue;
7926 }
7927
7928 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007929 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007930 To.get(), From.get(),
7931 /*CopyingBaseSubobject=*/false,
7932 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007933 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007934 Diag(CurrentLocation, diag::note_member_synthesized_at)
7935 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7936 CopyAssignOperator->setInvalidDecl();
7937 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007938 }
7939
7940 // Success! Record the copy.
7941 Statements.push_back(Copy.takeAs<Stmt>());
7942 }
7943
7944 if (!Invalid) {
7945 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007946 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007947
John McCall60d7b3a2010-08-24 06:29:42 +00007948 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007949 if (Return.isInvalid())
7950 Invalid = true;
7951 else {
7952 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007953
7954 if (Trap.hasErrorOccurred()) {
7955 Diag(CurrentLocation, diag::note_member_synthesized_at)
7956 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7957 Invalid = true;
7958 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007959 }
7960 }
7961
7962 if (Invalid) {
7963 CopyAssignOperator->setInvalidDecl();
7964 return;
7965 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007966
7967 StmtResult Body;
7968 {
7969 CompoundScopeRAII CompoundScope(*this);
7970 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7971 /*isStmtExpr=*/false);
7972 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7973 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007975
7976 if (ASTMutationListener *L = getASTMutationListener()) {
7977 L->CompletedImplicitDefinition(CopyAssignOperator);
7978 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007979}
7980
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007981Sema::ImplicitExceptionSpecification
7982Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7983 ImplicitExceptionSpecification ExceptSpec(Context);
7984
7985 if (ClassDecl->isInvalidDecl())
7986 return ExceptSpec;
7987
7988 // C++0x [except.spec]p14:
7989 // An implicitly declared special member function (Clause 12) shall have an
7990 // exception-specification. [...]
7991
7992 // It is unspecified whether or not an implicit move assignment operator
7993 // attempts to deduplicate calls to assignment operators of virtual bases are
7994 // made. As such, this exception specification is effectively unspecified.
7995 // Based on a similar decision made for constness in C++0x, we're erring on
7996 // the side of assuming such calls to be made regardless of whether they
7997 // actually happen.
7998 // Note that a move constructor is not implicitly declared when there are
7999 // virtual bases, but it can still be user-declared and explicitly defaulted.
8000 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8001 BaseEnd = ClassDecl->bases_end();
8002 Base != BaseEnd; ++Base) {
8003 if (Base->isVirtual())
8004 continue;
8005
8006 CXXRecordDecl *BaseClassDecl
8007 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8008 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8009 false, 0))
8010 ExceptSpec.CalledDecl(MoveAssign);
8011 }
8012
8013 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8014 BaseEnd = ClassDecl->vbases_end();
8015 Base != BaseEnd; ++Base) {
8016 CXXRecordDecl *BaseClassDecl
8017 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8018 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8019 false, 0))
8020 ExceptSpec.CalledDecl(MoveAssign);
8021 }
8022
8023 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8024 FieldEnd = ClassDecl->field_end();
8025 Field != FieldEnd;
8026 ++Field) {
8027 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8028 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8029 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8030 false, 0))
8031 ExceptSpec.CalledDecl(MoveAssign);
8032 }
8033 }
8034
8035 return ExceptSpec;
8036}
8037
8038CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8039 // Note: The following rules are largely analoguous to the move
8040 // constructor rules.
8041
8042 ImplicitExceptionSpecification Spec(
8043 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8044
8045 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8046 QualType RetType = Context.getLValueReferenceType(ArgType);
8047 ArgType = Context.getRValueReferenceType(ArgType);
8048
8049 // An implicitly-declared move assignment operator is an inline public
8050 // member of its class.
8051 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8052 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8053 SourceLocation ClassLoc = ClassDecl->getLocation();
8054 DeclarationNameInfo NameInfo(Name, ClassLoc);
8055 CXXMethodDecl *MoveAssignment
8056 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8057 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8058 /*TInfo=*/0, /*isStatic=*/false,
8059 /*StorageClassAsWritten=*/SC_None,
8060 /*isInline=*/true,
8061 /*isConstexpr=*/false,
8062 SourceLocation());
8063 MoveAssignment->setAccess(AS_public);
8064 MoveAssignment->setDefaulted();
8065 MoveAssignment->setImplicit();
8066 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8067
8068 // Add the parameter to the operator.
8069 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8070 ClassLoc, ClassLoc, /*Id=*/0,
8071 ArgType, /*TInfo=*/0,
8072 SC_None,
8073 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008074 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008075
8076 // Note that we have added this copy-assignment operator.
8077 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8078
8079 // C++0x [class.copy]p9:
8080 // If the definition of a class X does not explicitly declare a move
8081 // assignment operator, one will be implicitly declared as defaulted if and
8082 // only if:
8083 // [...]
8084 // - the move assignment operator would not be implicitly defined as
8085 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008086 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008087 // Cache this result so that we don't try to generate this over and over
8088 // on every lookup, leaking memory and wasting time.
8089 ClassDecl->setFailedImplicitMoveAssignment();
8090 return 0;
8091 }
8092
8093 if (Scope *S = getScopeForContext(ClassDecl))
8094 PushOnScopeChains(MoveAssignment, S, false);
8095 ClassDecl->addDecl(MoveAssignment);
8096
8097 AddOverriddenMethods(ClassDecl, MoveAssignment);
8098 return MoveAssignment;
8099}
8100
8101void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8102 CXXMethodDecl *MoveAssignOperator) {
8103 assert((MoveAssignOperator->isDefaulted() &&
8104 MoveAssignOperator->isOverloadedOperator() &&
8105 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008106 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8107 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008108 "DefineImplicitMoveAssignment called for wrong function");
8109
8110 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8111
8112 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8113 MoveAssignOperator->setInvalidDecl();
8114 return;
8115 }
8116
8117 MoveAssignOperator->setUsed();
8118
8119 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8120 DiagnosticErrorTrap Trap(Diags);
8121
8122 // C++0x [class.copy]p28:
8123 // The implicitly-defined or move assignment operator for a non-union class
8124 // X performs memberwise move assignment of its subobjects. The direct base
8125 // classes of X are assigned first, in the order of their declaration in the
8126 // base-specifier-list, and then the immediate non-static data members of X
8127 // are assigned, in the order in which they were declared in the class
8128 // definition.
8129
8130 // The statements that form the synthesized function body.
8131 ASTOwningVector<Stmt*> Statements(*this);
8132
8133 // The parameter for the "other" object, which we are move from.
8134 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8135 QualType OtherRefType = Other->getType()->
8136 getAs<RValueReferenceType>()->getPointeeType();
8137 assert(OtherRefType.getQualifiers() == 0 &&
8138 "Bad argument type of defaulted move assignment");
8139
8140 // Our location for everything implicitly-generated.
8141 SourceLocation Loc = MoveAssignOperator->getLocation();
8142
8143 // Construct a reference to the "other" object. We'll be using this
8144 // throughout the generated ASTs.
8145 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8146 assert(OtherRef && "Reference to parameter cannot fail!");
8147 // Cast to rvalue.
8148 OtherRef = CastForMoving(*this, OtherRef);
8149
8150 // Construct the "this" pointer. We'll be using this throughout the generated
8151 // ASTs.
8152 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8153 assert(This && "Reference to this cannot fail!");
8154
8155 // Assign base classes.
8156 bool Invalid = false;
8157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8158 E = ClassDecl->bases_end(); Base != E; ++Base) {
8159 // Form the assignment:
8160 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8161 QualType BaseType = Base->getType().getUnqualifiedType();
8162 if (!BaseType->isRecordType()) {
8163 Invalid = true;
8164 continue;
8165 }
8166
8167 CXXCastPath BasePath;
8168 BasePath.push_back(Base);
8169
8170 // Construct the "from" expression, which is an implicit cast to the
8171 // appropriately-qualified base type.
8172 Expr *From = OtherRef;
8173 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008174 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008175
8176 // Dereference "this".
8177 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8178
8179 // Implicitly cast "this" to the appropriately-qualified base type.
8180 To = ImpCastExprToType(To.take(),
8181 Context.getCVRQualifiedType(BaseType,
8182 MoveAssignOperator->getTypeQualifiers()),
8183 CK_UncheckedDerivedToBase,
8184 VK_LValue, &BasePath);
8185
8186 // Build the move.
8187 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8188 To.get(), From,
8189 /*CopyingBaseSubobject=*/true,
8190 /*Copying=*/false);
8191 if (Move.isInvalid()) {
8192 Diag(CurrentLocation, diag::note_member_synthesized_at)
8193 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8194 MoveAssignOperator->setInvalidDecl();
8195 return;
8196 }
8197
8198 // Success! Record the move.
8199 Statements.push_back(Move.takeAs<Expr>());
8200 }
8201
8202 // \brief Reference to the __builtin_memcpy function.
8203 Expr *BuiltinMemCpyRef = 0;
8204 // \brief Reference to the __builtin_objc_memmove_collectable function.
8205 Expr *CollectableMemCpyRef = 0;
8206
8207 // Assign non-static members.
8208 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8209 FieldEnd = ClassDecl->field_end();
8210 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008211 if (Field->isUnnamedBitfield())
8212 continue;
8213
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008214 // Check for members of reference type; we can't move those.
8215 if (Field->getType()->isReferenceType()) {
8216 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8217 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8218 Diag(Field->getLocation(), diag::note_declared_at);
8219 Diag(CurrentLocation, diag::note_member_synthesized_at)
8220 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8221 Invalid = true;
8222 continue;
8223 }
8224
8225 // Check for members of const-qualified, non-class type.
8226 QualType BaseType = Context.getBaseElementType(Field->getType());
8227 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8228 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8229 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8230 Diag(Field->getLocation(), diag::note_declared_at);
8231 Diag(CurrentLocation, diag::note_member_synthesized_at)
8232 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8233 Invalid = true;
8234 continue;
8235 }
8236
8237 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008238 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8239 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008240
8241 QualType FieldType = Field->getType().getNonReferenceType();
8242 if (FieldType->isIncompleteArrayType()) {
8243 assert(ClassDecl->hasFlexibleArrayMember() &&
8244 "Incomplete array type is not valid");
8245 continue;
8246 }
8247
8248 // Build references to the field in the object we're copying from and to.
8249 CXXScopeSpec SS; // Intentionally empty
8250 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8251 LookupMemberName);
8252 MemberLookup.addDecl(*Field);
8253 MemberLookup.resolveKind();
8254 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8255 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008256 SS, SourceLocation(), 0,
8257 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008258 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8259 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008260 SS, SourceLocation(), 0,
8261 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008262 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8263 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8264
8265 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8266 "Member reference with rvalue base must be rvalue except for reference "
8267 "members, which aren't allowed for move assignment.");
8268
8269 // If the field should be copied with __builtin_memcpy rather than via
8270 // explicit assignments, do so. This optimization only applies for arrays
8271 // of scalars and arrays of class type with trivial move-assignment
8272 // operators.
8273 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8274 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8275 // Compute the size of the memory buffer to be copied.
8276 QualType SizeType = Context.getSizeType();
8277 llvm::APInt Size(Context.getTypeSize(SizeType),
8278 Context.getTypeSizeInChars(BaseType).getQuantity());
8279 for (const ConstantArrayType *Array
8280 = Context.getAsConstantArrayType(FieldType);
8281 Array;
8282 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8283 llvm::APInt ArraySize
8284 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8285 Size *= ArraySize;
8286 }
8287
Douglas Gregor45d3d712011-09-01 02:09:07 +00008288 // Take the address of the field references for "from" and "to". We
8289 // directly construct UnaryOperators here because semantic analysis
8290 // does not permit us to take the address of an xvalue.
8291 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8292 Context.getPointerType(From.get()->getType()),
8293 VK_RValue, OK_Ordinary, Loc);
8294 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8295 Context.getPointerType(To.get()->getType()),
8296 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008297
8298 bool NeedsCollectableMemCpy =
8299 (BaseType->isRecordType() &&
8300 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8301
8302 if (NeedsCollectableMemCpy) {
8303 if (!CollectableMemCpyRef) {
8304 // Create a reference to the __builtin_objc_memmove_collectable function.
8305 LookupResult R(*this,
8306 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8307 Loc, LookupOrdinaryName);
8308 LookupName(R, TUScope, true);
8309
8310 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8311 if (!CollectableMemCpy) {
8312 // Something went horribly wrong earlier, and we will have
8313 // complained about it.
8314 Invalid = true;
8315 continue;
8316 }
8317
8318 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8319 CollectableMemCpy->getType(),
8320 VK_LValue, Loc, 0).take();
8321 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8322 }
8323 }
8324 // Create a reference to the __builtin_memcpy builtin function.
8325 else if (!BuiltinMemCpyRef) {
8326 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8327 LookupOrdinaryName);
8328 LookupName(R, TUScope, true);
8329
8330 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8331 if (!BuiltinMemCpy) {
8332 // Something went horribly wrong earlier, and we will have complained
8333 // about it.
8334 Invalid = true;
8335 continue;
8336 }
8337
8338 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8339 BuiltinMemCpy->getType(),
8340 VK_LValue, Loc, 0).take();
8341 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8342 }
8343
8344 ASTOwningVector<Expr*> CallArgs(*this);
8345 CallArgs.push_back(To.takeAs<Expr>());
8346 CallArgs.push_back(From.takeAs<Expr>());
8347 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8348 ExprResult Call = ExprError();
8349 if (NeedsCollectableMemCpy)
8350 Call = ActOnCallExpr(/*Scope=*/0,
8351 CollectableMemCpyRef,
8352 Loc, move_arg(CallArgs),
8353 Loc);
8354 else
8355 Call = ActOnCallExpr(/*Scope=*/0,
8356 BuiltinMemCpyRef,
8357 Loc, move_arg(CallArgs),
8358 Loc);
8359
8360 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8361 Statements.push_back(Call.takeAs<Expr>());
8362 continue;
8363 }
8364
8365 // Build the move of this field.
8366 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8367 To.get(), From.get(),
8368 /*CopyingBaseSubobject=*/false,
8369 /*Copying=*/false);
8370 if (Move.isInvalid()) {
8371 Diag(CurrentLocation, diag::note_member_synthesized_at)
8372 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8373 MoveAssignOperator->setInvalidDecl();
8374 return;
8375 }
8376
8377 // Success! Record the copy.
8378 Statements.push_back(Move.takeAs<Stmt>());
8379 }
8380
8381 if (!Invalid) {
8382 // Add a "return *this;"
8383 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8384
8385 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8386 if (Return.isInvalid())
8387 Invalid = true;
8388 else {
8389 Statements.push_back(Return.takeAs<Stmt>());
8390
8391 if (Trap.hasErrorOccurred()) {
8392 Diag(CurrentLocation, diag::note_member_synthesized_at)
8393 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8394 Invalid = true;
8395 }
8396 }
8397 }
8398
8399 if (Invalid) {
8400 MoveAssignOperator->setInvalidDecl();
8401 return;
8402 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008403
8404 StmtResult Body;
8405 {
8406 CompoundScopeRAII CompoundScope(*this);
8407 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8408 /*isStmtExpr=*/false);
8409 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8410 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008411 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8412
8413 if (ASTMutationListener *L = getASTMutationListener()) {
8414 L->CompletedImplicitDefinition(MoveAssignOperator);
8415 }
8416}
8417
Sean Hunt49634cf2011-05-13 06:10:58 +00008418std::pair<Sema::ImplicitExceptionSpecification, bool>
8419Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008420 if (ClassDecl->isInvalidDecl())
8421 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8422
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008423 // C++ [class.copy]p5:
8424 // The implicitly-declared copy constructor for a class X will
8425 // have the form
8426 //
8427 // X::X(const X&)
8428 //
8429 // if
Sean Huntc530d172011-06-10 04:44:37 +00008430 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008431 bool HasConstCopyConstructor = true;
8432
8433 // -- each direct or virtual base class B of X has a copy
8434 // constructor whose first parameter is of type const B& or
8435 // const volatile B&, and
8436 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8437 BaseEnd = ClassDecl->bases_end();
8438 HasConstCopyConstructor && Base != BaseEnd;
8439 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008440 // Virtual bases are handled below.
8441 if (Base->isVirtual())
8442 continue;
8443
Douglas Gregor22584312010-07-02 23:41:54 +00008444 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008445 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008446 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8447 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008448 }
8449
8450 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8451 BaseEnd = ClassDecl->vbases_end();
8452 HasConstCopyConstructor && Base != BaseEnd;
8453 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008454 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008455 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008456 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8457 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008458 }
8459
8460 // -- for all the nonstatic data members of X that are of a
8461 // class type M (or array thereof), each such class type
8462 // has a copy constructor whose first parameter is of type
8463 // const M& or const volatile M&.
8464 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8465 FieldEnd = ClassDecl->field_end();
8466 HasConstCopyConstructor && Field != FieldEnd;
8467 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008468 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008469 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008470 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8471 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008472 }
8473 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008474 // Otherwise, the implicitly declared copy constructor will have
8475 // the form
8476 //
8477 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008478
Douglas Gregor0d405db2010-07-01 20:59:04 +00008479 // C++ [except.spec]p14:
8480 // An implicitly declared special member function (Clause 12) shall have an
8481 // exception-specification. [...]
8482 ImplicitExceptionSpecification ExceptSpec(Context);
8483 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8484 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8485 BaseEnd = ClassDecl->bases_end();
8486 Base != BaseEnd;
8487 ++Base) {
8488 // Virtual bases are handled below.
8489 if (Base->isVirtual())
8490 continue;
8491
Douglas Gregor22584312010-07-02 23:41:54 +00008492 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008493 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008494 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008495 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008496 ExceptSpec.CalledDecl(CopyConstructor);
8497 }
8498 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8499 BaseEnd = ClassDecl->vbases_end();
8500 Base != BaseEnd;
8501 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008502 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008503 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008504 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008505 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008506 ExceptSpec.CalledDecl(CopyConstructor);
8507 }
8508 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8509 FieldEnd = ClassDecl->field_end();
8510 Field != FieldEnd;
8511 ++Field) {
8512 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008513 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8514 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008515 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008516 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008517 }
8518 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008519
Sean Hunt49634cf2011-05-13 06:10:58 +00008520 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8521}
8522
8523CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8524 CXXRecordDecl *ClassDecl) {
8525 // C++ [class.copy]p4:
8526 // If the class definition does not explicitly declare a copy
8527 // constructor, one is declared implicitly.
8528
8529 ImplicitExceptionSpecification Spec(Context);
8530 bool Const;
8531 llvm::tie(Spec, Const) =
8532 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8533
8534 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8535 QualType ArgType = ClassType;
8536 if (Const)
8537 ArgType = ArgType.withConst();
8538 ArgType = Context.getLValueReferenceType(ArgType);
8539
8540 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8541
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008542 DeclarationName Name
8543 = Context.DeclarationNames.getCXXConstructorName(
8544 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008545 SourceLocation ClassLoc = ClassDecl->getLocation();
8546 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008547
8548 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008549 // member of its class.
8550 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8551 Context, ClassDecl, ClassLoc, NameInfo,
8552 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8553 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8554 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008555 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008556 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008557 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008558 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008559
Douglas Gregor22584312010-07-02 23:41:54 +00008560 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008561 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8562
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008563 // Add the parameter to the constructor.
8564 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008565 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008566 /*IdentifierInfo=*/0,
8567 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008568 SC_None,
8569 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008570 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008571
Douglas Gregor23c94db2010-07-02 17:43:08 +00008572 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008573 PushOnScopeChains(CopyConstructor, S, false);
8574 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008575
Nico Weberafcc96a2012-01-23 03:19:29 +00008576 // C++11 [class.copy]p8:
8577 // ... If the class definition does not explicitly declare a copy
8578 // constructor, there is no user-declared move constructor, and there is no
8579 // user-declared move assignment operator, a copy constructor is implicitly
8580 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008581 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008582 (ClassDecl->hasUserDeclaredMoveAssignment() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008583 !getLangOpts().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008584 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008585 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008586
8587 return CopyConstructor;
8588}
8589
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008590void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008591 CXXConstructorDecl *CopyConstructor) {
8592 assert((CopyConstructor->isDefaulted() &&
8593 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008594 !CopyConstructor->doesThisDeclarationHaveABody() &&
8595 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008596 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008597
Anders Carlsson63010a72010-04-23 16:24:12 +00008598 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008599 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008600
Douglas Gregor39957dc2010-05-01 15:04:51 +00008601 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008602 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008603
Sean Huntcbb67482011-01-08 20:30:50 +00008604 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008605 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008606 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008607 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008608 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008609 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008610 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008611 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8612 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008613 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008614 /*isStmtExpr=*/false)
8615 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008616 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008617 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008618
8619 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008620 if (ASTMutationListener *L = getASTMutationListener()) {
8621 L->CompletedImplicitDefinition(CopyConstructor);
8622 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008623}
8624
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008625Sema::ImplicitExceptionSpecification
8626Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8627 // C++ [except.spec]p14:
8628 // An implicitly declared special member function (Clause 12) shall have an
8629 // exception-specification. [...]
8630 ImplicitExceptionSpecification ExceptSpec(Context);
8631 if (ClassDecl->isInvalidDecl())
8632 return ExceptSpec;
8633
8634 // Direct base-class constructors.
8635 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8636 BEnd = ClassDecl->bases_end();
8637 B != BEnd; ++B) {
8638 if (B->isVirtual()) // Handled below.
8639 continue;
8640
8641 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8642 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8643 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8644 // If this is a deleted function, add it anyway. This might be conformant
8645 // with the standard. This might not. I'm not sure. It might not matter.
8646 if (Constructor)
8647 ExceptSpec.CalledDecl(Constructor);
8648 }
8649 }
8650
8651 // Virtual base-class constructors.
8652 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8653 BEnd = ClassDecl->vbases_end();
8654 B != BEnd; ++B) {
8655 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8656 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8657 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8658 // If this is a deleted function, add it anyway. This might be conformant
8659 // with the standard. This might not. I'm not sure. It might not matter.
8660 if (Constructor)
8661 ExceptSpec.CalledDecl(Constructor);
8662 }
8663 }
8664
8665 // Field constructors.
8666 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8667 FEnd = ClassDecl->field_end();
8668 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008669 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008670 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8671 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8672 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8673 // If this is a deleted function, add it anyway. This might be conformant
8674 // with the standard. This might not. I'm not sure. It might not matter.
8675 // In particular, the problem is that this function never gets called. It
8676 // might just be ill-formed because this function attempts to refer to
8677 // a deleted function here.
8678 if (Constructor)
8679 ExceptSpec.CalledDecl(Constructor);
8680 }
8681 }
8682
8683 return ExceptSpec;
8684}
8685
8686CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8687 CXXRecordDecl *ClassDecl) {
8688 ImplicitExceptionSpecification Spec(
8689 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8690
8691 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8692 QualType ArgType = Context.getRValueReferenceType(ClassType);
8693
8694 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8695
8696 DeclarationName Name
8697 = Context.DeclarationNames.getCXXConstructorName(
8698 Context.getCanonicalType(ClassType));
8699 SourceLocation ClassLoc = ClassDecl->getLocation();
8700 DeclarationNameInfo NameInfo(Name, ClassLoc);
8701
8702 // C++0x [class.copy]p11:
8703 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008704 // member of its class.
8705 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8706 Context, ClassDecl, ClassLoc, NameInfo,
8707 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8708 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8709 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008710 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008711 MoveConstructor->setAccess(AS_public);
8712 MoveConstructor->setDefaulted();
8713 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008714
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008715 // Add the parameter to the constructor.
8716 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8717 ClassLoc, ClassLoc,
8718 /*IdentifierInfo=*/0,
8719 ArgType, /*TInfo=*/0,
8720 SC_None,
8721 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008722 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008723
8724 // C++0x [class.copy]p9:
8725 // If the definition of a class X does not explicitly declare a move
8726 // constructor, one will be implicitly declared as defaulted if and only if:
8727 // [...]
8728 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008729 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008730 // Cache this result so that we don't try to generate this over and over
8731 // on every lookup, leaking memory and wasting time.
8732 ClassDecl->setFailedImplicitMoveConstructor();
8733 return 0;
8734 }
8735
8736 // Note that we have declared this constructor.
8737 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8738
8739 if (Scope *S = getScopeForContext(ClassDecl))
8740 PushOnScopeChains(MoveConstructor, S, false);
8741 ClassDecl->addDecl(MoveConstructor);
8742
8743 return MoveConstructor;
8744}
8745
8746void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8747 CXXConstructorDecl *MoveConstructor) {
8748 assert((MoveConstructor->isDefaulted() &&
8749 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008750 !MoveConstructor->doesThisDeclarationHaveABody() &&
8751 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008752 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8753
8754 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8755 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8756
8757 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8758 DiagnosticErrorTrap Trap(Diags);
8759
8760 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8761 Trap.hasErrorOccurred()) {
8762 Diag(CurrentLocation, diag::note_member_synthesized_at)
8763 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8764 MoveConstructor->setInvalidDecl();
8765 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008766 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008767 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8768 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008769 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770 /*isStmtExpr=*/false)
8771 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008772 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008773 }
8774
8775 MoveConstructor->setUsed();
8776
8777 if (ASTMutationListener *L = getASTMutationListener()) {
8778 L->CompletedImplicitDefinition(MoveConstructor);
8779 }
8780}
8781
Douglas Gregore4e68d42012-02-15 19:33:52 +00008782bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8783 return FD->isDeleted() &&
8784 (FD->isDefaulted() || FD->isImplicit()) &&
8785 isa<CXXMethodDecl>(FD);
8786}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008787
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008788/// \brief Mark the call operator of the given lambda closure type as "used".
8789static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8790 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008791 = cast<CXXMethodDecl>(
8792 *Lambda->lookup(
8793 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008794 CallOperator->setReferenced();
8795 CallOperator->setUsed();
8796}
8797
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008798void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8799 SourceLocation CurrentLocation,
8800 CXXConversionDecl *Conv)
8801{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008802 CXXRecordDecl *Lambda = Conv->getParent();
8803
8804 // Make sure that the lambda call operator is marked used.
8805 markLambdaCallOperatorUsed(*this, Lambda);
8806
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008807 Conv->setUsed();
8808
8809 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8810 DiagnosticErrorTrap Trap(Diags);
8811
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008812 // Return the address of the __invoke function.
8813 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8814 CXXMethodDecl *Invoke
8815 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8816 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8817 VK_LValue, Conv->getLocation()).take();
8818 assert(FunctionRef && "Can't refer to __invoke function?");
8819 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8820 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8821 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008822 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008823
8824 // Fill in the __invoke function with a dummy implementation. IR generation
8825 // will fill in the actual details.
8826 Invoke->setUsed();
8827 Invoke->setReferenced();
8828 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8829 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008830
8831 if (ASTMutationListener *L = getASTMutationListener()) {
8832 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008833 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008834 }
8835}
8836
8837void Sema::DefineImplicitLambdaToBlockPointerConversion(
8838 SourceLocation CurrentLocation,
8839 CXXConversionDecl *Conv)
8840{
8841 Conv->setUsed();
8842
8843 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8844 DiagnosticErrorTrap Trap(Diags);
8845
Douglas Gregorac1303e2012-02-22 05:02:47 +00008846 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008847 Expr *This = ActOnCXXThis(CurrentLocation).take();
8848 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008849
Eli Friedman23f02672012-03-01 04:01:32 +00008850 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8851 Conv->getLocation(),
8852 Conv, DerefThis);
8853
8854 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8855 // behavior. Note that only the general conversion function does this
8856 // (since it's unusable otherwise); in the case where we inline the
8857 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008858 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008859 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8860 CK_CopyAndAutoreleaseBlockObject,
8861 BuildBlock.get(), 0, VK_RValue);
8862
8863 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008864 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008865 Conv->setInvalidDecl();
8866 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008867 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008868
Douglas Gregorac1303e2012-02-22 05:02:47 +00008869 // Create the return statement that returns the block from the conversion
8870 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008871 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008872 if (Return.isInvalid()) {
8873 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8874 Conv->setInvalidDecl();
8875 return;
8876 }
8877
8878 // Set the body of the conversion function.
8879 Stmt *ReturnS = Return.take();
8880 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8881 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008882 Conv->getLocation()));
8883
Douglas Gregorac1303e2012-02-22 05:02:47 +00008884 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008885 if (ASTMutationListener *L = getASTMutationListener()) {
8886 L->CompletedImplicitDefinition(Conv);
8887 }
8888}
8889
Douglas Gregorf52757d2012-03-10 06:53:13 +00008890/// \brief Determine whether the given list arguments contains exactly one
8891/// "real" (non-default) argument.
8892static bool hasOneRealArgument(MultiExprArg Args) {
8893 switch (Args.size()) {
8894 case 0:
8895 return false;
8896
8897 default:
8898 if (!Args.get()[1]->isDefaultArgument())
8899 return false;
8900
8901 // fall through
8902 case 1:
8903 return !Args.get()[0]->isDefaultArgument();
8904 }
8905
8906 return false;
8907}
8908
John McCall60d7b3a2010-08-24 06:29:42 +00008909ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008911 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008912 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008913 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008914 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008915 unsigned ConstructKind,
8916 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008917 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008918
Douglas Gregor2f599792010-04-02 18:24:57 +00008919 // C++0x [class.copy]p34:
8920 // When certain criteria are met, an implementation is allowed to
8921 // omit the copy/move construction of a class object, even if the
8922 // copy/move constructor and/or destructor for the object have
8923 // side effects. [...]
8924 // - when a temporary class object that has not been bound to a
8925 // reference (12.2) would be copied/moved to a class object
8926 // with the same cv-unqualified type, the copy/move operation
8927 // can be omitted by constructing the temporary object
8928 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008929 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00008930 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008931 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008932 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008933 }
Mike Stump1eb44332009-09-09 15:08:12 +00008934
8935 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008936 Elidable, move(ExprArgs), HadMultipleCandidates,
8937 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008938}
8939
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008940/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8941/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008942ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008943Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8944 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008945 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008946 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008947 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008948 unsigned ConstructKind,
8949 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008950 unsigned NumExprs = ExprArgs.size();
8951 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008952
Nick Lewycky909a70d2011-03-25 01:44:32 +00008953 for (specific_attr_iterator<NonNullAttr>
8954 i = Constructor->specific_attr_begin<NonNullAttr>(),
8955 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8956 const NonNullAttr *NonNull = *i;
8957 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8958 }
8959
Eli Friedman5f2987c2012-02-02 03:46:19 +00008960 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008961 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008962 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008963 HadMultipleCandidates, /*FIXME*/false,
8964 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008965 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8966 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008967}
8968
Mike Stump1eb44332009-09-09 15:08:12 +00008969bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008970 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008971 MultiExprArg Exprs,
8972 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008973 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008974 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008975 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008976 move(Exprs), HadMultipleCandidates, false,
8977 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008978 if (TempResult.isInvalid())
8979 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008980
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008981 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008982 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00008983 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008984 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008985 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008986
Anders Carlssonfe2de492009-08-25 05:18:00 +00008987 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008988}
8989
John McCall68c6c9a2010-02-02 09:10:11 +00008990void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008991 if (VD->isInvalidDecl()) return;
8992
John McCall68c6c9a2010-02-02 09:10:11 +00008993 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008994 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00008995 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008996 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008997
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008998 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00008999 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009000 CheckDestructorAccess(VD->getLocation(), Destructor,
9001 PDiag(diag::err_access_dtor_var)
9002 << VD->getDeclName()
9003 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009004 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009005
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009006 if (!VD->hasGlobalStorage()) return;
9007
9008 // Emit warning for non-trivial dtor in global scope (a real global,
9009 // class-static, function-static).
9010 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9011
9012 // TODO: this should be re-enabled for static locals by !CXAAtExit
9013 if (!VD->isStaticLocal())
9014 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009015}
9016
Douglas Gregor39da0b82009-09-09 23:08:42 +00009017/// \brief Given a constructor and the set of arguments provided for the
9018/// constructor, convert the arguments and add any required default arguments
9019/// to form a proper call to this constructor.
9020///
9021/// \returns true if an error occurred, false otherwise.
9022bool
9023Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9024 MultiExprArg ArgsPtr,
9025 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009026 ASTOwningVector<Expr*> &ConvertedArgs,
9027 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009028 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9029 unsigned NumArgs = ArgsPtr.size();
9030 Expr **Args = (Expr **)ArgsPtr.get();
9031
9032 const FunctionProtoType *Proto
9033 = Constructor->getType()->getAs<FunctionProtoType>();
9034 assert(Proto && "Constructor without a prototype?");
9035 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009036
9037 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009038 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009039 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009040 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009041 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009042
9043 VariadicCallType CallType =
9044 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009045 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009046 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9047 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009048 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009049 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009050
9051 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9052
9053 // FIXME: Missing call to CheckFunctionCall or equivalent
9054
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009055 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009056}
9057
Anders Carlsson20d45d22009-12-12 00:32:00 +00009058static inline bool
9059CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9060 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009061 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009062 if (isa<NamespaceDecl>(DC)) {
9063 return SemaRef.Diag(FnDecl->getLocation(),
9064 diag::err_operator_new_delete_declared_in_namespace)
9065 << FnDecl->getDeclName();
9066 }
9067
9068 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009069 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009070 return SemaRef.Diag(FnDecl->getLocation(),
9071 diag::err_operator_new_delete_declared_static)
9072 << FnDecl->getDeclName();
9073 }
9074
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009075 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009076}
9077
Anders Carlsson156c78e2009-12-13 17:53:43 +00009078static inline bool
9079CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9080 CanQualType ExpectedResultType,
9081 CanQualType ExpectedFirstParamType,
9082 unsigned DependentParamTypeDiag,
9083 unsigned InvalidParamTypeDiag) {
9084 QualType ResultType =
9085 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9086
9087 // Check that the result type is not dependent.
9088 if (ResultType->isDependentType())
9089 return SemaRef.Diag(FnDecl->getLocation(),
9090 diag::err_operator_new_delete_dependent_result_type)
9091 << FnDecl->getDeclName() << ExpectedResultType;
9092
9093 // Check that the result type is what we expect.
9094 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9095 return SemaRef.Diag(FnDecl->getLocation(),
9096 diag::err_operator_new_delete_invalid_result_type)
9097 << FnDecl->getDeclName() << ExpectedResultType;
9098
9099 // A function template must have at least 2 parameters.
9100 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9101 return SemaRef.Diag(FnDecl->getLocation(),
9102 diag::err_operator_new_delete_template_too_few_parameters)
9103 << FnDecl->getDeclName();
9104
9105 // The function decl must have at least 1 parameter.
9106 if (FnDecl->getNumParams() == 0)
9107 return SemaRef.Diag(FnDecl->getLocation(),
9108 diag::err_operator_new_delete_too_few_parameters)
9109 << FnDecl->getDeclName();
9110
9111 // Check the the first parameter type is not dependent.
9112 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9113 if (FirstParamType->isDependentType())
9114 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9115 << FnDecl->getDeclName() << ExpectedFirstParamType;
9116
9117 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009118 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009119 ExpectedFirstParamType)
9120 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9121 << FnDecl->getDeclName() << ExpectedFirstParamType;
9122
9123 return false;
9124}
9125
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009126static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009127CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009128 // C++ [basic.stc.dynamic.allocation]p1:
9129 // A program is ill-formed if an allocation function is declared in a
9130 // namespace scope other than global scope or declared static in global
9131 // scope.
9132 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9133 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009134
9135 CanQualType SizeTy =
9136 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9137
9138 // C++ [basic.stc.dynamic.allocation]p1:
9139 // The return type shall be void*. The first parameter shall have type
9140 // std::size_t.
9141 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9142 SizeTy,
9143 diag::err_operator_new_dependent_param_type,
9144 diag::err_operator_new_param_type))
9145 return true;
9146
9147 // C++ [basic.stc.dynamic.allocation]p1:
9148 // The first parameter shall not have an associated default argument.
9149 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009150 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009151 diag::err_operator_new_default_arg)
9152 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9153
9154 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009155}
9156
9157static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009158CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9159 // C++ [basic.stc.dynamic.deallocation]p1:
9160 // A program is ill-formed if deallocation functions are declared in a
9161 // namespace scope other than global scope or declared static in global
9162 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009163 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9164 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009165
9166 // C++ [basic.stc.dynamic.deallocation]p2:
9167 // Each deallocation function shall return void and its first parameter
9168 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009169 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9170 SemaRef.Context.VoidPtrTy,
9171 diag::err_operator_delete_dependent_param_type,
9172 diag::err_operator_delete_param_type))
9173 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009174
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009175 return false;
9176}
9177
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009178/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9179/// of this overloaded operator is well-formed. If so, returns false;
9180/// otherwise, emits appropriate diagnostics and returns true.
9181bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009182 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009183 "Expected an overloaded operator declaration");
9184
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009185 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9186
Mike Stump1eb44332009-09-09 15:08:12 +00009187 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009188 // The allocation and deallocation functions, operator new,
9189 // operator new[], operator delete and operator delete[], are
9190 // described completely in 3.7.3. The attributes and restrictions
9191 // found in the rest of this subclause do not apply to them unless
9192 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009193 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009194 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009195
Anders Carlssona3ccda52009-12-12 00:26:23 +00009196 if (Op == OO_New || Op == OO_Array_New)
9197 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009198
9199 // C++ [over.oper]p6:
9200 // An operator function shall either be a non-static member
9201 // function or be a non-member function and have at least one
9202 // parameter whose type is a class, a reference to a class, an
9203 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009204 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9205 if (MethodDecl->isStatic())
9206 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009207 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009208 } else {
9209 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009210 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9211 ParamEnd = FnDecl->param_end();
9212 Param != ParamEnd; ++Param) {
9213 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009214 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9215 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009216 ClassOrEnumParam = true;
9217 break;
9218 }
9219 }
9220
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009221 if (!ClassOrEnumParam)
9222 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009223 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009224 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009225 }
9226
9227 // C++ [over.oper]p8:
9228 // An operator function cannot have default arguments (8.3.6),
9229 // except where explicitly stated below.
9230 //
Mike Stump1eb44332009-09-09 15:08:12 +00009231 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009232 // (C++ [over.call]p1).
9233 if (Op != OO_Call) {
9234 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9235 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009236 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009237 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009238 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009239 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009240 }
9241 }
9242
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009243 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9244 { false, false, false }
9245#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9246 , { Unary, Binary, MemberOnly }
9247#include "clang/Basic/OperatorKinds.def"
9248 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009249
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009250 bool CanBeUnaryOperator = OperatorUses[Op][0];
9251 bool CanBeBinaryOperator = OperatorUses[Op][1];
9252 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009253
9254 // C++ [over.oper]p8:
9255 // [...] Operator functions cannot have more or fewer parameters
9256 // than the number required for the corresponding operator, as
9257 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009258 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009259 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009260 if (Op != OO_Call &&
9261 ((NumParams == 1 && !CanBeUnaryOperator) ||
9262 (NumParams == 2 && !CanBeBinaryOperator) ||
9263 (NumParams < 1) || (NumParams > 2))) {
9264 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009265 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009266 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009267 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009268 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009269 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009270 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009271 assert(CanBeBinaryOperator &&
9272 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009273 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009274 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009275
Chris Lattner416e46f2008-11-21 07:57:12 +00009276 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009277 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009278 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009279
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009280 // Overloaded operators other than operator() cannot be variadic.
9281 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009282 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009283 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009284 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009285 }
9286
9287 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009288 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9289 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009290 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009291 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009292 }
9293
9294 // C++ [over.inc]p1:
9295 // The user-defined function called operator++ implements the
9296 // prefix and postfix ++ operator. If this function is a member
9297 // function with no parameters, or a non-member function with one
9298 // parameter of class or enumeration type, it defines the prefix
9299 // increment operator ++ for objects of that type. If the function
9300 // is a member function with one parameter (which shall be of type
9301 // int) or a non-member function with two parameters (the second
9302 // of which shall be of type int), it defines the postfix
9303 // increment operator ++ for objects of that type.
9304 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9305 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9306 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009307 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009308 ParamIsInt = BT->getKind() == BuiltinType::Int;
9309
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009310 if (!ParamIsInt)
9311 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009312 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009313 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009314 }
9315
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009316 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009317}
Chris Lattner5a003a42008-12-17 07:09:26 +00009318
Sean Hunta6c058d2010-01-13 09:01:02 +00009319/// CheckLiteralOperatorDeclaration - Check whether the declaration
9320/// of this literal operator function is well-formed. If so, returns
9321/// false; otherwise, emits appropriate diagnostics and returns true.
9322bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009323 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009324 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9325 << FnDecl->getDeclName();
9326 return true;
9327 }
9328
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009329 if (FnDecl->isExternC()) {
9330 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9331 return true;
9332 }
9333
Sean Hunta6c058d2010-01-13 09:01:02 +00009334 bool Valid = false;
9335
Richard Smith36f5cfe2012-03-09 08:00:36 +00009336 // This might be the definition of a literal operator template.
9337 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9338 // This might be a specialization of a literal operator template.
9339 if (!TpDecl)
9340 TpDecl = FnDecl->getPrimaryTemplate();
9341
Sean Hunt216c2782010-04-07 23:11:06 +00009342 // template <char...> type operator "" name() is the only valid template
9343 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009344 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009345 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009346 // Must have only one template parameter
9347 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9348 if (Params->size() == 1) {
9349 NonTypeTemplateParmDecl *PmDecl =
9350 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009351
Sean Hunt216c2782010-04-07 23:11:06 +00009352 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009353 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9354 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9355 Valid = true;
9356 }
9357 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009358 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009359 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009360 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9361
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009362 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009363
Sean Hunt30019c02010-04-07 22:57:35 +00009364 // unsigned long long int, long double, and any character type are allowed
9365 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009366 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9367 Context.hasSameType(T, Context.LongDoubleTy) ||
9368 Context.hasSameType(T, Context.CharTy) ||
9369 Context.hasSameType(T, Context.WCharTy) ||
9370 Context.hasSameType(T, Context.Char16Ty) ||
9371 Context.hasSameType(T, Context.Char32Ty)) {
9372 if (++Param == FnDecl->param_end())
9373 Valid = true;
9374 goto FinishedParams;
9375 }
9376
Sean Hunt30019c02010-04-07 22:57:35 +00009377 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009378 const PointerType *PT = T->getAs<PointerType>();
9379 if (!PT)
9380 goto FinishedParams;
9381 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009382 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009383 goto FinishedParams;
9384 T = T.getUnqualifiedType();
9385
9386 // Move on to the second parameter;
9387 ++Param;
9388
9389 // If there is no second parameter, the first must be a const char *
9390 if (Param == FnDecl->param_end()) {
9391 if (Context.hasSameType(T, Context.CharTy))
9392 Valid = true;
9393 goto FinishedParams;
9394 }
9395
9396 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9397 // are allowed as the first parameter to a two-parameter function
9398 if (!(Context.hasSameType(T, Context.CharTy) ||
9399 Context.hasSameType(T, Context.WCharTy) ||
9400 Context.hasSameType(T, Context.Char16Ty) ||
9401 Context.hasSameType(T, Context.Char32Ty)))
9402 goto FinishedParams;
9403
9404 // The second and final parameter must be an std::size_t
9405 T = (*Param)->getType().getUnqualifiedType();
9406 if (Context.hasSameType(T, Context.getSizeType()) &&
9407 ++Param == FnDecl->param_end())
9408 Valid = true;
9409 }
9410
9411 // FIXME: This diagnostic is absolutely terrible.
9412FinishedParams:
9413 if (!Valid) {
9414 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9415 << FnDecl->getDeclName();
9416 return true;
9417 }
9418
Richard Smitha9e88b22012-03-09 08:16:22 +00009419 // A parameter-declaration-clause containing a default argument is not
9420 // equivalent to any of the permitted forms.
9421 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9422 ParamEnd = FnDecl->param_end();
9423 Param != ParamEnd; ++Param) {
9424 if ((*Param)->hasDefaultArg()) {
9425 Diag((*Param)->getDefaultArgRange().getBegin(),
9426 diag::err_literal_operator_default_argument)
9427 << (*Param)->getDefaultArgRange();
9428 break;
9429 }
9430 }
9431
Richard Smith2fb4ae32012-03-08 02:39:21 +00009432 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009433 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9434 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009435 // C++11 [usrlit.suffix]p1:
9436 // Literal suffix identifiers that do not start with an underscore
9437 // are reserved for future standardization.
9438 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009439 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009440
Sean Hunta6c058d2010-01-13 09:01:02 +00009441 return false;
9442}
9443
Douglas Gregor074149e2009-01-05 19:45:36 +00009444/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9445/// linkage specification, including the language and (if present)
9446/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9447/// the location of the language string literal, which is provided
9448/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9449/// the '{' brace. Otherwise, this linkage specification does not
9450/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009451Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9452 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009453 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009454 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009455 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009456 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009457 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009458 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009459 Language = LinkageSpecDecl::lang_cxx;
9460 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009461 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009462 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009463 }
Mike Stump1eb44332009-09-09 15:08:12 +00009464
Chris Lattnercc98eac2008-12-17 07:13:27 +00009465 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009466
Douglas Gregor074149e2009-01-05 19:45:36 +00009467 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009468 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009469 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009470 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009471 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009472}
9473
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009474/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009475/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9476/// valid, it's the position of the closing '}' brace in a linkage
9477/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009478Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009479 Decl *LinkageSpec,
9480 SourceLocation RBraceLoc) {
9481 if (LinkageSpec) {
9482 if (RBraceLoc.isValid()) {
9483 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9484 LSDecl->setRBraceLoc(RBraceLoc);
9485 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009486 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009487 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009488 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009489}
9490
Douglas Gregord308e622009-05-18 20:51:54 +00009491/// \brief Perform semantic analysis for the variable declaration that
9492/// occurs within a C++ catch clause, returning the newly-created
9493/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009494VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009495 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009496 SourceLocation StartLoc,
9497 SourceLocation Loc,
9498 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009499 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009500 QualType ExDeclType = TInfo->getType();
9501
Sebastian Redl4b07b292008-12-22 19:15:10 +00009502 // Arrays and functions decay.
9503 if (ExDeclType->isArrayType())
9504 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9505 else if (ExDeclType->isFunctionType())
9506 ExDeclType = Context.getPointerType(ExDeclType);
9507
9508 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9509 // The exception-declaration shall not denote a pointer or reference to an
9510 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009511 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009512 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009513 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009514 Invalid = true;
9515 }
Douglas Gregord308e622009-05-18 20:51:54 +00009516
Sebastian Redl4b07b292008-12-22 19:15:10 +00009517 QualType BaseType = ExDeclType;
9518 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009519 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009520 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009521 BaseType = Ptr->getPointeeType();
9522 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009523 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009524 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009525 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009526 BaseType = Ref->getPointeeType();
9527 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009528 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009529 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009530 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009531 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009532 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009533
Mike Stump1eb44332009-09-09 15:08:12 +00009534 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009535 RequireNonAbstractType(Loc, ExDeclType,
9536 diag::err_abstract_type_in_decl,
9537 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009538 Invalid = true;
9539
John McCall5a180392010-07-24 00:37:23 +00009540 // Only the non-fragile NeXT runtime currently supports C++ catches
9541 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009542 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009543 QualType T = ExDeclType;
9544 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9545 T = RT->getPointeeType();
9546
9547 if (T->isObjCObjectType()) {
9548 Diag(Loc, diag::err_objc_object_catch);
9549 Invalid = true;
9550 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009551 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009552 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009553 }
9554 }
9555
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009556 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9557 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009558 ExDecl->setExceptionVariable(true);
9559
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009560 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009561 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009562 Invalid = true;
9563
Douglas Gregorc41b8782011-07-06 18:14:43 +00009564 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009565 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009566 // C++ [except.handle]p16:
9567 // The object declared in an exception-declaration or, if the
9568 // exception-declaration does not specify a name, a temporary (12.2) is
9569 // copy-initialized (8.5) from the exception object. [...]
9570 // The object is destroyed when the handler exits, after the destruction
9571 // of any automatic objects initialized within the handler.
9572 //
9573 // We just pretend to initialize the object with itself, then make sure
9574 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009575 QualType initType = ExDeclType;
9576
9577 InitializedEntity entity =
9578 InitializedEntity::InitializeVariable(ExDecl);
9579 InitializationKind initKind =
9580 InitializationKind::CreateCopy(Loc, SourceLocation());
9581
9582 Expr *opaqueValue =
9583 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9584 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9585 ExprResult result = sequence.Perform(*this, entity, initKind,
9586 MultiExprArg(&opaqueValue, 1));
9587 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009588 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009589 else {
9590 // If the constructor used was non-trivial, set this as the
9591 // "initializer".
9592 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9593 if (!construct->getConstructor()->isTrivial()) {
9594 Expr *init = MaybeCreateExprWithCleanups(construct);
9595 ExDecl->setInit(init);
9596 }
9597
9598 // And make sure it's destructable.
9599 FinalizeVarWithDestructor(ExDecl, recordType);
9600 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009601 }
9602 }
9603
Douglas Gregord308e622009-05-18 20:51:54 +00009604 if (Invalid)
9605 ExDecl->setInvalidDecl();
9606
9607 return ExDecl;
9608}
9609
9610/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9611/// handler.
John McCalld226f652010-08-21 09:40:31 +00009612Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009613 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009614 bool Invalid = D.isInvalidType();
9615
9616 // Check for unexpanded parameter packs.
9617 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9618 UPPC_ExceptionType)) {
9619 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9620 D.getIdentifierLoc());
9621 Invalid = true;
9622 }
9623
Sebastian Redl4b07b292008-12-22 19:15:10 +00009624 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009625 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009626 LookupOrdinaryName,
9627 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009628 // The scope should be freshly made just for us. There is just no way
9629 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009630 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009631 if (PrevDecl->isTemplateParameter()) {
9632 // Maybe we will complain about the shadowed template parameter.
9633 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009634 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009635 }
9636 }
9637
Chris Lattnereaaebc72009-04-25 08:06:05 +00009638 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009639 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9640 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009641 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009642 }
9643
Douglas Gregor83cb9422010-09-09 17:09:21 +00009644 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009645 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009646 D.getIdentifierLoc(),
9647 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009648 if (Invalid)
9649 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009650
Sebastian Redl4b07b292008-12-22 19:15:10 +00009651 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009652 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009653 PushOnScopeChains(ExDecl, S);
9654 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009655 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009656
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009657 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009658 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009659}
Anders Carlssonfb311762009-03-14 00:25:26 +00009660
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009661Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009662 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009663 Expr *AssertMessageExpr_,
9664 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009665 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009666
Anders Carlssonc3082412009-03-14 00:33:21 +00009667 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009668 // In a static_assert-declaration, the constant-expression shall be a
9669 // constant expression that can be contextually converted to bool.
9670 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9671 if (Converted.isInvalid())
9672 return 0;
9673
Richard Smithdaaefc52011-12-14 23:32:26 +00009674 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009675 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9676 PDiag(diag::err_static_assert_expression_is_not_constant),
9677 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009678 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009679
Richard Smith0cc323c2012-03-05 23:20:05 +00009680 if (!Cond) {
9681 llvm::SmallString<256> MsgBuffer;
9682 llvm::raw_svector_ostream Msg(MsgBuffer);
9683 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009684 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009685 << Msg.str() << AssertExpr->getSourceRange();
9686 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009687 }
Mike Stump1eb44332009-09-09 15:08:12 +00009688
Douglas Gregor399ad972010-12-15 23:55:21 +00009689 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9690 return 0;
9691
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009692 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9693 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009694
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009695 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009696 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009697}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009698
Douglas Gregor1d869352010-04-07 16:53:43 +00009699/// \brief Perform semantic analysis of the given friend type declaration.
9700///
9701/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009702FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9703 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009704 TypeSourceInfo *TSInfo) {
9705 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9706
9707 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009708 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009709
Richard Smith6b130222011-10-18 21:39:00 +00009710 // C++03 [class.friend]p2:
9711 // An elaborated-type-specifier shall be used in a friend declaration
9712 // for a class.*
9713 //
9714 // * The class-key of the elaborated-type-specifier is required.
9715 if (!ActiveTemplateInstantiations.empty()) {
9716 // Do not complain about the form of friend template types during
9717 // template instantiation; we will already have complained when the
9718 // template was declared.
9719 } else if (!T->isElaboratedTypeSpecifier()) {
9720 // If we evaluated the type to a record type, suggest putting
9721 // a tag in front.
9722 if (const RecordType *RT = T->getAs<RecordType>()) {
9723 RecordDecl *RD = RT->getDecl();
9724
9725 std::string InsertionText = std::string(" ") + RD->getKindName();
9726
9727 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009728 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009729 diag::warn_cxx98_compat_unelaborated_friend_type :
9730 diag::ext_unelaborated_friend_type)
9731 << (unsigned) RD->getTagKind()
9732 << T
9733 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9734 InsertionText);
9735 } else {
9736 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009737 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009738 diag::warn_cxx98_compat_nonclass_type_friend :
9739 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009740 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009741 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009742 }
Richard Smith6b130222011-10-18 21:39:00 +00009743 } else if (T->getAs<EnumType>()) {
9744 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009745 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009746 diag::warn_cxx98_compat_enum_friend :
9747 diag::ext_enum_friend)
9748 << T
9749 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009750 }
9751
Douglas Gregor06245bf2010-04-07 17:57:12 +00009752 // C++0x [class.friend]p3:
9753 // If the type specifier in a friend declaration designates a (possibly
9754 // cv-qualified) class type, that class is declared as a friend; otherwise,
9755 // the friend declaration is ignored.
9756
9757 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9758 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009759
Abramo Bagnara0216df82011-10-29 20:52:52 +00009760 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009761}
9762
John McCall9a34edb2010-10-19 01:40:49 +00009763/// Handle a friend tag declaration where the scope specifier was
9764/// templated.
9765Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9766 unsigned TagSpec, SourceLocation TagLoc,
9767 CXXScopeSpec &SS,
9768 IdentifierInfo *Name, SourceLocation NameLoc,
9769 AttributeList *Attr,
9770 MultiTemplateParamsArg TempParamLists) {
9771 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9772
9773 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009774 bool Invalid = false;
9775
9776 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009777 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009778 TempParamLists.get(),
9779 TempParamLists.size(),
9780 /*friend*/ true,
9781 isExplicitSpecialization,
9782 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009783 if (TemplateParams->size() > 0) {
9784 // This is a declaration of a class template.
9785 if (Invalid)
9786 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009787
Eric Christopher4110e132011-07-21 05:34:24 +00009788 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9789 SS, Name, NameLoc, Attr,
9790 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009791 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009792 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009793 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009794 } else {
9795 // The "template<>" header is extraneous.
9796 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9797 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9798 isExplicitSpecialization = true;
9799 }
9800 }
9801
9802 if (Invalid) return 0;
9803
John McCall9a34edb2010-10-19 01:40:49 +00009804 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009805 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009806 if (TempParamLists.get()[I]->size()) {
9807 isAllExplicitSpecializations = false;
9808 break;
9809 }
9810 }
9811
9812 // FIXME: don't ignore attributes.
9813
9814 // If it's explicit specializations all the way down, just forget
9815 // about the template header and build an appropriate non-templated
9816 // friend. TODO: for source fidelity, remember the headers.
9817 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009818 if (SS.isEmpty()) {
9819 bool Owned = false;
9820 bool IsDependent = false;
9821 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9822 Attr, AS_public,
9823 /*ModulePrivateLoc=*/SourceLocation(),
9824 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009825 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009826 /*ScopedEnumUsesClassTag=*/false,
9827 /*UnderlyingType=*/TypeResult());
9828 }
9829
Douglas Gregor2494dd02011-03-01 01:34:45 +00009830 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009831 ElaboratedTypeKeyword Keyword
9832 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009833 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009834 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009835 if (T.isNull())
9836 return 0;
9837
9838 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9839 if (isa<DependentNameType>(T)) {
9840 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009841 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009842 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009843 TL.setNameLoc(NameLoc);
9844 } else {
9845 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009846 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009847 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009848 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9849 }
9850
9851 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9852 TSI, FriendLoc);
9853 Friend->setAccess(AS_public);
9854 CurContext->addDecl(Friend);
9855 return Friend;
9856 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009857
9858 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9859
9860
John McCall9a34edb2010-10-19 01:40:49 +00009861
9862 // Handle the case of a templated-scope friend class. e.g.
9863 // template <class T> class A<T>::B;
9864 // FIXME: we don't support these right now.
9865 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9866 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9867 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9868 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009869 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009870 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009871 TL.setNameLoc(NameLoc);
9872
9873 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9874 TSI, FriendLoc);
9875 Friend->setAccess(AS_public);
9876 Friend->setUnsupportedFriend(true);
9877 CurContext->addDecl(Friend);
9878 return Friend;
9879}
9880
9881
John McCalldd4a3b02009-09-16 22:47:08 +00009882/// Handle a friend type declaration. This works in tandem with
9883/// ActOnTag.
9884///
9885/// Notes on friend class templates:
9886///
9887/// We generally treat friend class declarations as if they were
9888/// declaring a class. So, for example, the elaborated type specifier
9889/// in a friend declaration is required to obey the restrictions of a
9890/// class-head (i.e. no typedefs in the scope chain), template
9891/// parameters are required to match up with simple template-ids, &c.
9892/// However, unlike when declaring a template specialization, it's
9893/// okay to refer to a template specialization without an empty
9894/// template parameter declaration, e.g.
9895/// friend class A<T>::B<unsigned>;
9896/// We permit this as a special case; if there are any template
9897/// parameters present at all, require proper matching, i.e.
9898/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009899Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009900 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009901 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009902
9903 assert(DS.isFriendSpecified());
9904 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9905
John McCalldd4a3b02009-09-16 22:47:08 +00009906 // Try to convert the decl specifier to a type. This works for
9907 // friend templates because ActOnTag never produces a ClassTemplateDecl
9908 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009909 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009910 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9911 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009912 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009913 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009914
Douglas Gregor6ccab972010-12-16 01:14:37 +00009915 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9916 return 0;
9917
John McCalldd4a3b02009-09-16 22:47:08 +00009918 // This is definitely an error in C++98. It's probably meant to
9919 // be forbidden in C++0x, too, but the specification is just
9920 // poorly written.
9921 //
9922 // The problem is with declarations like the following:
9923 // template <T> friend A<T>::foo;
9924 // where deciding whether a class C is a friend or not now hinges
9925 // on whether there exists an instantiation of A that causes
9926 // 'foo' to equal C. There are restrictions on class-heads
9927 // (which we declare (by fiat) elaborated friend declarations to
9928 // be) that makes this tractable.
9929 //
9930 // FIXME: handle "template <> friend class A<T>;", which
9931 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009932 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009933 Diag(Loc, diag::err_tagless_friend_type_template)
9934 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009935 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009936 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009937
John McCall02cace72009-08-28 07:59:38 +00009938 // C++98 [class.friend]p1: A friend of a class is a function
9939 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009940 // This is fixed in DR77, which just barely didn't make the C++03
9941 // deadline. It's also a very silly restriction that seriously
9942 // affects inner classes and which nobody else seems to implement;
9943 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009944 //
9945 // But note that we could warn about it: it's always useless to
9946 // friend one of your own members (it's not, however, worthless to
9947 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009948
John McCalldd4a3b02009-09-16 22:47:08 +00009949 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009950 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009951 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009952 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009953 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009954 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009955 DS.getFriendSpecLoc());
9956 else
Abramo Bagnara0216df82011-10-29 20:52:52 +00009957 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +00009958
9959 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009960 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009961
John McCalldd4a3b02009-09-16 22:47:08 +00009962 D->setAccess(AS_public);
9963 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009964
John McCalld226f652010-08-21 09:40:31 +00009965 return D;
John McCall02cace72009-08-28 07:59:38 +00009966}
9967
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009968Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +00009969 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009970 const DeclSpec &DS = D.getDeclSpec();
9971
9972 assert(DS.isFriendSpecified());
9973 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9974
9975 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009976 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +00009977
9978 // C++ [class.friend]p1
9979 // A friend of a class is a function or class....
9980 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009981 // It *doesn't* see through dependent types, which is correct
9982 // according to [temp.arg.type]p3:
9983 // If a declaration acquires a function type through a
9984 // type dependent on a template-parameter and this causes
9985 // a declaration that does not use the syntactic form of a
9986 // function declarator to have a function type, the program
9987 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009988 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +00009989 Diag(Loc, diag::err_unexpected_friend);
9990
9991 // It might be worthwhile to try to recover by creating an
9992 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009993 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009994 }
9995
9996 // C++ [namespace.memdef]p3
9997 // - If a friend declaration in a non-local class first declares a
9998 // class or function, the friend class or function is a member
9999 // of the innermost enclosing namespace.
10000 // - The name of the friend is not found by simple name lookup
10001 // until a matching declaration is provided in that namespace
10002 // scope (either before or after the class declaration granting
10003 // friendship).
10004 // - If a friend function is called, its name may be found by the
10005 // name lookup that considers functions from namespaces and
10006 // classes associated with the types of the function arguments.
10007 // - When looking for a prior declaration of a class or a function
10008 // declared as a friend, scopes outside the innermost enclosing
10009 // namespace scope are not considered.
10010
John McCall337ec3d2010-10-12 23:13:28 +000010011 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010012 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10013 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010014 assert(Name);
10015
Douglas Gregor6ccab972010-12-16 01:14:37 +000010016 // Check for unexpanded parameter packs.
10017 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10018 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10019 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10020 return 0;
10021
John McCall67d1a672009-08-06 02:15:43 +000010022 // The context we found the declaration in, or in which we should
10023 // create the declaration.
10024 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010025 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010026 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010027 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010028
John McCall337ec3d2010-10-12 23:13:28 +000010029 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010030
John McCall337ec3d2010-10-12 23:13:28 +000010031 // There are four cases here.
10032 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010033 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010034 // there as appropriate.
10035 // Recover from invalid scope qualifiers as if they just weren't there.
10036 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010037 // C++0x [namespace.memdef]p3:
10038 // If the name in a friend declaration is neither qualified nor
10039 // a template-id and the declaration is a function or an
10040 // elaborated-type-specifier, the lookup to determine whether
10041 // the entity has been previously declared shall not consider
10042 // any scopes outside the innermost enclosing namespace.
10043 // C++0x [class.friend]p11:
10044 // If a friend declaration appears in a local class and the name
10045 // specified is an unqualified name, a prior declaration is
10046 // looked up without considering scopes that are outside the
10047 // innermost enclosing non-class scope. For a friend function
10048 // declaration, if there is no prior declaration, the program is
10049 // ill-formed.
10050 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010051 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010052
John McCall29ae6e52010-10-13 05:45:15 +000010053 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010054 DC = CurContext;
10055 while (true) {
10056 // Skip class contexts. If someone can cite chapter and verse
10057 // for this behavior, that would be nice --- it's what GCC and
10058 // EDG do, and it seems like a reasonable intent, but the spec
10059 // really only says that checks for unqualified existing
10060 // declarations should stop at the nearest enclosing namespace,
10061 // not that they should only consider the nearest enclosing
10062 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010063 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010064 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010065
John McCall68263142009-11-18 22:49:29 +000010066 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010067
10068 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010069 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010070 break;
John McCall29ae6e52010-10-13 05:45:15 +000010071
John McCall8a407372010-10-14 22:22:28 +000010072 if (isTemplateId) {
10073 if (isa<TranslationUnitDecl>(DC)) break;
10074 } else {
10075 if (DC->isFileContext()) break;
10076 }
John McCall67d1a672009-08-06 02:15:43 +000010077 DC = DC->getParent();
10078 }
10079
10080 // C++ [class.friend]p1: A friend of a class is a function or
10081 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010082 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010083 // Most C++ 98 compilers do seem to give an error here, so
10084 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010085 if (!Previous.empty() && DC->Equals(CurContext))
10086 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010087 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010088 diag::warn_cxx98_compat_friend_is_member :
10089 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010090
John McCall380aaa42010-10-13 06:22:15 +000010091 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010092
Douglas Gregor883af832011-10-10 01:11:59 +000010093 // C++ [class.friend]p6:
10094 // A function can be defined in a friend declaration of a class if and
10095 // only if the class is a non-local class (9.8), the function name is
10096 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010097 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010098 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10099 }
10100
John McCall337ec3d2010-10-12 23:13:28 +000010101 // - There's a non-dependent scope specifier, in which case we
10102 // compute it and do a previous lookup there for a function
10103 // or function template.
10104 } else if (!SS.getScopeRep()->isDependent()) {
10105 DC = computeDeclContext(SS);
10106 if (!DC) return 0;
10107
10108 if (RequireCompleteDeclContext(SS, DC)) return 0;
10109
10110 LookupQualifiedName(Previous, DC);
10111
10112 // Ignore things found implicitly in the wrong scope.
10113 // TODO: better diagnostics for this case. Suggesting the right
10114 // qualified scope would be nice...
10115 LookupResult::Filter F = Previous.makeFilter();
10116 while (F.hasNext()) {
10117 NamedDecl *D = F.next();
10118 if (!DC->InEnclosingNamespaceSetOf(
10119 D->getDeclContext()->getRedeclContext()))
10120 F.erase();
10121 }
10122 F.done();
10123
10124 if (Previous.empty()) {
10125 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010126 Diag(Loc, diag::err_qualified_friend_not_found)
10127 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010128 return 0;
10129 }
10130
10131 // C++ [class.friend]p1: A friend of a class is a function or
10132 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010133 if (DC->Equals(CurContext))
10134 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010135 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010136 diag::warn_cxx98_compat_friend_is_member :
10137 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010138
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010139 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010140 // C++ [class.friend]p6:
10141 // A function can be defined in a friend declaration of a class if and
10142 // only if the class is a non-local class (9.8), the function name is
10143 // unqualified, and the function has namespace scope.
10144 SemaDiagnosticBuilder DB
10145 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10146
10147 DB << SS.getScopeRep();
10148 if (DC->isFileContext())
10149 DB << FixItHint::CreateRemoval(SS.getRange());
10150 SS.clear();
10151 }
John McCall337ec3d2010-10-12 23:13:28 +000010152
10153 // - There's a scope specifier that does not match any template
10154 // parameter lists, in which case we use some arbitrary context,
10155 // create a method or method template, and wait for instantiation.
10156 // - There's a scope specifier that does match some template
10157 // parameter lists, which we don't handle right now.
10158 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010159 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010160 // C++ [class.friend]p6:
10161 // A function can be defined in a friend declaration of a class if and
10162 // only if the class is a non-local class (9.8), the function name is
10163 // unqualified, and the function has namespace scope.
10164 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10165 << SS.getScopeRep();
10166 }
10167
John McCall337ec3d2010-10-12 23:13:28 +000010168 DC = CurContext;
10169 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010170 }
Douglas Gregor883af832011-10-10 01:11:59 +000010171
John McCall29ae6e52010-10-13 05:45:15 +000010172 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010173 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010174 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10175 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10176 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010177 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010178 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10179 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010180 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010181 }
John McCall67d1a672009-08-06 02:15:43 +000010182 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010183
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010184 // FIXME: This is an egregious hack to cope with cases where the scope stack
10185 // does not contain the declaration context, i.e., in an out-of-line
10186 // definition of a class.
10187 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10188 if (!DCScope) {
10189 FakeDCScope.setEntity(DC);
10190 DCScope = &FakeDCScope;
10191 }
10192
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010193 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010194 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10195 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010196 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010197
Douglas Gregor182ddf02009-09-28 00:08:27 +000010198 assert(ND->getDeclContext() == DC);
10199 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010200
John McCallab88d972009-08-31 22:39:49 +000010201 // Add the function declaration to the appropriate lookup tables,
10202 // adjusting the redeclarations list as necessary. We don't
10203 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010204 //
John McCallab88d972009-08-31 22:39:49 +000010205 // Also update the scope-based lookup if the target context's
10206 // lookup context is in lexical scope.
10207 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010208 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010209 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010210 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010211 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010212 }
John McCall02cace72009-08-28 07:59:38 +000010213
10214 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010215 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010216 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010217 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010218 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010219
John McCall337ec3d2010-10-12 23:13:28 +000010220 if (ND->isInvalidDecl())
10221 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010222 else {
10223 FunctionDecl *FD;
10224 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10225 FD = FTD->getTemplatedDecl();
10226 else
10227 FD = cast<FunctionDecl>(ND);
10228
10229 // Mark templated-scope function declarations as unsupported.
10230 if (FD->getNumTemplateParameterLists())
10231 FrD->setUnsupportedFriend(true);
10232 }
John McCall337ec3d2010-10-12 23:13:28 +000010233
John McCalld226f652010-08-21 09:40:31 +000010234 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010235}
10236
John McCalld226f652010-08-21 09:40:31 +000010237void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10238 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010239
Sebastian Redl50de12f2009-03-24 22:27:57 +000010240 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10241 if (!Fn) {
10242 Diag(DelLoc, diag::err_deleted_non_function);
10243 return;
10244 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010245 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010246 Diag(DelLoc, diag::err_deleted_decl_not_first);
10247 Diag(Prev->getLocation(), diag::note_previous_declaration);
10248 // If the declaration wasn't the first, we delete the function anyway for
10249 // recovery.
10250 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010251 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010252
10253 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10254 if (!MD)
10255 return;
10256
10257 // A deleted special member function is trivial if the corresponding
10258 // implicitly-declared function would have been.
10259 switch (getSpecialMember(MD)) {
10260 case CXXInvalid:
10261 break;
10262 case CXXDefaultConstructor:
10263 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10264 break;
10265 case CXXCopyConstructor:
10266 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10267 break;
10268 case CXXMoveConstructor:
10269 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10270 break;
10271 case CXXCopyAssignment:
10272 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10273 break;
10274 case CXXMoveAssignment:
10275 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10276 break;
10277 case CXXDestructor:
10278 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10279 break;
10280 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010281}
Sebastian Redl13e88542009-04-27 21:33:24 +000010282
Sean Hunte4246a62011-05-12 06:15:49 +000010283void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10284 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10285
10286 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010287 if (MD->getParent()->isDependentType()) {
10288 MD->setDefaulted();
10289 MD->setExplicitlyDefaulted();
10290 return;
10291 }
10292
Sean Hunte4246a62011-05-12 06:15:49 +000010293 CXXSpecialMember Member = getSpecialMember(MD);
10294 if (Member == CXXInvalid) {
10295 Diag(DefaultLoc, diag::err_default_special_members);
10296 return;
10297 }
10298
10299 MD->setDefaulted();
10300 MD->setExplicitlyDefaulted();
10301
Sean Huntcd10dec2011-05-23 23:14:04 +000010302 // If this definition appears within the record, do the checking when
10303 // the record is complete.
10304 const FunctionDecl *Primary = MD;
10305 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10306 // Find the uninstantiated declaration that actually had the '= default'
10307 // on it.
10308 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10309
10310 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010311 return;
10312
10313 switch (Member) {
10314 case CXXDefaultConstructor: {
10315 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10316 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010317 if (!CD->isInvalidDecl())
10318 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10319 break;
10320 }
10321
10322 case CXXCopyConstructor: {
10323 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10324 CheckExplicitlyDefaultedCopyConstructor(CD);
10325 if (!CD->isInvalidDecl())
10326 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010327 break;
10328 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010329
Sean Hunt2b188082011-05-14 05:23:28 +000010330 case CXXCopyAssignment: {
10331 CheckExplicitlyDefaultedCopyAssignment(MD);
10332 if (!MD->isInvalidDecl())
10333 DefineImplicitCopyAssignment(DefaultLoc, MD);
10334 break;
10335 }
10336
Sean Huntcb45a0f2011-05-12 22:46:25 +000010337 case CXXDestructor: {
10338 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10339 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010340 if (!DD->isInvalidDecl())
10341 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010342 break;
10343 }
10344
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010345 case CXXMoveConstructor: {
10346 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10347 CheckExplicitlyDefaultedMoveConstructor(CD);
10348 if (!CD->isInvalidDecl())
10349 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010350 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010351 }
Sean Hunt82713172011-05-25 23:16:36 +000010352
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010353 case CXXMoveAssignment: {
10354 CheckExplicitlyDefaultedMoveAssignment(MD);
10355 if (!MD->isInvalidDecl())
10356 DefineImplicitMoveAssignment(DefaultLoc, MD);
10357 break;
10358 }
10359
10360 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010361 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010362 }
10363 } else {
10364 Diag(DefaultLoc, diag::err_default_special_members);
10365 }
10366}
10367
Sebastian Redl13e88542009-04-27 21:33:24 +000010368static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010369 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010370 Stmt *SubStmt = *CI;
10371 if (!SubStmt)
10372 continue;
10373 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010374 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010375 diag::err_return_in_constructor_handler);
10376 if (!isa<Expr>(SubStmt))
10377 SearchForReturnInStmt(Self, SubStmt);
10378 }
10379}
10380
10381void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10382 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10383 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10384 SearchForReturnInStmt(*this, Handler);
10385 }
10386}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010387
Mike Stump1eb44332009-09-09 15:08:12 +000010388bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010389 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010390 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10391 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010392
Chandler Carruth73857792010-02-15 11:53:20 +000010393 if (Context.hasSameType(NewTy, OldTy) ||
10394 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010395 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010396
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010397 // Check if the return types are covariant
10398 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010399
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010400 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010401 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10402 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010403 NewClassTy = NewPT->getPointeeType();
10404 OldClassTy = OldPT->getPointeeType();
10405 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010406 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10407 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10408 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10409 NewClassTy = NewRT->getPointeeType();
10410 OldClassTy = OldRT->getPointeeType();
10411 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010412 }
10413 }
Mike Stump1eb44332009-09-09 15:08:12 +000010414
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010415 // The return types aren't either both pointers or references to a class type.
10416 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010417 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010418 diag::err_different_return_type_for_overriding_virtual_function)
10419 << New->getDeclName() << NewTy << OldTy;
10420 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010421
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010422 return true;
10423 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010424
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010425 // C++ [class.virtual]p6:
10426 // If the return type of D::f differs from the return type of B::f, the
10427 // class type in the return type of D::f shall be complete at the point of
10428 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010429 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10430 if (!RT->isBeingDefined() &&
10431 RequireCompleteType(New->getLocation(), NewClassTy,
10432 PDiag(diag::err_covariant_return_incomplete)
10433 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010434 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010435 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010436
Douglas Gregora4923eb2009-11-16 21:35:15 +000010437 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010438 // Check if the new class derives from the old class.
10439 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10440 Diag(New->getLocation(),
10441 diag::err_covariant_return_not_derived)
10442 << New->getDeclName() << NewTy << OldTy;
10443 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10444 return true;
10445 }
Mike Stump1eb44332009-09-09 15:08:12 +000010446
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010447 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010448 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010449 diag::err_covariant_return_inaccessible_base,
10450 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10451 // FIXME: Should this point to the return type?
10452 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010453 // FIXME: this note won't trigger for delayed access control
10454 // diagnostics, and it's impossible to get an undelayed error
10455 // here from access control during the original parse because
10456 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010457 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10458 return true;
10459 }
10460 }
Mike Stump1eb44332009-09-09 15:08:12 +000010461
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010462 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010463 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010464 Diag(New->getLocation(),
10465 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010466 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010467 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10468 return true;
10469 };
Mike Stump1eb44332009-09-09 15:08:12 +000010470
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010471
10472 // The new class type must have the same or less qualifiers as the old type.
10473 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10474 Diag(New->getLocation(),
10475 diag::err_covariant_return_type_class_type_more_qualified)
10476 << New->getDeclName() << NewTy << OldTy;
10477 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10478 return true;
10479 };
Mike Stump1eb44332009-09-09 15:08:12 +000010480
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010481 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010482}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010483
Douglas Gregor4ba31362009-12-01 17:24:26 +000010484/// \brief Mark the given method pure.
10485///
10486/// \param Method the method to be marked pure.
10487///
10488/// \param InitRange the source range that covers the "0" initializer.
10489bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010490 SourceLocation EndLoc = InitRange.getEnd();
10491 if (EndLoc.isValid())
10492 Method->setRangeEnd(EndLoc);
10493
Douglas Gregor4ba31362009-12-01 17:24:26 +000010494 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10495 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010496 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010497 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010498
10499 if (!Method->isInvalidDecl())
10500 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10501 << Method->getDeclName() << InitRange;
10502 return true;
10503}
10504
Douglas Gregor552e2992012-02-21 02:22:07 +000010505/// \brief Determine whether the given declaration is a static data member.
10506static bool isStaticDataMember(Decl *D) {
10507 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10508 if (!Var)
10509 return false;
10510
10511 return Var->isStaticDataMember();
10512}
John McCall731ad842009-12-19 09:28:58 +000010513/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10514/// an initializer for the out-of-line declaration 'Dcl'. The scope
10515/// is a fresh scope pushed for just this purpose.
10516///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010517/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10518/// static data member of class X, names should be looked up in the scope of
10519/// class X.
John McCalld226f652010-08-21 09:40:31 +000010520void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010521 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010522 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010523
John McCall731ad842009-12-19 09:28:58 +000010524 // We should only get called for declarations with scope specifiers, like:
10525 // int foo::bar;
10526 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010527 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010528
10529 // If we are parsing the initializer for a static data member, push a
10530 // new expression evaluation context that is associated with this static
10531 // data member.
10532 if (isStaticDataMember(D))
10533 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010534}
10535
10536/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010537/// initializer for the out-of-line declaration 'D'.
10538void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010539 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010540 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010541
Douglas Gregor552e2992012-02-21 02:22:07 +000010542 if (isStaticDataMember(D))
10543 PopExpressionEvaluationContext();
10544
John McCall731ad842009-12-19 09:28:58 +000010545 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010546 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010547}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010548
10549/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10550/// C++ if/switch/while/for statement.
10551/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010552DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010553 // C++ 6.4p2:
10554 // The declarator shall not specify a function or an array.
10555 // The type-specifier-seq shall not contain typedef and shall not declare a
10556 // new class or enumeration.
10557 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10558 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010559
10560 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010561 if (!Dcl)
10562 return true;
10563
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010564 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10565 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010566 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010567 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010568 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010569
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010570 return Dcl;
10571}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010572
Douglas Gregordfe65432011-07-28 19:11:31 +000010573void Sema::LoadExternalVTableUses() {
10574 if (!ExternalSource)
10575 return;
10576
10577 SmallVector<ExternalVTableUse, 4> VTables;
10578 ExternalSource->ReadUsedVTables(VTables);
10579 SmallVector<VTableUse, 4> NewUses;
10580 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10581 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10582 = VTablesUsed.find(VTables[I].Record);
10583 // Even if a definition wasn't required before, it may be required now.
10584 if (Pos != VTablesUsed.end()) {
10585 if (!Pos->second && VTables[I].DefinitionRequired)
10586 Pos->second = true;
10587 continue;
10588 }
10589
10590 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10591 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10592 }
10593
10594 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10595}
10596
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010597void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10598 bool DefinitionRequired) {
10599 // Ignore any vtable uses in unevaluated operands or for classes that do
10600 // not have a vtable.
10601 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10602 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010603 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010604 return;
10605
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010606 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010607 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010608 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10609 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10610 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10611 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010612 // If we already had an entry, check to see if we are promoting this vtable
10613 // to required a definition. If so, we need to reappend to the VTableUses
10614 // list, since we may have already processed the first entry.
10615 if (DefinitionRequired && !Pos.first->second) {
10616 Pos.first->second = true;
10617 } else {
10618 // Otherwise, we can early exit.
10619 return;
10620 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010621 }
10622
10623 // Local classes need to have their virtual members marked
10624 // immediately. For all other classes, we mark their virtual members
10625 // at the end of the translation unit.
10626 if (Class->isLocalClass())
10627 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010628 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010629 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010630}
10631
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010632bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010633 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010634 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010635 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010636
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010637 // Note: The VTableUses vector could grow as a result of marking
10638 // the members of a class as "used", so we check the size each
10639 // time through the loop and prefer indices (with are stable) to
10640 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010641 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010642 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010643 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010644 if (!Class)
10645 continue;
10646
10647 SourceLocation Loc = VTableUses[I].second;
10648
10649 // If this class has a key function, but that key function is
10650 // defined in another translation unit, we don't need to emit the
10651 // vtable even though we're using it.
10652 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010653 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010654 switch (KeyFunction->getTemplateSpecializationKind()) {
10655 case TSK_Undeclared:
10656 case TSK_ExplicitSpecialization:
10657 case TSK_ExplicitInstantiationDeclaration:
10658 // The key function is in another translation unit.
10659 continue;
10660
10661 case TSK_ExplicitInstantiationDefinition:
10662 case TSK_ImplicitInstantiation:
10663 // We will be instantiating the key function.
10664 break;
10665 }
10666 } else if (!KeyFunction) {
10667 // If we have a class with no key function that is the subject
10668 // of an explicit instantiation declaration, suppress the
10669 // vtable; it will live with the explicit instantiation
10670 // definition.
10671 bool IsExplicitInstantiationDeclaration
10672 = Class->getTemplateSpecializationKind()
10673 == TSK_ExplicitInstantiationDeclaration;
10674 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10675 REnd = Class->redecls_end();
10676 R != REnd; ++R) {
10677 TemplateSpecializationKind TSK
10678 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10679 if (TSK == TSK_ExplicitInstantiationDeclaration)
10680 IsExplicitInstantiationDeclaration = true;
10681 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10682 IsExplicitInstantiationDeclaration = false;
10683 break;
10684 }
10685 }
10686
10687 if (IsExplicitInstantiationDeclaration)
10688 continue;
10689 }
10690
10691 // Mark all of the virtual members of this class as referenced, so
10692 // that we can build a vtable. Then, tell the AST consumer that a
10693 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010694 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010695 MarkVirtualMembersReferenced(Loc, Class);
10696 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10697 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10698
10699 // Optionally warn if we're emitting a weak vtable.
10700 if (Class->getLinkage() == ExternalLinkage &&
10701 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010702 const FunctionDecl *KeyFunctionDef = 0;
10703 if (!KeyFunction ||
10704 (KeyFunction->hasBody(KeyFunctionDef) &&
10705 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010706 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10707 TSK_ExplicitInstantiationDefinition
10708 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10709 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010710 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010711 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010712 VTableUses.clear();
10713
Douglas Gregor78844032011-04-22 22:25:37 +000010714 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010715}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010716
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010717void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10718 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010719 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10720 e = RD->method_end(); i != e; ++i) {
10721 CXXMethodDecl *MD = *i;
10722
10723 // C++ [basic.def.odr]p2:
10724 // [...] A virtual member function is used if it is not pure. [...]
10725 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010726 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010727 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010728
10729 // Only classes that have virtual bases need a VTT.
10730 if (RD->getNumVBases() == 0)
10731 return;
10732
10733 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10734 e = RD->bases_end(); i != e; ++i) {
10735 const CXXRecordDecl *Base =
10736 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010737 if (Base->getNumVBases() == 0)
10738 continue;
10739 MarkVirtualMembersReferenced(Loc, Base);
10740 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010741}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010742
10743/// SetIvarInitializers - This routine builds initialization ASTs for the
10744/// Objective-C implementation whose ivars need be initialized.
10745void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010746 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010747 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010748 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010749 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010750 CollectIvarsToConstructOrDestruct(OID, ivars);
10751 if (ivars.empty())
10752 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010753 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010754 for (unsigned i = 0; i < ivars.size(); i++) {
10755 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010756 if (Field->isInvalidDecl())
10757 continue;
10758
Sean Huntcbb67482011-01-08 20:30:50 +000010759 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010760 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10761 InitializationKind InitKind =
10762 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10763
10764 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010765 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010766 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010767 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010768 // Note, MemberInit could actually come back empty if no initialization
10769 // is required (e.g., because it would call a trivial default constructor)
10770 if (!MemberInit.get() || MemberInit.isInvalid())
10771 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010772
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010773 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010774 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10775 SourceLocation(),
10776 MemberInit.takeAs<Expr>(),
10777 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010778 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010779
10780 // Be sure that the destructor is accessible and is marked as referenced.
10781 if (const RecordType *RecordTy
10782 = Context.getBaseElementType(Field->getType())
10783 ->getAs<RecordType>()) {
10784 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010785 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010786 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010787 CheckDestructorAccess(Field->getLocation(), Destructor,
10788 PDiag(diag::err_access_dtor_ivar)
10789 << Context.getBaseElementType(Field->getType()));
10790 }
10791 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010792 }
10793 ObjCImplementation->setIvarInitializers(Context,
10794 AllToInit.data(), AllToInit.size());
10795 }
10796}
Sean Huntfe57eef2011-05-04 05:57:24 +000010797
Sean Huntebcbe1d2011-05-04 23:29:54 +000010798static
10799void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10800 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10801 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10802 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10803 Sema &S) {
10804 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10805 CE = Current.end();
10806 if (Ctor->isInvalidDecl())
10807 return;
10808
10809 const FunctionDecl *FNTarget = 0;
10810 CXXConstructorDecl *Target;
10811
10812 // We ignore the result here since if we don't have a body, Target will be
10813 // null below.
10814 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10815 Target
10816= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10817
10818 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10819 // Avoid dereferencing a null pointer here.
10820 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10821
10822 if (!Current.insert(Canonical))
10823 return;
10824
10825 // We know that beyond here, we aren't chaining into a cycle.
10826 if (!Target || !Target->isDelegatingConstructor() ||
10827 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10828 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10829 Valid.insert(*CI);
10830 Current.clear();
10831 // We've hit a cycle.
10832 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10833 Current.count(TCanonical)) {
10834 // If we haven't diagnosed this cycle yet, do so now.
10835 if (!Invalid.count(TCanonical)) {
10836 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010837 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010838 << Ctor;
10839
10840 // Don't add a note for a function delegating directo to itself.
10841 if (TCanonical != Canonical)
10842 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10843
10844 CXXConstructorDecl *C = Target;
10845 while (C->getCanonicalDecl() != Canonical) {
10846 (void)C->getTargetConstructor()->hasBody(FNTarget);
10847 assert(FNTarget && "Ctor cycle through bodiless function");
10848
10849 C
10850 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10851 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10852 }
10853 }
10854
10855 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10856 Invalid.insert(*CI);
10857 Current.clear();
10858 } else {
10859 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10860 }
10861}
10862
10863
Sean Huntfe57eef2011-05-04 05:57:24 +000010864void Sema::CheckDelegatingCtorCycles() {
10865 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10866
Sean Huntebcbe1d2011-05-04 23:29:54 +000010867 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10868 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010869
Douglas Gregor0129b562011-07-27 21:57:17 +000010870 for (DelegatingCtorDeclsType::iterator
10871 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010872 E = DelegatingCtorDecls.end();
10873 I != E; ++I) {
10874 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010875 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010876
10877 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10878 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010879}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010880
10881/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10882Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10883 // Implicitly declared functions (e.g. copy constructors) are
10884 // __host__ __device__
10885 if (D->isImplicit())
10886 return CFT_HostDevice;
10887
10888 if (D->hasAttr<CUDAGlobalAttr>())
10889 return CFT_Global;
10890
10891 if (D->hasAttr<CUDADeviceAttr>()) {
10892 if (D->hasAttr<CUDAHostAttr>())
10893 return CFT_HostDevice;
10894 else
10895 return CFT_Device;
10896 }
10897
10898 return CFT_Host;
10899}
10900
10901bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10902 CUDAFunctionTarget CalleeTarget) {
10903 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10904 // Callable from the device only."
10905 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10906 return true;
10907
10908 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10909 // Callable from the host only."
10910 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10911 // Callable from the host only."
10912 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10913 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10914 return true;
10915
10916 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10917 return true;
10918
10919 return false;
10920}