blob: 29df5c12a60d96285cb712373caa4cf1801c1fb0 [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++
283 if (!getLangOptions().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.
375bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
376 bool Invalid = false;
377
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000379 // For non-template functions, default arguments can be added in
380 // later declarations of a function in the same
381 // scope. Declarations in different scopes have completely
382 // distinct sets of default arguments. That is, declarations in
383 // inner scopes do not acquire default arguments from
384 // declarations in outer scopes, and vice versa. In a given
385 // function declaration, all parameters subsequent to a
386 // parameter with a default argument shall have default
387 // arguments supplied in this or previous declarations. A
388 // default argument shall not be redefined by a later
389 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000390 //
391 // C++ [dcl.fct.default]p6:
392 // Except for member functions of class templates, the default arguments
393 // in a member function definition that appears outside of the class
394 // definition are added to the set of default arguments provided by the
395 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
397 ParmVarDecl *OldParam = Old->getParamDecl(p);
398 ParmVarDecl *NewParam = New->getParamDecl(p);
399
Douglas Gregor6cc15182009-09-11 18:44:32 +0000400 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000401
Francois Pichet8d051e02011-04-10 03:03:52 +0000402 unsigned DiagDefaultParamID =
403 diag::err_param_default_argument_redefinition;
404
405 // MSVC accepts that default parameters be redefined for member functions
406 // of template class. The new default parameter's value is ignored.
407 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000408 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000409 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
410 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000411 // Merge the old default argument into the new parameter.
412 NewParam->setHasInheritedDefaultArg();
413 if (OldParam->hasUninstantiatedDefaultArg())
414 NewParam->setUninstantiatedDefaultArg(
415 OldParam->getUninstantiatedDefaultArg());
416 else
417 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000418 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000419 Invalid = false;
420 }
421 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000422
Francois Pichet8cf90492011-04-10 04:58:30 +0000423 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
424 // hint here. Alternatively, we could walk the type-source information
425 // for NewParam to find the last source location in the type... but it
426 // isn't worth the effort right now. This is the kind of test case that
427 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000428 // int f(int);
429 // void g(int (*fp)(int) = f);
430 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000431 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000432 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000433
434 // Look for the function declaration where the default argument was
435 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000436 for (FunctionDecl *Older = Old->getPreviousDecl();
437 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000438 if (!Older->getParamDecl(p)->hasDefaultArg())
439 break;
440
441 OldParam = Older->getParamDecl(p);
442 }
443
444 Diag(OldParam->getLocation(), diag::note_previous_definition)
445 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000446 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000447 // Merge the old default argument into the new parameter.
448 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000449 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000450 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000451 if (OldParam->hasUninstantiatedDefaultArg())
452 NewParam->setUninstantiatedDefaultArg(
453 OldParam->getUninstantiatedDefaultArg());
454 else
John McCall3d6c1782010-05-04 01:53:42 +0000455 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000456 } else if (NewParam->hasDefaultArg()) {
457 if (New->getDescribedFunctionTemplate()) {
458 // Paragraph 4, quoted above, only applies to non-template functions.
459 Diag(NewParam->getLocation(),
460 diag::err_param_default_argument_template_redecl)
461 << NewParam->getDefaultArgRange();
462 Diag(Old->getLocation(), diag::note_template_prev_declaration)
463 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000464 } else if (New->getTemplateSpecializationKind()
465 != TSK_ImplicitInstantiation &&
466 New->getTemplateSpecializationKind() != TSK_Undeclared) {
467 // C++ [temp.expr.spec]p21:
468 // Default function arguments shall not be specified in a declaration
469 // or a definition for one of the following explicit specializations:
470 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000471 // - the explicit specialization of a member function template;
472 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000473 // template where the class template specialization to which the
474 // member function specialization belongs is implicitly
475 // instantiated.
476 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
477 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
478 << New->getDeclName()
479 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000480 } else if (New->getDeclContext()->isDependentContext()) {
481 // C++ [dcl.fct.default]p6 (DR217):
482 // Default arguments for a member function of a class template shall
483 // be specified on the initial declaration of the member function
484 // within the class template.
485 //
486 // Reading the tea leaves a bit in DR217 and its reference to DR205
487 // leads me to the conclusion that one cannot add default function
488 // arguments for an out-of-line definition of a member function of a
489 // dependent type.
490 int WhichKind = 2;
491 if (CXXRecordDecl *Record
492 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
493 if (Record->getDescribedClassTemplate())
494 WhichKind = 0;
495 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
496 WhichKind = 1;
497 else
498 WhichKind = 2;
499 }
500
501 Diag(NewParam->getLocation(),
502 diag::err_param_default_argument_member_template_redecl)
503 << WhichKind
504 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000505 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
506 CXXSpecialMember NewSM = getSpecialMember(Ctor),
507 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
508 if (NewSM != OldSM) {
509 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
510 << NewParam->getDefaultArgRange() << NewSM;
511 Diag(Old->getLocation(), diag::note_previous_declaration_special)
512 << OldSM;
513 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000515 }
516 }
517
Richard Smithff234882012-02-20 23:28:05 +0000518 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000519 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000520 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000521 if (New->isConstexpr() != Old->isConstexpr()) {
522 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
523 << New << New->isConstexpr();
524 Diag(Old->getLocation(), diag::note_previous_declaration);
525 Invalid = true;
526 }
527
Douglas Gregore13ad832010-02-12 07:32:17 +0000528 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000529 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000530
Douglas Gregorcda9c672009-02-16 17:45:42 +0000531 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000532}
533
Sebastian Redl60618fa2011-03-12 11:50:43 +0000534/// \brief Merge the exception specifications of two variable declarations.
535///
536/// This is called when there's a redeclaration of a VarDecl. The function
537/// checks if the redeclaration might have an exception specification and
538/// validates compatibility and merges the specs if necessary.
539void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
540 // Shortcut if exceptions are disabled.
541 if (!getLangOptions().CXXExceptions)
542 return;
543
544 assert(Context.hasSameType(New->getType(), Old->getType()) &&
545 "Should only be called if types are otherwise the same.");
546
547 QualType NewType = New->getType();
548 QualType OldType = Old->getType();
549
550 // We're only interested in pointers and references to functions, as well
551 // as pointers to member functions.
552 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
553 NewType = R->getPointeeType();
554 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
555 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
556 NewType = P->getPointeeType();
557 OldType = OldType->getAs<PointerType>()->getPointeeType();
558 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
559 NewType = M->getPointeeType();
560 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
561 }
562
563 if (!NewType->isFunctionProtoType())
564 return;
565
566 // There's lots of special cases for functions. For function pointers, system
567 // libraries are hopefully not as broken so that we don't need these
568 // workarounds.
569 if (CheckEquivalentExceptionSpec(
570 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
571 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
572 New->setInvalidDecl();
573 }
574}
575
Chris Lattner3d1cee32008-04-08 05:04:30 +0000576/// CheckCXXDefaultArguments - Verify that the default arguments for a
577/// function declaration are well-formed according to C++
578/// [dcl.fct.default].
579void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
580 unsigned NumParams = FD->getNumParams();
581 unsigned p;
582
Douglas Gregorc6889e72012-02-14 22:28:59 +0000583 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
584 isa<CXXMethodDecl>(FD) &&
585 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 // Find first parameter with a default argument
588 for (p = 0; p < NumParams; ++p) {
589 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000590 if (Param->hasDefaultArg()) {
591 // C++11 [expr.prim.lambda]p5:
592 // [...] Default arguments (8.3.6) shall not be specified in the
593 // parameter-declaration-clause of a lambda-declarator.
594 //
595 // FIXME: Core issue 974 strikes this sentence, we only provide an
596 // extension warning.
597 if (IsLambda)
598 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
599 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000600 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000601 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 }
603
604 // C++ [dcl.fct.default]p4:
605 // In a given function declaration, all parameters
606 // subsequent to a parameter with a default argument shall
607 // have default arguments supplied in this or previous
608 // declarations. A default argument shall not be redefined
609 // by a later declaration (not even to the same value).
610 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000611 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000612 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000613 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000614 if (Param->isInvalidDecl())
615 /* We already complained about this parameter. */;
616 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000617 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000618 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000619 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000620 else
Mike Stump1eb44332009-09-09 15:08:12 +0000621 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000622 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner3d1cee32008-04-08 05:04:30 +0000624 LastMissingDefaultArg = p;
625 }
626 }
627
628 if (LastMissingDefaultArg > 0) {
629 // Some default arguments were missing. Clear out all of the
630 // default arguments up to (and including) the last missing
631 // default argument, so that we leave the function parameters
632 // in a semantically valid state.
633 for (p = 0; p <= LastMissingDefaultArg; ++p) {
634 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000635 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 Param->setDefaultArg(0);
637 }
638 }
639 }
640}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000641
Richard Smith9f569cc2011-10-01 02:31:28 +0000642// CheckConstexprParameterTypes - Check whether a function's parameter types
643// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000644// diagnostic and return false.
645static bool CheckConstexprParameterTypes(Sema &SemaRef,
646 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000647 unsigned ArgIndex = 0;
648 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
649 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
650 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
651 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
652 SourceLocation ParamLoc = PD->getLocation();
653 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000654 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smith9f569cc2011-10-01 02:31:28 +0000655 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
656 << ArgIndex+1 << PD->getSourceRange()
Richard Smith86c3ae42012-02-13 03:54:03 +0000657 << isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000658 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000659 }
660 return true;
661}
662
663// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000664// the requirements of a constexpr function definition or a constexpr
665// constructor definition. If so, return true. If not, produce appropriate
666// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000667//
Richard Smith86c3ae42012-02-13 03:54:03 +0000668// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
669bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000670 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
671 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000672 // C++11 [dcl.constexpr]p4:
673 // The definition of a constexpr constructor shall satisfy the following
674 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000675 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000676 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000677 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000678 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
679 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
680 << RD->getNumVBases();
681 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
682 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000683 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000684 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000685 return false;
686 }
Richard Smith35340502012-01-13 04:54:00 +0000687 }
688
689 if (!isa<CXXConstructorDecl>(NewFD)) {
690 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000691 // The definition of a constexpr function shall satisfy the following
692 // constraints:
693 // - it shall not be virtual;
694 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
695 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000696 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000697
Richard Smith86c3ae42012-02-13 03:54:03 +0000698 // If it's not obvious why this function is virtual, find an overridden
699 // function which uses the 'virtual' keyword.
700 const CXXMethodDecl *WrittenVirtual = Method;
701 while (!WrittenVirtual->isVirtualAsWritten())
702 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
703 if (WrittenVirtual != Method)
704 Diag(WrittenVirtual->getLocation(),
705 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000706 return false;
707 }
708
709 // - its return type shall be a literal type;
710 QualType RT = NewFD->getResultType();
711 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000712 RequireLiteralType(NewFD->getLocation(), RT,
713 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000714 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000715 }
716
Richard Smith35340502012-01-13 04:54:00 +0000717 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000718 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000719 return false;
720
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return true;
722}
723
724/// Check the given declaration statement is legal within a constexpr function
725/// body. C++0x [dcl.constexpr]p3,p4.
726///
727/// \return true if the body is OK, false if we have diagnosed a problem.
728static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
729 DeclStmt *DS) {
730 // C++0x [dcl.constexpr]p3 and p4:
731 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
732 // contain only
733 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
734 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
735 switch ((*DclIt)->getKind()) {
736 case Decl::StaticAssert:
737 case Decl::Using:
738 case Decl::UsingShadow:
739 case Decl::UsingDirective:
740 case Decl::UnresolvedUsingTypename:
741 // - static_assert-declarations
742 // - using-declarations,
743 // - using-directives,
744 continue;
745
746 case Decl::Typedef:
747 case Decl::TypeAlias: {
748 // - typedef declarations and alias-declarations that do not define
749 // classes or enumerations,
750 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
751 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
752 // Don't allow variably-modified types in constexpr functions.
753 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
754 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
755 << TL.getSourceRange() << TL.getType()
756 << isa<CXXConstructorDecl>(Dcl);
757 return false;
758 }
759 continue;
760 }
761
762 case Decl::Enum:
763 case Decl::CXXRecord:
764 // As an extension, we allow the declaration (but not the definition) of
765 // classes and enumerations in all declarations, not just in typedef and
766 // alias declarations.
767 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
768 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
769 << isa<CXXConstructorDecl>(Dcl);
770 return false;
771 }
772 continue;
773
774 case Decl::Var:
775 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
776 << isa<CXXConstructorDecl>(Dcl);
777 return false;
778
779 default:
780 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
781 << isa<CXXConstructorDecl>(Dcl);
782 return false;
783 }
784 }
785
786 return true;
787}
788
789/// Check that the given field is initialized within a constexpr constructor.
790///
791/// \param Dcl The constexpr constructor being checked.
792/// \param Field The field being checked. This may be a member of an anonymous
793/// struct or union nested within the class being checked.
794/// \param Inits All declarations, including anonymous struct/union members and
795/// indirect members, for which any initialization was provided.
796/// \param Diagnosed Set to true if an error is produced.
797static void CheckConstexprCtorInitializer(Sema &SemaRef,
798 const FunctionDecl *Dcl,
799 FieldDecl *Field,
800 llvm::SmallSet<Decl*, 16> &Inits,
801 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000802 if (Field->isUnnamedBitfield())
803 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000804
805 if (Field->isAnonymousStructOrUnion() &&
806 Field->getType()->getAsCXXRecordDecl()->isEmpty())
807 return;
808
Richard Smith9f569cc2011-10-01 02:31:28 +0000809 if (!Inits.count(Field)) {
810 if (!Diagnosed) {
811 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
812 Diagnosed = true;
813 }
814 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
815 } else if (Field->isAnonymousStructOrUnion()) {
816 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
817 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
818 I != E; ++I)
819 // If an anonymous union contains an anonymous struct of which any member
820 // is initialized, all members must be initialized.
821 if (!RD->isUnion() || Inits.count(*I))
822 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
823 }
824}
825
826/// Check the body for the given constexpr function declaration only contains
827/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
828///
829/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000830bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000831 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000832 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000833 // The definition of a constexpr function shall satisfy the following
834 // constraints: [...]
835 // - its function-body shall be = delete, = default, or a
836 // compound-statement
837 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000838 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 // In the definition of a constexpr constructor, [...]
840 // - its function-body shall not be a function-try-block;
841 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
842 << isa<CXXConstructorDecl>(Dcl);
843 return false;
844 }
845
846 // - its function-body shall be [...] a compound-statement that contains only
847 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
848
849 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
850 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
851 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
852 switch ((*BodyIt)->getStmtClass()) {
853 case Stmt::NullStmtClass:
854 // - null statements,
855 continue;
856
857 case Stmt::DeclStmtClass:
858 // - static_assert-declarations
859 // - using-declarations,
860 // - using-directives,
861 // - typedef declarations and alias-declarations that do not define
862 // classes or enumerations,
863 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
864 return false;
865 continue;
866
867 case Stmt::ReturnStmtClass:
868 // - and exactly one return statement;
869 if (isa<CXXConstructorDecl>(Dcl))
870 break;
871
872 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000873 continue;
874
875 default:
876 break;
877 }
878
879 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
880 << isa<CXXConstructorDecl>(Dcl);
881 return false;
882 }
883
884 if (const CXXConstructorDecl *Constructor
885 = dyn_cast<CXXConstructorDecl>(Dcl)) {
886 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000887 // DR1359:
888 // - every non-variant non-static data member and base class sub-object
889 // shall be initialized;
890 // - if the class is a non-empty union, or for each non-empty anonymous
891 // union member of a non-union class, exactly one non-static data member
892 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000893 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000894 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000895 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
896 return false;
897 }
Richard Smith6e433752011-10-10 16:38:04 +0000898 } else if (!Constructor->isDependentContext() &&
899 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000900 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
901
902 // Skip detailed checking if we have enough initializers, and we would
903 // allow at most one initializer per member.
904 bool AnyAnonStructUnionMembers = false;
905 unsigned Fields = 0;
906 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
907 E = RD->field_end(); I != E; ++I, ++Fields) {
908 if ((*I)->isAnonymousStructOrUnion()) {
909 AnyAnonStructUnionMembers = true;
910 break;
911 }
912 }
913 if (AnyAnonStructUnionMembers ||
914 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
915 // Check initialization of non-static data members. Base classes are
916 // always initialized so do not need to be checked. Dependent bases
917 // might not have initializers in the member initializer list.
918 llvm::SmallSet<Decl*, 16> Inits;
919 for (CXXConstructorDecl::init_const_iterator
920 I = Constructor->init_begin(), E = Constructor->init_end();
921 I != E; ++I) {
922 if (FieldDecl *FD = (*I)->getMember())
923 Inits.insert(FD);
924 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
925 Inits.insert(ID->chain_begin(), ID->chain_end());
926 }
927
928 bool Diagnosed = false;
929 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
930 E = RD->field_end(); I != E; ++I)
931 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
932 if (Diagnosed)
933 return false;
934 }
935 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000936 } else {
937 if (ReturnStmts.empty()) {
938 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
939 return false;
940 }
941 if (ReturnStmts.size() > 1) {
942 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
943 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
944 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
945 return false;
946 }
947 }
948
Richard Smith5ba73e12012-02-04 00:33:54 +0000949 // C++11 [dcl.constexpr]p5:
950 // if no function argument values exist such that the function invocation
951 // substitution would produce a constant expression, the program is
952 // ill-formed; no diagnostic required.
953 // C++11 [dcl.constexpr]p3:
954 // - every constructor call and implicit conversion used in initializing the
955 // return value shall be one of those allowed in a constant expression.
956 // C++11 [dcl.constexpr]p4:
957 // - every constructor involved in initializing non-static data members and
958 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000959 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000960 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000961 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
962 << isa<CXXConstructorDecl>(Dcl);
963 for (size_t I = 0, N = Diags.size(); I != N; ++I)
964 Diag(Diags[I].first, Diags[I].second);
965 return false;
966 }
967
Richard Smith9f569cc2011-10-01 02:31:28 +0000968 return true;
969}
970
Douglas Gregorb48fe382008-10-31 09:07:45 +0000971/// isCurrentClassName - Determine whether the identifier II is the
972/// name of the class type currently being defined. In the case of
973/// nested classes, this will only return true if II is the name of
974/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000975bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
976 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000977 assert(getLangOptions().CPlusPlus && "No class names in C!");
978
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000979 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000980 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000981 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000982 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
983 } else
984 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
985
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000986 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987 return &II == CurDecl->getIdentifier();
988 else
989 return false;
990}
991
Mike Stump1eb44332009-09-09 15:08:12 +0000992/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000993///
994/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
995/// and returns NULL otherwise.
996CXXBaseSpecifier *
997Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
998 SourceRange SpecifierRange,
999 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001000 TypeSourceInfo *TInfo,
1001 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001002 QualType BaseType = TInfo->getType();
1003
Douglas Gregor2943aed2009-03-03 04:44:36 +00001004 // C++ [class.union]p1:
1005 // A union shall not have base classes.
1006 if (Class->isUnion()) {
1007 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1008 << SpecifierRange;
1009 return 0;
1010 }
1011
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001012 if (EllipsisLoc.isValid() &&
1013 !TInfo->getType()->containsUnexpandedParameterPack()) {
1014 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1015 << TInfo->getTypeLoc().getSourceRange();
1016 EllipsisLoc = SourceLocation();
1017 }
1018
Douglas Gregor2943aed2009-03-03 04:44:36 +00001019 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001020 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001021 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001022 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001023
1024 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001025
1026 // Base specifiers must be record types.
1027 if (!BaseType->isRecordType()) {
1028 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1029 return 0;
1030 }
1031
1032 // C++ [class.union]p1:
1033 // A union shall not be used as a base class.
1034 if (BaseType->isUnionType()) {
1035 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1036 return 0;
1037 }
1038
1039 // C++ [class.derived]p2:
1040 // The class-name in a base-specifier shall not be an incompletely
1041 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001042 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001043 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001044 << SpecifierRange)) {
1045 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001046 return 0;
John McCall572fc622010-08-17 07:23:57 +00001047 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001048
Eli Friedman1d954f62009-08-15 21:55:26 +00001049 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001050 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001051 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001052 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001053 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001054 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1055 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001056
Anders Carlsson1d209272011-03-25 14:55:14 +00001057 // C++ [class]p3:
1058 // If a class is marked final and it appears as a base-type-specifier in
1059 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001060 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001061 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1062 << CXXBaseDecl->getDeclName();
1063 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1064 << CXXBaseDecl->getDeclName();
1065 return 0;
1066 }
1067
John McCall572fc622010-08-17 07:23:57 +00001068 if (BaseDecl->isInvalidDecl())
1069 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001070
1071 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001072 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001073 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001074 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001075}
1076
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001077/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1078/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001079/// example:
1080/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001081/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001082BaseResult
John McCalld226f652010-08-21 09:40:31 +00001083Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001084 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 ParsedType basetype, SourceLocation BaseLoc,
1086 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001087 if (!classdecl)
1088 return true;
1089
Douglas Gregor40808ce2009-03-09 23:48:35 +00001090 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001091 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001092 if (!Class)
1093 return true;
1094
Nick Lewycky56062202010-07-26 16:56:01 +00001095 TypeSourceInfo *TInfo = 0;
1096 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001097
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001098 if (EllipsisLoc.isInvalid() &&
1099 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001100 UPPC_BaseType))
1101 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001102
Douglas Gregor2943aed2009-03-03 04:44:36 +00001103 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001104 Virtual, Access, TInfo,
1105 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001106 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregor2943aed2009-03-03 04:44:36 +00001108 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001109}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001110
Douglas Gregor2943aed2009-03-03 04:44:36 +00001111/// \brief Performs the actual work of attaching the given base class
1112/// specifiers to a C++ class.
1113bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1114 unsigned NumBases) {
1115 if (NumBases == 0)
1116 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001117
1118 // Used to keep track of which base types we have already seen, so
1119 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001120 // that the key is always the unqualified canonical type of the base
1121 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001122 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1123
1124 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001125 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001126 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001127 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001128 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001129 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001130 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001131
1132 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1133 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001134 // C++ [class.mi]p3:
1135 // A class shall not be specified as a direct base class of a
1136 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001137 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001138 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001139 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141
1142 // Delete the duplicate base class specifier; we're going to
1143 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001144 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145
1146 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001147 } else {
1148 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001149 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001151 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001152 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1153 if (RD->hasAttr<WeakAttr>())
1154 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001155 }
1156 }
1157
1158 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001159 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001160
1161 // Delete the remaining (good) base class specifiers, since their
1162 // data has been copied into the CXXRecordDecl.
1163 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001164 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001165
1166 return Invalid;
1167}
1168
1169/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1170/// class, after checking whether there are any duplicate base
1171/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001172void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001173 unsigned NumBases) {
1174 if (!ClassDecl || !Bases || !NumBases)
1175 return;
1176
1177 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001178 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001180}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001181
John McCall3cb0ebd2010-03-10 03:28:59 +00001182static CXXRecordDecl *GetClassForType(QualType T) {
1183 if (const RecordType *RT = T->getAs<RecordType>())
1184 return cast<CXXRecordDecl>(RT->getDecl());
1185 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1186 return ICT->getDecl();
1187 else
1188 return 0;
1189}
1190
Douglas Gregora8f32e02009-10-06 17:59:45 +00001191/// \brief Determine whether the type \p Derived is a C++ class that is
1192/// derived from the type \p Base.
1193bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1194 if (!getLangOptions().CPlusPlus)
1195 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001196
1197 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1198 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001199 return false;
1200
John McCall3cb0ebd2010-03-10 03:28:59 +00001201 CXXRecordDecl *BaseRD = GetClassForType(Base);
1202 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001203 return false;
1204
John McCall86ff3082010-02-04 22:26:26 +00001205 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1206 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001207}
1208
1209/// \brief Determine whether the type \p Derived is a C++ class that is
1210/// derived from the type \p Base.
1211bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1212 if (!getLangOptions().CPlusPlus)
1213 return false;
1214
John McCall3cb0ebd2010-03-10 03:28:59 +00001215 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1216 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217 return false;
1218
John McCall3cb0ebd2010-03-10 03:28:59 +00001219 CXXRecordDecl *BaseRD = GetClassForType(Base);
1220 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221 return false;
1222
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1224}
1225
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001226void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001227 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001228 assert(BasePathArray.empty() && "Base path array must be empty!");
1229 assert(Paths.isRecordingPaths() && "Must record paths!");
1230
1231 const CXXBasePath &Path = Paths.front();
1232
1233 // We first go backward and check if we have a virtual base.
1234 // FIXME: It would be better if CXXBasePath had the base specifier for
1235 // the nearest virtual base.
1236 unsigned Start = 0;
1237 for (unsigned I = Path.size(); I != 0; --I) {
1238 if (Path[I - 1].Base->isVirtual()) {
1239 Start = I - 1;
1240 break;
1241 }
1242 }
1243
1244 // Now add all bases.
1245 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001246 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001247}
1248
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001249/// \brief Determine whether the given base path includes a virtual
1250/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001251bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1252 for (CXXCastPath::const_iterator B = BasePath.begin(),
1253 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001254 B != BEnd; ++B)
1255 if ((*B)->isVirtual())
1256 return true;
1257
1258 return false;
1259}
1260
Douglas Gregora8f32e02009-10-06 17:59:45 +00001261/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1262/// conversion (where Derived and Base are class types) is
1263/// well-formed, meaning that the conversion is unambiguous (and
1264/// that all of the base classes are accessible). Returns true
1265/// and emits a diagnostic if the code is ill-formed, returns false
1266/// otherwise. Loc is the location where this routine should point to
1267/// if there is an error, and Range is the source range to highlight
1268/// if there is an error.
1269bool
1270Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001271 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001272 unsigned AmbigiousBaseConvID,
1273 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001274 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001275 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001276 // First, determine whether the path from Derived to Base is
1277 // ambiguous. This is slightly more expensive than checking whether
1278 // the Derived to Base conversion exists, because here we need to
1279 // explore multiple paths to determine if there is an ambiguity.
1280 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1281 /*DetectVirtual=*/false);
1282 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1283 assert(DerivationOkay &&
1284 "Can only be used with a derived-to-base conversion");
1285 (void)DerivationOkay;
1286
1287 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001288 if (InaccessibleBaseID) {
1289 // Check that the base class can be accessed.
1290 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1291 InaccessibleBaseID)) {
1292 case AR_inaccessible:
1293 return true;
1294 case AR_accessible:
1295 case AR_dependent:
1296 case AR_delayed:
1297 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001298 }
John McCall6b2accb2010-02-10 09:31:12 +00001299 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001300
1301 // Build a base path if necessary.
1302 if (BasePath)
1303 BuildBasePathArray(Paths, *BasePath);
1304 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001305 }
1306
1307 // We know that the derived-to-base conversion is ambiguous, and
1308 // we're going to produce a diagnostic. Perform the derived-to-base
1309 // search just one more time to compute all of the possible paths so
1310 // that we can print them out. This is more expensive than any of
1311 // the previous derived-to-base checks we've done, but at this point
1312 // performance isn't as much of an issue.
1313 Paths.clear();
1314 Paths.setRecordingPaths(true);
1315 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1316 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1317 (void)StillOkay;
1318
1319 // Build up a textual representation of the ambiguous paths, e.g.,
1320 // D -> B -> A, that will be used to illustrate the ambiguous
1321 // conversions in the diagnostic. We only print one of the paths
1322 // to each base class subobject.
1323 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1324
1325 Diag(Loc, AmbigiousBaseConvID)
1326 << Derived << Base << PathDisplayStr << Range << Name;
1327 return true;
1328}
1329
1330bool
1331Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001332 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001333 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001334 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001336 IgnoreAccess ? 0
1337 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001338 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001339 Loc, Range, DeclarationName(),
1340 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001341}
1342
1343
1344/// @brief Builds a string representing ambiguous paths from a
1345/// specific derived class to different subobjects of the same base
1346/// class.
1347///
1348/// This function builds a string that can be used in error messages
1349/// to show the different paths that one can take through the
1350/// inheritance hierarchy to go from the derived class to different
1351/// subobjects of a base class. The result looks something like this:
1352/// @code
1353/// struct D -> struct B -> struct A
1354/// struct D -> struct C -> struct A
1355/// @endcode
1356std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1357 std::string PathDisplayStr;
1358 std::set<unsigned> DisplayedPaths;
1359 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1360 Path != Paths.end(); ++Path) {
1361 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1362 // We haven't displayed a path to this particular base
1363 // class subobject yet.
1364 PathDisplayStr += "\n ";
1365 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1366 for (CXXBasePath::const_iterator Element = Path->begin();
1367 Element != Path->end(); ++Element)
1368 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1369 }
1370 }
1371
1372 return PathDisplayStr;
1373}
1374
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001375//===----------------------------------------------------------------------===//
1376// C++ class member Handling
1377//===----------------------------------------------------------------------===//
1378
Abramo Bagnara6206d532010-06-05 05:09:32 +00001379/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001380bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1381 SourceLocation ASLoc,
1382 SourceLocation ColonLoc,
1383 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001384 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001385 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001386 ASLoc, ColonLoc);
1387 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001388 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001389}
1390
Anders Carlsson9e682d92011-01-20 05:57:14 +00001391/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001392void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001393 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001394 if (!MD || !MD->isVirtual())
1395 return;
1396
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001397 if (MD->isDependentContext())
1398 return;
1399
Anders Carlsson9e682d92011-01-20 05:57:14 +00001400 // C++0x [class.virtual]p3:
1401 // If a virtual function is marked with the virt-specifier override and does
1402 // not override a member function of a base class,
1403 // the program is ill-formed.
1404 bool HasOverriddenMethods =
1405 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001406 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001407 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001408 diag::err_function_marked_override_not_overriding)
1409 << MD->getDeclName();
1410 return;
1411 }
1412}
1413
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001414/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1415/// function overrides a virtual member function marked 'final', according to
1416/// C++0x [class.virtual]p3.
1417bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1418 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001419 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001420 return false;
1421
1422 Diag(New->getLocation(), diag::err_final_function_overridden)
1423 << New->getDeclName();
1424 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1425 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001426}
1427
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001428/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1429/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001430/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1431/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1432/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001433Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001434Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001435 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001436 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001437 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001438 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001439 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1440 DeclarationName Name = NameInfo.getName();
1441 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001442
1443 // For anonymous bitfields, the location should point to the type.
1444 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001445 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001446
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001447 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448
John McCall4bde1e12010-06-04 08:34:12 +00001449 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001450 assert(!DS.isFriendSpecified());
1451
Richard Smith1ab0d902011-06-25 02:28:38 +00001452 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001453
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454 // C++ 9.2p6: A member shall not be declared to have automatic storage
1455 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001456 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1457 // data members and cannot be applied to names declared const or static,
1458 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459 switch (DS.getStorageClassSpec()) {
1460 case DeclSpec::SCS_unspecified:
1461 case DeclSpec::SCS_typedef:
1462 case DeclSpec::SCS_static:
1463 // FALL THROUGH.
1464 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001465 case DeclSpec::SCS_mutable:
1466 if (isFunc) {
1467 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001468 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001469 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001470 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Sebastian Redla11f42f2008-11-17 23:24:37 +00001472 // FIXME: It would be nicer if the keyword was ignored only for this
1473 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001474 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001475 }
1476 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477 default:
1478 if (DS.getStorageClassSpecLoc().isValid())
1479 Diag(DS.getStorageClassSpecLoc(),
1480 diag::err_storageclass_invalid_for_member);
1481 else
1482 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1483 D.getMutableDeclSpec().ClearStorageClassSpecs();
1484 }
1485
Sebastian Redl669d5d72008-11-14 23:42:31 +00001486 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1487 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001488 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001489
1490 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001491 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001492 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001493
1494 // Data members must have identifiers for names.
1495 if (Name.getNameKind() != DeclarationName::Identifier) {
1496 Diag(Loc, diag::err_bad_variable_name)
1497 << Name;
1498 return 0;
1499 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001500
Douglas Gregorf2503652011-09-21 14:40:46 +00001501 IdentifierInfo *II = Name.getAsIdentifierInfo();
1502
1503 // Member field could not be with "template" keyword.
1504 // So TemplateParameterLists should be empty in this case.
1505 if (TemplateParameterLists.size()) {
1506 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1507 if (TemplateParams->size()) {
1508 // There is no such thing as a member field template.
1509 Diag(D.getIdentifierLoc(), diag::err_template_member)
1510 << II
1511 << SourceRange(TemplateParams->getTemplateLoc(),
1512 TemplateParams->getRAngleLoc());
1513 } else {
1514 // There is an extraneous 'template<>' for this member.
1515 Diag(TemplateParams->getTemplateLoc(),
1516 diag::err_template_member_noparams)
1517 << II
1518 << SourceRange(TemplateParams->getTemplateLoc(),
1519 TemplateParams->getRAngleLoc());
1520 }
1521 return 0;
1522 }
1523
Douglas Gregor922fff22010-10-13 22:19:53 +00001524 if (SS.isSet() && !SS.isInvalid()) {
1525 // The user provided a superfluous scope specifier inside a class
1526 // definition:
1527 //
1528 // class X {
1529 // int X::member;
1530 // };
1531 DeclContext *DC = 0;
1532 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1533 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001534 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001535 else
1536 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1537 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001538
Douglas Gregor922fff22010-10-13 22:19:53 +00001539 SS.clear();
1540 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001541
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001542 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001543 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001544 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001545 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001546 assert(!HasDeferredInit);
1547
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001548 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001549 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001550 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001551 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001552
1553 // Non-instance-fields can't have a bitfield.
1554 if (BitWidth) {
1555 if (Member->isInvalidDecl()) {
1556 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001557 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001558 // C++ 9.6p3: A bit-field shall not be a static member.
1559 // "static member 'A' cannot be a bit-field"
1560 Diag(Loc, diag::err_static_not_bitfield)
1561 << Name << BitWidth->getSourceRange();
1562 } else if (isa<TypedefDecl>(Member)) {
1563 // "typedef member 'x' cannot be a bit-field"
1564 Diag(Loc, diag::err_typedef_not_bitfield)
1565 << Name << BitWidth->getSourceRange();
1566 } else {
1567 // A function typedef ("typedef int f(); f a;").
1568 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1569 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001570 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001571 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001572 }
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Chris Lattner8b963ef2009-03-05 23:01:03 +00001574 BitWidth = 0;
1575 Member->setInvalidDecl();
1576 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001577
1578 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Douglas Gregor37b372b2009-08-20 22:52:58 +00001580 // If we have declared a member function template, set the access of the
1581 // templated declaration as well.
1582 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1583 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001584 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001585
Anders Carlssonaae5af22011-01-20 04:34:22 +00001586 if (VS.isOverrideSpecified()) {
1587 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1588 if (!MD || !MD->isVirtual()) {
1589 Diag(Member->getLocStart(),
1590 diag::override_keyword_only_allowed_on_virtual_member_functions)
1591 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001592 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001593 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001594 }
1595 if (VS.isFinalSpecified()) {
1596 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1597 if (!MD || !MD->isVirtual()) {
1598 Diag(Member->getLocStart(),
1599 diag::override_keyword_only_allowed_on_virtual_member_functions)
1600 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001601 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001602 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001603 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001604
Douglas Gregorf5251602011-03-08 17:10:18 +00001605 if (VS.getLastLocation().isValid()) {
1606 // Update the end location of a method that has a virt-specifiers.
1607 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1608 MD->setRangeEnd(VS.getLastLocation());
1609 }
1610
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001611 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001612
Douglas Gregor10bd3682008-11-17 22:58:34 +00001613 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001614
John McCallb25b2952011-02-15 07:12:36 +00001615 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001616 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001617 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001618}
1619
Richard Smith7a614d82011-06-11 17:19:42 +00001620/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001621/// in-class initializer for a non-static C++ class member, and after
1622/// instantiating an in-class initializer in a class template. Such actions
1623/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001624void
1625Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1626 Expr *InitExpr) {
1627 FieldDecl *FD = cast<FieldDecl>(D);
1628
1629 if (!InitExpr) {
1630 FD->setInvalidDecl();
1631 FD->removeInClassInitializer();
1632 return;
1633 }
1634
Peter Collingbournefef21892011-10-23 18:59:44 +00001635 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1636 FD->setInvalidDecl();
1637 FD->removeInClassInitializer();
1638 return;
1639 }
1640
Richard Smith7a614d82011-06-11 17:19:42 +00001641 ExprResult Init = InitExpr;
1642 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001643 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001644 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001645 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1646 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001647 Expr **Inits = &InitExpr;
1648 unsigned NumInits = 1;
1649 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1650 InitializationKind Kind = EqualLoc.isInvalid()
1651 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1652 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1653 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1654 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001655 if (Init.isInvalid()) {
1656 FD->setInvalidDecl();
1657 return;
1658 }
1659
1660 CheckImplicitConversions(Init.get(), EqualLoc);
1661 }
1662
1663 // C++0x [class.base.init]p7:
1664 // The initialization of each base and member constitutes a
1665 // full-expression.
1666 Init = MaybeCreateExprWithCleanups(Init);
1667 if (Init.isInvalid()) {
1668 FD->setInvalidDecl();
1669 return;
1670 }
1671
1672 InitExpr = Init.release();
1673
1674 FD->setInClassInitializer(InitExpr);
1675}
1676
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001677/// \brief Find the direct and/or virtual base specifiers that
1678/// correspond to the given base type, for use in base initialization
1679/// within a constructor.
1680static bool FindBaseInitializer(Sema &SemaRef,
1681 CXXRecordDecl *ClassDecl,
1682 QualType BaseType,
1683 const CXXBaseSpecifier *&DirectBaseSpec,
1684 const CXXBaseSpecifier *&VirtualBaseSpec) {
1685 // First, check for a direct base class.
1686 DirectBaseSpec = 0;
1687 for (CXXRecordDecl::base_class_const_iterator Base
1688 = ClassDecl->bases_begin();
1689 Base != ClassDecl->bases_end(); ++Base) {
1690 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1691 // We found a direct base of this type. That's what we're
1692 // initializing.
1693 DirectBaseSpec = &*Base;
1694 break;
1695 }
1696 }
1697
1698 // Check for a virtual base class.
1699 // FIXME: We might be able to short-circuit this if we know in advance that
1700 // there are no virtual bases.
1701 VirtualBaseSpec = 0;
1702 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1703 // We haven't found a base yet; search the class hierarchy for a
1704 // virtual base class.
1705 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1706 /*DetectVirtual=*/false);
1707 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1708 BaseType, Paths)) {
1709 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1710 Path != Paths.end(); ++Path) {
1711 if (Path->back().Base->isVirtual()) {
1712 VirtualBaseSpec = Path->back().Base;
1713 break;
1714 }
1715 }
1716 }
1717 }
1718
1719 return DirectBaseSpec || VirtualBaseSpec;
1720}
1721
Sebastian Redl6df65482011-09-24 17:48:25 +00001722/// \brief Handle a C++ member initializer using braced-init-list syntax.
1723MemInitResult
1724Sema::ActOnMemInitializer(Decl *ConstructorD,
1725 Scope *S,
1726 CXXScopeSpec &SS,
1727 IdentifierInfo *MemberOrBase,
1728 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001729 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001730 SourceLocation IdLoc,
1731 Expr *InitList,
1732 SourceLocation EllipsisLoc) {
1733 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001734 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001735 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001736}
1737
1738/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001739MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001740Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001741 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001742 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001743 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001744 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001745 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001746 SourceLocation IdLoc,
1747 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001748 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001749 SourceLocation RParenLoc,
1750 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001751 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1752 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001753 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001754 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001755}
1756
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001757namespace {
1758
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001759// Callback to only accept typo corrections that can be a valid C++ member
1760// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001761class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1762 public:
1763 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1764 : ClassDecl(ClassDecl) {}
1765
1766 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1767 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1768 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1769 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1770 else
1771 return isa<TypeDecl>(ND);
1772 }
1773 return false;
1774 }
1775
1776 private:
1777 CXXRecordDecl *ClassDecl;
1778};
1779
1780}
1781
Sebastian Redl6df65482011-09-24 17:48:25 +00001782/// \brief Handle a C++ member initializer.
1783MemInitResult
1784Sema::BuildMemInitializer(Decl *ConstructorD,
1785 Scope *S,
1786 CXXScopeSpec &SS,
1787 IdentifierInfo *MemberOrBase,
1788 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001789 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001790 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001791 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001792 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001793 if (!ConstructorD)
1794 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001796 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
1798 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001799 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001800 if (!Constructor) {
1801 // The user wrote a constructor initializer on a function that is
1802 // not a C++ constructor. Ignore the error for now, because we may
1803 // have more member initializers coming; we'll diagnose it just
1804 // once in ActOnMemInitializers.
1805 return true;
1806 }
1807
1808 CXXRecordDecl *ClassDecl = Constructor->getParent();
1809
1810 // C++ [class.base.init]p2:
1811 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001812 // constructor's class and, if not found in that scope, are looked
1813 // up in the scope containing the constructor's definition.
1814 // [Note: if the constructor's class contains a member with the
1815 // same name as a direct or virtual base class of the class, a
1816 // mem-initializer-id naming the member or base class and composed
1817 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001818 // mem-initializer-id for the hidden base class may be specified
1819 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001820 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001821 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001822 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001823 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001824 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001825 ValueDecl *Member;
1826 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1827 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001828 if (EllipsisLoc.isValid())
1829 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001830 << MemberOrBase
1831 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001832
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001833 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001834 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001835 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001836 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001837 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001838 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001839 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001840
1841 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001842 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001843 } else if (DS.getTypeSpecType() == TST_decltype) {
1844 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001845 } else {
1846 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1847 LookupParsedName(R, S, &SS);
1848
1849 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1850 if (!TyD) {
1851 if (R.isAmbiguous()) return true;
1852
John McCallfd225442010-04-09 19:01:14 +00001853 // We don't want access-control diagnostics here.
1854 R.suppressDiagnostics();
1855
Douglas Gregor7a886e12010-01-19 06:46:48 +00001856 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1857 bool NotUnknownSpecialization = false;
1858 DeclContext *DC = computeDeclContext(SS, false);
1859 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1860 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1861
1862 if (!NotUnknownSpecialization) {
1863 // When the scope specifier can refer to a member of an unknown
1864 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001865 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1866 SS.getWithLocInContext(Context),
1867 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001868 if (BaseType.isNull())
1869 return true;
1870
Douglas Gregor7a886e12010-01-19 06:46:48 +00001871 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001872 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001873 }
1874 }
1875
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001876 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001877 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001878 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001879 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001880 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001881 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001882 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1883 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1884 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001885 // We have found a non-static data member with a similar
1886 // name to what was typed; complain and initialize that
1887 // member.
1888 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1889 << MemberOrBase << true << CorrectedQuotedStr
1890 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1891 Diag(Member->getLocation(), diag::note_previous_decl)
1892 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001893
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001894 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001895 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001896 const CXXBaseSpecifier *DirectBaseSpec;
1897 const CXXBaseSpecifier *VirtualBaseSpec;
1898 if (FindBaseInitializer(*this, ClassDecl,
1899 Context.getTypeDeclType(Type),
1900 DirectBaseSpec, VirtualBaseSpec)) {
1901 // We have found a direct or virtual base class with a
1902 // similar name to what was typed; complain and initialize
1903 // that base class.
1904 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001905 << MemberOrBase << false << CorrectedQuotedStr
1906 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001907
1908 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1909 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001910 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001911 diag::note_base_class_specified_here)
1912 << BaseSpec->getType()
1913 << BaseSpec->getSourceRange();
1914
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001915 TyD = Type;
1916 }
1917 }
1918 }
1919
Douglas Gregor7a886e12010-01-19 06:46:48 +00001920 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001921 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001922 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 return true;
1924 }
John McCall2b194412009-12-21 10:41:20 +00001925 }
1926
Douglas Gregor7a886e12010-01-19 06:46:48 +00001927 if (BaseType.isNull()) {
1928 BaseType = Context.getTypeDeclType(TyD);
1929 if (SS.isSet()) {
1930 NestedNameSpecifier *Qualifier =
1931 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001932
Douglas Gregor7a886e12010-01-19 06:46:48 +00001933 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001934 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001935 }
John McCall2b194412009-12-21 10:41:20 +00001936 }
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
John McCalla93c9342009-12-07 02:54:59 +00001939 if (!TInfo)
1940 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001941
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001942 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001943}
1944
Chandler Carruth81c64772011-09-03 01:14:15 +00001945/// Checks a member initializer expression for cases where reference (or
1946/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001947static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1948 Expr *Init,
1949 SourceLocation IdLoc) {
1950 QualType MemberTy = Member->getType();
1951
1952 // We only handle pointers and references currently.
1953 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1954 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1955 return;
1956
1957 const bool IsPointer = MemberTy->isPointerType();
1958 if (IsPointer) {
1959 if (const UnaryOperator *Op
1960 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1961 // The only case we're worried about with pointers requires taking the
1962 // address.
1963 if (Op->getOpcode() != UO_AddrOf)
1964 return;
1965
1966 Init = Op->getSubExpr();
1967 } else {
1968 // We only handle address-of expression initializers for pointers.
1969 return;
1970 }
1971 }
1972
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001973 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1974 // Taking the address of a temporary will be diagnosed as a hard error.
1975 if (IsPointer)
1976 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001977
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001978 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1979 << Member << Init->getSourceRange();
1980 } else if (const DeclRefExpr *DRE
1981 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1982 // We only warn when referring to a non-reference parameter declaration.
1983 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1984 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001985 return;
1986
1987 S.Diag(Init->getExprLoc(),
1988 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1989 : diag::warn_bind_ref_member_to_parameter)
1990 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001991 } else {
1992 // Other initializers are fine.
1993 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001994 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001995
1996 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1997 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001998}
1999
John McCallb4190042009-11-04 23:02:40 +00002000/// Checks an initializer expression for use of uninitialized fields, such as
2001/// containing the field that is being initialized. Returns true if there is an
2002/// uninitialized field was used an updates the SourceLocation parameter; false
2003/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002004static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002005 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002006 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002007 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2008
Nick Lewycky43ad1822010-06-15 07:32:55 +00002009 if (isa<CallExpr>(S)) {
2010 // Do not descend into function calls or constructors, as the use
2011 // of an uninitialized field may be valid. One would have to inspect
2012 // the contents of the function/ctor to determine if it is safe or not.
2013 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2014 // may be safe, depending on what the function/ctor does.
2015 return false;
2016 }
2017 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2018 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002019
2020 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2021 // The member expression points to a static data member.
2022 assert(VD->isStaticDataMember() &&
2023 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002024 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002025 return false;
2026 }
2027
2028 if (isa<EnumConstantDecl>(RhsField)) {
2029 // The member expression points to an enum.
2030 return false;
2031 }
2032
John McCallb4190042009-11-04 23:02:40 +00002033 if (RhsField == LhsField) {
2034 // Initializing a field with itself. Throw a warning.
2035 // But wait; there are exceptions!
2036 // Exception #1: The field may not belong to this record.
2037 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002038 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002039 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2040 // Even though the field matches, it does not belong to this record.
2041 return false;
2042 }
2043 // None of the exceptions triggered; return true to indicate an
2044 // uninitialized field was used.
2045 *L = ME->getMemberLoc();
2046 return true;
2047 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002048 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002049 // sizeof/alignof doesn't reference contents, do not warn.
2050 return false;
2051 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2052 // address-of doesn't reference contents (the pointer may be dereferenced
2053 // in the same expression but it would be rare; and weird).
2054 if (UOE->getOpcode() == UO_AddrOf)
2055 return false;
John McCallb4190042009-11-04 23:02:40 +00002056 }
John McCall7502c1d2011-02-13 04:07:26 +00002057 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002058 if (!*it) {
2059 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002060 continue;
2061 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002062 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2063 return true;
John McCallb4190042009-11-04 23:02:40 +00002064 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002065 return false;
John McCallb4190042009-11-04 23:02:40 +00002066}
2067
John McCallf312b1e2010-08-26 23:41:50 +00002068MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002069Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002070 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002071 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2072 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2073 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002074 "Member must be a FieldDecl or IndirectFieldDecl");
2075
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002076 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002077 return true;
2078
Douglas Gregor464b2f02010-11-05 22:21:31 +00002079 if (Member->isInvalidDecl())
2080 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002081
John McCallb4190042009-11-04 23:02:40 +00002082 // Diagnose value-uses of fields to initialize themselves, e.g.
2083 // foo(foo)
2084 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002085 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002086 Expr **Args;
2087 unsigned NumArgs;
2088 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2089 Args = ParenList->getExprs();
2090 NumArgs = ParenList->getNumExprs();
2091 } else {
2092 InitListExpr *InitList = cast<InitListExpr>(Init);
2093 Args = InitList->getInits();
2094 NumArgs = InitList->getNumInits();
2095 }
2096 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002097 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002098 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002099 // FIXME: Return true in the case when other fields are used before being
2100 // uninitialized. For example, let this field be the i'th field. When
2101 // initializing the i'th field, throw a warning if any of the >= i'th
2102 // fields are used, as they are not yet initialized.
2103 // Right now we are only handling the case where the i'th field uses
2104 // itself in its initializer.
2105 Diag(L, diag::warn_field_is_uninit);
2106 }
2107 }
2108
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002109 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002110
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002111 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002112 // Can't check initialization for a member of dependent type or when
2113 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002114 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002115 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002116 bool InitList = false;
2117 if (isa<InitListExpr>(Init)) {
2118 InitList = true;
2119 Args = &Init;
2120 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002121
2122 if (isStdInitializerList(Member->getType(), 0)) {
2123 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2124 << /*at end of ctor*/1 << InitRange;
2125 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002126 }
2127
Chandler Carruth894aed92010-12-06 09:23:57 +00002128 // Initialize the member.
2129 InitializedEntity MemberEntity =
2130 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2131 : InitializedEntity::InitializeMember(IndirectMember, 0);
2132 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002133 InitList ? InitializationKind::CreateDirectList(IdLoc)
2134 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2135 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002136
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002137 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2138 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2139 MultiExprArg(*this, Args, NumArgs),
2140 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002141 if (MemberInit.isInvalid())
2142 return true;
2143
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002144 CheckImplicitConversions(MemberInit.get(),
2145 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002146
2147 // C++0x [class.base.init]p7:
2148 // The initialization of each base and member constitutes a
2149 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002150 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002151 if (MemberInit.isInvalid())
2152 return true;
2153
2154 // If we are in a dependent context, template instantiation will
2155 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002156 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002157 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2158 // of the information that we have about the member
2159 // initializer. However, deconstructing the ASTs is a dicey process,
2160 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002161 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002162 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002163 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002164 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002165 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2166 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002167 }
2168
Chandler Carruth894aed92010-12-06 09:23:57 +00002169 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002170 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2171 InitRange.getBegin(), Init,
2172 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002173 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002174 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2175 InitRange.getBegin(), Init,
2176 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002177 }
Eli Friedman59c04372009-07-29 19:44:27 +00002178}
2179
John McCallf312b1e2010-08-26 23:41:50 +00002180MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002181Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002182 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002183 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002184 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002185 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002186 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002187 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002188
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002189 bool InitList = true;
2190 Expr **Args = &Init;
2191 unsigned NumArgs = 1;
2192 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2193 InitList = false;
2194 Args = ParenList->getExprs();
2195 NumArgs = ParenList->getNumExprs();
2196 }
2197
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002198 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002199 // Initialize the object.
2200 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2201 QualType(ClassDecl->getTypeForDecl(), 0));
2202 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002203 InitList ? InitializationKind::CreateDirectList(NameLoc)
2204 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2205 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2207 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2208 MultiExprArg(*this, Args,NumArgs),
2209 0);
Sean Hunt41717662011-02-26 19:13:13 +00002210 if (DelegationInit.isInvalid())
2211 return true;
2212
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002213 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2214 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002215
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002216 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002217
2218 // C++0x [class.base.init]p7:
2219 // The initialization of each base and member constitutes a
2220 // full-expression.
2221 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2222 if (DelegationInit.isInvalid())
2223 return true;
2224
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002225 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002226 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002228}
2229
2230MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002231Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002232 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002233 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002234 SourceLocation BaseLoc
2235 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002236
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002237 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2238 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2239 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2240
2241 // C++ [class.base.init]p2:
2242 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002243 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002244 // of that class, the mem-initializer is ill-formed. A
2245 // mem-initializer-list can initialize a base class using any
2246 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002247 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002248
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002249 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002250 if (EllipsisLoc.isValid()) {
2251 // This is a pack expansion.
2252 if (!BaseType->containsUnexpandedParameterPack()) {
2253 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002254 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002255
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002256 EllipsisLoc = SourceLocation();
2257 }
2258 } else {
2259 // Check for any unexpanded parameter packs.
2260 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2261 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002262
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002264 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002265 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002266
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002267 // Check for direct and virtual base classes.
2268 const CXXBaseSpecifier *DirectBaseSpec = 0;
2269 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2270 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002271 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2272 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002273 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002274
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002275 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2276 VirtualBaseSpec);
2277
2278 // C++ [base.class.init]p2:
2279 // Unless the mem-initializer-id names a nonstatic data member of the
2280 // constructor's class or a direct or virtual base of that class, the
2281 // mem-initializer is ill-formed.
2282 if (!DirectBaseSpec && !VirtualBaseSpec) {
2283 // If the class has any dependent bases, then it's possible that
2284 // one of those types will resolve to the same type as
2285 // BaseType. Therefore, just treat this as a dependent base
2286 // class initialization. FIXME: Should we try to check the
2287 // initialization anyway? It seems odd.
2288 if (ClassDecl->hasAnyDependentBases())
2289 Dependent = true;
2290 else
2291 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2292 << BaseType << Context.getTypeDeclType(ClassDecl)
2293 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2294 }
2295 }
2296
2297 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002298 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Sebastian Redl6df65482011-09-24 17:48:25 +00002300 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2301 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002302 InitRange.getBegin(), Init,
2303 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002304 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002305
2306 // C++ [base.class.init]p2:
2307 // If a mem-initializer-id is ambiguous because it designates both
2308 // a direct non-virtual base class and an inherited virtual base
2309 // class, the mem-initializer is ill-formed.
2310 if (DirectBaseSpec && VirtualBaseSpec)
2311 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002312 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002314 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002315 if (!BaseSpec)
2316 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2317
2318 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002319 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002320 Expr **Args = &Init;
2321 unsigned NumArgs = 1;
2322 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002323 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 Args = ParenList->getExprs();
2325 NumArgs = ParenList->getNumExprs();
2326 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002327
2328 InitializedEntity BaseEntity =
2329 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2330 InitializationKind Kind =
2331 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2332 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2333 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2335 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2336 MultiExprArg(*this, Args, NumArgs),
2337 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002338 if (BaseInit.isInvalid())
2339 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002340
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002341 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002342
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002343 // C++0x [class.base.init]p7:
2344 // The initialization of each base and member constitutes a
2345 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002346 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 if (BaseInit.isInvalid())
2348 return true;
2349
2350 // If we are in a dependent context, template instantiation will
2351 // perform this type-checking again. Just save the arguments that we
2352 // received in a ParenListExpr.
2353 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2354 // of the information that we have about the base
2355 // initializer. However, deconstructing the ASTs is a dicey process,
2356 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002357 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002358 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002359
Sean Huntcbb67482011-01-08 20:30:50 +00002360 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002361 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002362 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002363 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002364 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002365}
2366
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002367// Create a static_cast\<T&&>(expr).
2368static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2369 QualType ExprType = E->getType();
2370 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2371 SourceLocation ExprLoc = E->getLocStart();
2372 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2373 TargetType, ExprLoc);
2374
2375 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2376 SourceRange(ExprLoc, ExprLoc),
2377 E->getSourceRange()).take();
2378}
2379
Anders Carlssone5ef7402010-04-23 03:10:23 +00002380/// ImplicitInitializerKind - How an implicit base or member initializer should
2381/// initialize its base or member.
2382enum ImplicitInitializerKind {
2383 IIK_Default,
2384 IIK_Copy,
2385 IIK_Move
2386};
2387
Anders Carlssondefefd22010-04-23 02:00:02 +00002388static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002389BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002390 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002391 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002392 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002393 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002394 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002395 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2396 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002397
John McCall60d7b3a2010-08-24 06:29:42 +00002398 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002399
2400 switch (ImplicitInitKind) {
2401 case IIK_Default: {
2402 InitializationKind InitKind
2403 = InitializationKind::CreateDefault(Constructor->getLocation());
2404 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2405 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002406 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002407 break;
2408 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002409
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002410 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002411 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002412 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002413 ParmVarDecl *Param = Constructor->getParamDecl(0);
2414 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002415
Anders Carlssone5ef7402010-04-23 03:10:23 +00002416 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002417 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002418 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002419 Constructor->getLocation(), ParamType,
2420 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002421
Eli Friedman5f2987c2012-02-02 03:46:19 +00002422 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2423
Anders Carlssonc7957502010-04-24 22:02:54 +00002424 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002425 QualType ArgTy =
2426 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2427 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002428
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002429 if (Moving) {
2430 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2431 }
2432
John McCallf871d0c2010-08-07 06:22:56 +00002433 CXXCastPath BasePath;
2434 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002435 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2436 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002437 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002439
Anders Carlssone5ef7402010-04-23 03:10:23 +00002440 InitializationKind InitKind
2441 = InitializationKind::CreateDirect(Constructor->getLocation(),
2442 SourceLocation(), SourceLocation());
2443 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2444 &CopyCtorArg, 1);
2445 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002446 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002447 break;
2448 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002449 }
John McCall9ae2f072010-08-23 23:25:46 +00002450
Douglas Gregor53c374f2010-12-07 00:41:46 +00002451 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002452 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002453 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002454
Anders Carlssondefefd22010-04-23 02:00:02 +00002455 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002456 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002457 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2458 SourceLocation()),
2459 BaseSpec->isVirtual(),
2460 SourceLocation(),
2461 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002462 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002463 SourceLocation());
2464
Anders Carlssondefefd22010-04-23 02:00:02 +00002465 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002466}
2467
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468static bool RefersToRValueRef(Expr *MemRef) {
2469 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2470 return Referenced->getType()->isRValueReferenceType();
2471}
2472
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002473static bool
2474BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002475 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002476 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002477 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002478 if (Field->isInvalidDecl())
2479 return true;
2480
Chandler Carruthf186b542010-06-29 23:50:44 +00002481 SourceLocation Loc = Constructor->getLocation();
2482
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002483 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2484 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002485 ParmVarDecl *Param = Constructor->getParamDecl(0);
2486 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002487
2488 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002489 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2490 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002491
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002492 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002493 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002494 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002495 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002496
Eli Friedman5f2987c2012-02-02 03:46:19 +00002497 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2498
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002499 if (Moving) {
2500 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2501 }
2502
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002503 // Build a reference to this field within the parameter.
2504 CXXScopeSpec SS;
2505 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2506 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2508 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002509 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002510 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002511 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002512 ParamType, Loc,
2513 /*IsArrow=*/false,
2514 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002515 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002516 /*FirstQualifierInScope=*/0,
2517 MemberLookup,
2518 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002519 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002520 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002521
2522 // C++11 [class.copy]p15:
2523 // - if a member m has rvalue reference type T&&, it is direct-initialized
2524 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002525 if (RefersToRValueRef(CtorArg.get())) {
2526 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002527 }
2528
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002529 // When the field we are copying is an array, create index variables for
2530 // each dimension of the array. We use these index variables to subscript
2531 // the source array, and other clients (e.g., CodeGen) will perform the
2532 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002533 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002534 QualType BaseType = Field->getType();
2535 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002536 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002537 while (const ConstantArrayType *Array
2538 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002540 // Create the iteration variable for this array index.
2541 IdentifierInfo *IterationVarName = 0;
2542 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002543 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 llvm::raw_svector_ostream OS(Str);
2545 OS << "__i" << IndexVariables.size();
2546 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2547 }
2548 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002549 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002550 IterationVarName, SizeType,
2551 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002552 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002553 IndexVariables.push_back(IterationVar);
2554
2555 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002556 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002557 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002558 assert(!IterationVarRef.isInvalid() &&
2559 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002560 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2561 assert(!IterationVarRef.isInvalid() &&
2562 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002563
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002564 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002565 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002566 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002567 Loc);
2568 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002569 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002570
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002571 BaseType = Array->getElementType();
2572 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002573
2574 // The array subscript expression is an lvalue, which is wrong for moving.
2575 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002576 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002577
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002578 // Construct the entity that we will be initializing. For an array, this
2579 // will be first element in the array, which may require several levels
2580 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002581 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002583 if (Indirect)
2584 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2585 else
2586 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2588 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2589 0,
2590 Entities.back()));
2591
2592 // Direct-initialize to use the copy constructor.
2593 InitializationKind InitKind =
2594 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2595
Sebastian Redl74e611a2011-09-04 18:14:28 +00002596 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002597 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002598 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002599
John McCall60d7b3a2010-08-24 06:29:42 +00002600 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002601 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002602 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002603 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002604 if (MemberInit.isInvalid())
2605 return true;
2606
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002607 if (Indirect) {
2608 assert(IndexVariables.size() == 0 &&
2609 "Indirect field improperly initialized");
2610 CXXMemberInit
2611 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2612 Loc, Loc,
2613 MemberInit.takeAs<Expr>(),
2614 Loc);
2615 } else
2616 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2617 Loc, MemberInit.takeAs<Expr>(),
2618 Loc,
2619 IndexVariables.data(),
2620 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002621 return false;
2622 }
2623
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002624 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2625
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002626 QualType FieldBaseElementType =
2627 SemaRef.Context.getBaseElementType(Field->getType());
2628
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002629 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002630 InitializedEntity InitEntity
2631 = Indirect? InitializedEntity::InitializeMember(Indirect)
2632 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002633 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002634 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002635
2636 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002637 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002638 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002639
Douglas Gregor53c374f2010-12-07 00:41:46 +00002640 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002641 if (MemberInit.isInvalid())
2642 return true;
2643
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002644 if (Indirect)
2645 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2646 Indirect, Loc,
2647 Loc,
2648 MemberInit.get(),
2649 Loc);
2650 else
2651 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2652 Field, Loc, Loc,
2653 MemberInit.get(),
2654 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002655 return false;
2656 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002657
Sean Hunt1f2f3842011-05-17 00:19:05 +00002658 if (!Field->getParent()->isUnion()) {
2659 if (FieldBaseElementType->isReferenceType()) {
2660 SemaRef.Diag(Constructor->getLocation(),
2661 diag::err_uninitialized_member_in_ctor)
2662 << (int)Constructor->isImplicit()
2663 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2664 << 0 << Field->getDeclName();
2665 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2666 return true;
2667 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002668
Sean Hunt1f2f3842011-05-17 00:19:05 +00002669 if (FieldBaseElementType.isConstQualified()) {
2670 SemaRef.Diag(Constructor->getLocation(),
2671 diag::err_uninitialized_member_in_ctor)
2672 << (int)Constructor->isImplicit()
2673 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2674 << 1 << Field->getDeclName();
2675 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2676 return true;
2677 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002678 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002679
John McCallf85e1932011-06-15 23:02:42 +00002680 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2681 FieldBaseElementType->isObjCRetainableType() &&
2682 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2683 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2684 // Instant objects:
2685 // Default-initialize Objective-C pointers to NULL.
2686 CXXMemberInit
2687 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2688 Loc, Loc,
2689 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2690 Loc);
2691 return false;
2692 }
2693
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002694 // Nothing to initialize.
2695 CXXMemberInit = 0;
2696 return false;
2697}
John McCallf1860e52010-05-20 23:23:51 +00002698
2699namespace {
2700struct BaseAndFieldInfo {
2701 Sema &S;
2702 CXXConstructorDecl *Ctor;
2703 bool AnyErrorsInInits;
2704 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002705 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002706 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002707
2708 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2709 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002710 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2711 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002712 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002713 else if (Generated && Ctor->isMoveConstructor())
2714 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002715 else
2716 IIK = IIK_Default;
2717 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002718
2719 bool isImplicitCopyOrMove() const {
2720 switch (IIK) {
2721 case IIK_Copy:
2722 case IIK_Move:
2723 return true;
2724
2725 case IIK_Default:
2726 return false;
2727 }
David Blaikie30263482012-01-20 21:50:17 +00002728
2729 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002730 }
John McCallf1860e52010-05-20 23:23:51 +00002731};
2732}
2733
Richard Smitha4950662011-09-19 13:34:43 +00002734/// \brief Determine whether the given indirect field declaration is somewhere
2735/// within an anonymous union.
2736static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2737 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2738 CEnd = F->chain_end();
2739 C != CEnd; ++C)
2740 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2741 if (Record->isUnion())
2742 return true;
2743
2744 return false;
2745}
2746
Douglas Gregorddb21472011-11-02 23:04:16 +00002747/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2748/// array type.
2749static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2750 if (T->isIncompleteArrayType())
2751 return true;
2752
2753 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2754 if (!ArrayT->getSize())
2755 return true;
2756
2757 T = ArrayT->getElementType();
2758 }
2759
2760 return false;
2761}
2762
Richard Smith7a614d82011-06-11 17:19:42 +00002763static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002764 FieldDecl *Field,
2765 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002766
Chandler Carruthe861c602010-06-30 02:59:29 +00002767 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002768 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002769 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002770 return false;
2771 }
2772
Richard Smith7a614d82011-06-11 17:19:42 +00002773 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2774 // has a brace-or-equal-initializer, the entity is initialized as specified
2775 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002776 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002777 CXXCtorInitializer *Init;
2778 if (Indirect)
2779 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2780 SourceLocation(),
2781 SourceLocation(), 0,
2782 SourceLocation());
2783 else
2784 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2785 SourceLocation(),
2786 SourceLocation(), 0,
2787 SourceLocation());
2788 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002789 return false;
2790 }
2791
Richard Smithc115f632011-09-18 11:14:50 +00002792 // Don't build an implicit initializer for union members if none was
2793 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002794 if (Field->getParent()->isUnion() ||
2795 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002796 return false;
2797
Douglas Gregorddb21472011-11-02 23:04:16 +00002798 // Don't initialize incomplete or zero-length arrays.
2799 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2800 return false;
2801
John McCallf1860e52010-05-20 23:23:51 +00002802 // Don't try to build an implicit initializer if there were semantic
2803 // errors in any of the initializers (and therefore we might be
2804 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002805 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002806 return false;
2807
Sean Huntcbb67482011-01-08 20:30:50 +00002808 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002809 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2810 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002811 return true;
John McCallf1860e52010-05-20 23:23:51 +00002812
Francois Pichet00eb3f92010-12-04 09:14:42 +00002813 if (Init)
2814 Info.AllToInit.push_back(Init);
2815
John McCallf1860e52010-05-20 23:23:51 +00002816 return false;
2817}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002818
2819bool
2820Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2821 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002822 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002823 Constructor->setNumCtorInitializers(1);
2824 CXXCtorInitializer **initializer =
2825 new (Context) CXXCtorInitializer*[1];
2826 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2827 Constructor->setCtorInitializers(initializer);
2828
Sean Huntb76af9c2011-05-03 23:05:34 +00002829 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002830 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002831 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2832 }
2833
Sean Huntc1598702011-05-05 00:05:47 +00002834 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002835
Sean Hunt059ce0d2011-05-01 07:04:31 +00002836 return false;
2837}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002838
John McCallb77115d2011-06-17 00:18:42 +00002839bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2840 CXXCtorInitializer **Initializers,
2841 unsigned NumInitializers,
2842 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002843 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002844 // Just store the initializers as written, they will be checked during
2845 // instantiation.
2846 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002847 Constructor->setNumCtorInitializers(NumInitializers);
2848 CXXCtorInitializer **baseOrMemberInitializers =
2849 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002850 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002851 NumInitializers * sizeof(CXXCtorInitializer*));
2852 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002853 }
2854
2855 return false;
2856 }
2857
John McCallf1860e52010-05-20 23:23:51 +00002858 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002859
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002860 // We need to build the initializer AST according to order of construction
2861 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002862 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002863 if (!ClassDecl)
2864 return true;
2865
Eli Friedman80c30da2009-11-09 19:20:36 +00002866 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002868 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002869 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002870
2871 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002872 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002873 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002874 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002875 }
2876
Anders Carlsson711f34a2010-04-21 19:52:01 +00002877 // Keep track of the direct virtual bases.
2878 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2879 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2880 E = ClassDecl->bases_end(); I != E; ++I) {
2881 if (I->isVirtual())
2882 DirectVBases.insert(I);
2883 }
2884
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002885 // Push virtual bases before others.
2886 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2887 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2888
Sean Huntcbb67482011-01-08 20:30:50 +00002889 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002890 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2891 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002892 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002893 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002894 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002895 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002896 VBase, IsInheritedVirtualBase,
2897 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002898 HadError = true;
2899 continue;
2900 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002901
John McCallf1860e52010-05-20 23:23:51 +00002902 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002903 }
2904 }
Mike Stump1eb44332009-09-09 15:08:12 +00002905
John McCallf1860e52010-05-20 23:23:51 +00002906 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2908 E = ClassDecl->bases_end(); Base != E; ++Base) {
2909 // Virtuals are in the virtual base list and already constructed.
2910 if (Base->isVirtual())
2911 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002912
Sean Huntcbb67482011-01-08 20:30:50 +00002913 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002914 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2915 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002916 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002917 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002918 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002919 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002920 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002921 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002922 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002923 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002924
John McCallf1860e52010-05-20 23:23:51 +00002925 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002926 }
2927 }
Mike Stump1eb44332009-09-09 15:08:12 +00002928
John McCallf1860e52010-05-20 23:23:51 +00002929 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002930 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2931 MemEnd = ClassDecl->decls_end();
2932 Mem != MemEnd; ++Mem) {
2933 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002934 // C++ [class.bit]p2:
2935 // A declaration for a bit-field that omits the identifier declares an
2936 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2937 // initialized.
2938 if (F->isUnnamedBitfield())
2939 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002940
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002941 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002942 // handle anonymous struct/union fields based on their individual
2943 // indirect fields.
2944 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2945 continue;
2946
2947 if (CollectFieldInitializer(*this, Info, F))
2948 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002949 continue;
2950 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002951
2952 // Beyond this point, we only consider default initialization.
2953 if (Info.IIK != IIK_Default)
2954 continue;
2955
2956 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2957 if (F->getType()->isIncompleteArrayType()) {
2958 assert(ClassDecl->hasFlexibleArrayMember() &&
2959 "Incomplete array type is not valid");
2960 continue;
2961 }
2962
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002963 // Initialize each field of an anonymous struct individually.
2964 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2965 HadError = true;
2966
2967 continue;
2968 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002969 }
Mike Stump1eb44332009-09-09 15:08:12 +00002970
John McCallf1860e52010-05-20 23:23:51 +00002971 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002972 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002973 Constructor->setNumCtorInitializers(NumInitializers);
2974 CXXCtorInitializer **baseOrMemberInitializers =
2975 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002976 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002977 NumInitializers * sizeof(CXXCtorInitializer*));
2978 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002979
John McCallef027fe2010-03-16 21:39:52 +00002980 // Constructors implicitly reference the base and member
2981 // destructors.
2982 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2983 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002984 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002985
2986 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002987}
2988
Eli Friedman6347f422009-07-21 19:28:10 +00002989static void *GetKeyForTopLevelField(FieldDecl *Field) {
2990 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002991 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002992 if (RT->getDecl()->isAnonymousStructOrUnion())
2993 return static_cast<void *>(RT->getDecl());
2994 }
2995 return static_cast<void *>(Field);
2996}
2997
Anders Carlssonea356fb2010-04-02 05:42:15 +00002998static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002999 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003000}
3001
Anders Carlssonea356fb2010-04-02 05:42:15 +00003002static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003003 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003004 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003005 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003006
Eli Friedman6347f422009-07-21 19:28:10 +00003007 // For fields injected into the class via declaration of an anonymous union,
3008 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003009 FieldDecl *Field = Member->getAnyMember();
3010
John McCall3c3ccdb2010-04-10 09:28:51 +00003011 // If the field is a member of an anonymous struct or union, our key
3012 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003013 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003014 if (RD->isAnonymousStructOrUnion()) {
3015 while (true) {
3016 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3017 if (Parent->isAnonymousStructOrUnion())
3018 RD = Parent;
3019 else
3020 break;
3021 }
3022
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003023 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003024 }
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003026 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003027}
3028
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003029static void
3030DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003031 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003032 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003033 unsigned NumInits) {
3034 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003035 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003037 // Don't check initializers order unless the warning is enabled at the
3038 // location of at least one initializer.
3039 bool ShouldCheckOrder = false;
3040 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003041 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003042 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3043 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003044 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003045 ShouldCheckOrder = true;
3046 break;
3047 }
3048 }
3049 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003050 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003051
John McCalld6ca8da2010-04-10 07:37:23 +00003052 // Build the list of bases and members in the order that they'll
3053 // actually be initialized. The explicit initializers should be in
3054 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003055 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Anders Carlsson071d6102010-04-02 03:38:04 +00003057 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3058
John McCalld6ca8da2010-04-10 07:37:23 +00003059 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003060 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003061 ClassDecl->vbases_begin(),
3062 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003063 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003064
John McCalld6ca8da2010-04-10 07:37:23 +00003065 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003066 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003067 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003068 if (Base->isVirtual())
3069 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003070 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072
John McCalld6ca8da2010-04-10 07:37:23 +00003073 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003074 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003075 E = ClassDecl->field_end(); Field != E; ++Field) {
3076 if (Field->isUnnamedBitfield())
3077 continue;
3078
John McCalld6ca8da2010-04-10 07:37:23 +00003079 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003080 }
3081
John McCalld6ca8da2010-04-10 07:37:23 +00003082 unsigned NumIdealInits = IdealInitKeys.size();
3083 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003084
Sean Huntcbb67482011-01-08 20:30:50 +00003085 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003086 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003087 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003088 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003089
3090 // Scan forward to try to find this initializer in the idealized
3091 // initializers list.
3092 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3093 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003094 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003095
3096 // If we didn't find this initializer, it must be because we
3097 // scanned past it on a previous iteration. That can only
3098 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003099 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003100 Sema::SemaDiagnosticBuilder D =
3101 SemaRef.Diag(PrevInit->getSourceLocation(),
3102 diag::warn_initializer_out_of_order);
3103
Francois Pichet00eb3f92010-12-04 09:14:42 +00003104 if (PrevInit->isAnyMemberInitializer())
3105 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003106 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003107 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003108
Francois Pichet00eb3f92010-12-04 09:14:42 +00003109 if (Init->isAnyMemberInitializer())
3110 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003111 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003112 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003113
3114 // Move back to the initializer's location in the ideal list.
3115 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3116 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003117 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003118
3119 assert(IdealIndex != NumIdealInits &&
3120 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003121 }
John McCalld6ca8da2010-04-10 07:37:23 +00003122
3123 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003124 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003125}
3126
John McCall3c3ccdb2010-04-10 09:28:51 +00003127namespace {
3128bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003129 CXXCtorInitializer *Init,
3130 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003131 if (!PrevInit) {
3132 PrevInit = Init;
3133 return false;
3134 }
3135
3136 if (FieldDecl *Field = Init->getMember())
3137 S.Diag(Init->getSourceLocation(),
3138 diag::err_multiple_mem_initialization)
3139 << Field->getDeclName()
3140 << Init->getSourceRange();
3141 else {
John McCallf4c73712011-01-19 06:33:43 +00003142 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003143 assert(BaseClass && "neither field nor base");
3144 S.Diag(Init->getSourceLocation(),
3145 diag::err_multiple_base_initialization)
3146 << QualType(BaseClass, 0)
3147 << Init->getSourceRange();
3148 }
3149 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3150 << 0 << PrevInit->getSourceRange();
3151
3152 return true;
3153}
3154
Sean Huntcbb67482011-01-08 20:30:50 +00003155typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003156typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3157
3158bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003159 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003160 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003161 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003162 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003163 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003164
3165 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003166 if (Parent->isUnion()) {
3167 UnionEntry &En = Unions[Parent];
3168 if (En.first && En.first != Child) {
3169 S.Diag(Init->getSourceLocation(),
3170 diag::err_multiple_mem_union_initialization)
3171 << Field->getDeclName()
3172 << Init->getSourceRange();
3173 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3174 << 0 << En.second->getSourceRange();
3175 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003176 }
3177 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003178 En.first = Child;
3179 En.second = Init;
3180 }
David Blaikie6fe29652011-11-17 06:01:57 +00003181 if (!Parent->isAnonymousStructOrUnion())
3182 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003183 }
3184
3185 Child = Parent;
3186 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003187 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003188
3189 return false;
3190}
3191}
3192
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003193/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003194void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003195 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003196 CXXCtorInitializer **meminits,
3197 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003198 bool AnyErrors) {
3199 if (!ConstructorDecl)
3200 return;
3201
3202 AdjustDeclIfTemplate(ConstructorDecl);
3203
3204 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003205 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003206
3207 if (!Constructor) {
3208 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3209 return;
3210 }
3211
Sean Huntcbb67482011-01-08 20:30:50 +00003212 CXXCtorInitializer **MemInits =
3213 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003214
3215 // Mapping for the duplicate initializers check.
3216 // For member initializers, this is keyed with a FieldDecl*.
3217 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003218 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003219
3220 // Mapping for the inconsistent anonymous-union initializers check.
3221 RedundantUnionMap MemberUnions;
3222
Anders Carlssonea356fb2010-04-02 05:42:15 +00003223 bool HadError = false;
3224 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003225 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003226
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003227 // Set the source order index.
3228 Init->setSourceOrder(i);
3229
Francois Pichet00eb3f92010-12-04 09:14:42 +00003230 if (Init->isAnyMemberInitializer()) {
3231 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003232 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3233 CheckRedundantUnionInit(*this, Init, MemberUnions))
3234 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003235 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003236 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3237 if (CheckRedundantInit(*this, Init, Members[Key]))
3238 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003239 } else {
3240 assert(Init->isDelegatingInitializer());
3241 // This must be the only initializer
3242 if (i != 0 || NumMemInits > 1) {
3243 Diag(MemInits[0]->getSourceLocation(),
3244 diag::err_delegating_initializer_alone)
3245 << MemInits[0]->getSourceRange();
3246 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003247 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003248 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003249 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003250 // Return immediately as the initializer is set.
3251 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003252 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003253 }
3254
Anders Carlssonea356fb2010-04-02 05:42:15 +00003255 if (HadError)
3256 return;
3257
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003258 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003259
Sean Huntcbb67482011-01-08 20:30:50 +00003260 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003261}
3262
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003263void
John McCallef027fe2010-03-16 21:39:52 +00003264Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3265 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003266 // Ignore dependent contexts. Also ignore unions, since their members never
3267 // have destructors implicitly called.
3268 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003269 return;
John McCall58e6f342010-03-16 05:22:47 +00003270
3271 // FIXME: all the access-control diagnostics are positioned on the
3272 // field/base declaration. That's probably good; that said, the
3273 // user might reasonably want to know why the destructor is being
3274 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003275
Anders Carlsson9f853df2009-11-17 04:44:12 +00003276 // Non-static data members.
3277 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3278 E = ClassDecl->field_end(); I != E; ++I) {
3279 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003280 if (Field->isInvalidDecl())
3281 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003282
3283 // Don't destroy incomplete or zero-length arrays.
3284 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3285 continue;
3286
Anders Carlsson9f853df2009-11-17 04:44:12 +00003287 QualType FieldType = Context.getBaseElementType(Field->getType());
3288
3289 const RecordType* RT = FieldType->getAs<RecordType>();
3290 if (!RT)
3291 continue;
3292
3293 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003294 if (FieldClassDecl->isInvalidDecl())
3295 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003296 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003297 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003298 // The destructor for an implicit anonymous union member is never invoked.
3299 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3300 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003301
Douglas Gregordb89f282010-07-01 22:47:18 +00003302 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003303 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003304 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003305 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003306 << Field->getDeclName()
3307 << FieldType);
3308
Eli Friedman5f2987c2012-02-02 03:46:19 +00003309 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003310 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003311 }
3312
John McCall58e6f342010-03-16 05:22:47 +00003313 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3314
Anders Carlsson9f853df2009-11-17 04:44:12 +00003315 // Bases.
3316 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3317 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003318 // Bases are always records in a well-formed non-dependent class.
3319 const RecordType *RT = Base->getType()->getAs<RecordType>();
3320
3321 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003322 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003323 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003324
John McCall58e6f342010-03-16 05:22:47 +00003325 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003326 // If our base class is invalid, we probably can't get its dtor anyway.
3327 if (BaseClassDecl->isInvalidDecl())
3328 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003329 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003330 continue;
John McCall58e6f342010-03-16 05:22:47 +00003331
Douglas Gregordb89f282010-07-01 22:47:18 +00003332 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003333 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003334
3335 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003336 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003337 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003338 << Base->getType()
3339 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003340
Eli Friedman5f2987c2012-02-02 03:46:19 +00003341 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003342 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003343 }
3344
3345 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003346 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3347 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003348
3349 // Bases are always records in a well-formed non-dependent class.
3350 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3351
3352 // Ignore direct virtual bases.
3353 if (DirectVirtualBases.count(RT))
3354 continue;
3355
John McCall58e6f342010-03-16 05:22:47 +00003356 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003357 // If our base class is invalid, we probably can't get its dtor anyway.
3358 if (BaseClassDecl->isInvalidDecl())
3359 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003360 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003361 continue;
John McCall58e6f342010-03-16 05:22:47 +00003362
Douglas Gregordb89f282010-07-01 22:47:18 +00003363 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003364 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003365 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003366 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003367 << VBase->getType());
3368
Eli Friedman5f2987c2012-02-02 03:46:19 +00003369 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003370 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003371 }
3372}
3373
John McCalld226f652010-08-21 09:40:31 +00003374void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003375 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003376 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Mike Stump1eb44332009-09-09 15:08:12 +00003378 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003379 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003380 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003381}
3382
Mike Stump1eb44332009-09-09 15:08:12 +00003383bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003384 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003385 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003386 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003387 else
John McCall94c3b562010-08-18 09:41:07 +00003388 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003389}
3390
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003391bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003392 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003393 if (!getLangOptions().CPlusPlus)
3394 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Anders Carlsson11f21a02009-03-23 19:10:31 +00003396 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003397 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Ted Kremenek6217b802009-07-29 21:53:49 +00003399 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003400 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003401 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003402 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003404 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003405 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003406 }
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Ted Kremenek6217b802009-07-29 21:53:49 +00003408 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003409 if (!RT)
3410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003411
John McCall86ff3082010-02-04 22:26:26 +00003412 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003413
John McCall94c3b562010-08-18 09:41:07 +00003414 // We can't answer whether something is abstract until it has a
3415 // definition. If it's currently being defined, we'll walk back
3416 // over all the declarations when we have a full definition.
3417 const CXXRecordDecl *Def = RD->getDefinition();
3418 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003419 return false;
3420
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003421 if (!RD->isAbstract())
3422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003424 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003425 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003426
John McCall94c3b562010-08-18 09:41:07 +00003427 return true;
3428}
3429
3430void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3431 // Check if we've already emitted the list of pure virtual functions
3432 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003433 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003434 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003436 CXXFinalOverriderMap FinalOverriders;
3437 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003439 // Keep a set of seen pure methods so we won't diagnose the same method
3440 // more than once.
3441 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3442
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003443 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3444 MEnd = FinalOverriders.end();
3445 M != MEnd;
3446 ++M) {
3447 for (OverridingMethods::iterator SO = M->second.begin(),
3448 SOEnd = M->second.end();
3449 SO != SOEnd; ++SO) {
3450 // C++ [class.abstract]p4:
3451 // A class is abstract if it contains or inherits at least one
3452 // pure virtual function for which the final overrider is pure
3453 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003455 //
3456 if (SO->second.size() != 1)
3457 continue;
3458
3459 if (!SO->second.front().Method->isPure())
3460 continue;
3461
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003462 if (!SeenPureMethods.insert(SO->second.front().Method))
3463 continue;
3464
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003465 Diag(SO->second.front().Method->getLocation(),
3466 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003467 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003468 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003469 }
3470
3471 if (!PureVirtualClassDiagSet)
3472 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3473 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003474}
3475
Anders Carlsson8211eff2009-03-24 01:19:16 +00003476namespace {
John McCall94c3b562010-08-18 09:41:07 +00003477struct AbstractUsageInfo {
3478 Sema &S;
3479 CXXRecordDecl *Record;
3480 CanQualType AbstractType;
3481 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003482
John McCall94c3b562010-08-18 09:41:07 +00003483 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3484 : S(S), Record(Record),
3485 AbstractType(S.Context.getCanonicalType(
3486 S.Context.getTypeDeclType(Record))),
3487 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003488
John McCall94c3b562010-08-18 09:41:07 +00003489 void DiagnoseAbstractType() {
3490 if (Invalid) return;
3491 S.DiagnoseAbstractType(Record);
3492 Invalid = true;
3493 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003494
John McCall94c3b562010-08-18 09:41:07 +00003495 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3496};
3497
3498struct CheckAbstractUsage {
3499 AbstractUsageInfo &Info;
3500 const NamedDecl *Ctx;
3501
3502 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3503 : Info(Info), Ctx(Ctx) {}
3504
3505 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3506 switch (TL.getTypeLocClass()) {
3507#define ABSTRACT_TYPELOC(CLASS, PARENT)
3508#define TYPELOC(CLASS, PARENT) \
3509 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3510#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003511 }
John McCall94c3b562010-08-18 09:41:07 +00003512 }
Mike Stump1eb44332009-09-09 15:08:12 +00003513
John McCall94c3b562010-08-18 09:41:07 +00003514 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3515 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3516 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003517 if (!TL.getArg(I))
3518 continue;
3519
John McCall94c3b562010-08-18 09:41:07 +00003520 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3521 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003522 }
John McCall94c3b562010-08-18 09:41:07 +00003523 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003524
John McCall94c3b562010-08-18 09:41:07 +00003525 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3526 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528
John McCall94c3b562010-08-18 09:41:07 +00003529 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3530 // Visit the type parameters from a permissive context.
3531 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3532 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3533 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3534 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3535 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3536 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003537 }
John McCall94c3b562010-08-18 09:41:07 +00003538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCall94c3b562010-08-18 09:41:07 +00003540 // Visit pointee types from a permissive context.
3541#define CheckPolymorphic(Type) \
3542 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3543 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3544 }
3545 CheckPolymorphic(PointerTypeLoc)
3546 CheckPolymorphic(ReferenceTypeLoc)
3547 CheckPolymorphic(MemberPointerTypeLoc)
3548 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003549 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003550
John McCall94c3b562010-08-18 09:41:07 +00003551 /// Handle all the types we haven't given a more specific
3552 /// implementation for above.
3553 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3554 // Every other kind of type that we haven't called out already
3555 // that has an inner type is either (1) sugar or (2) contains that
3556 // inner type in some way as a subobject.
3557 if (TypeLoc Next = TL.getNextTypeLoc())
3558 return Visit(Next, Sel);
3559
3560 // If there's no inner type and we're in a permissive context,
3561 // don't diagnose.
3562 if (Sel == Sema::AbstractNone) return;
3563
3564 // Check whether the type matches the abstract type.
3565 QualType T = TL.getType();
3566 if (T->isArrayType()) {
3567 Sel = Sema::AbstractArrayType;
3568 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003569 }
John McCall94c3b562010-08-18 09:41:07 +00003570 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3571 if (CT != Info.AbstractType) return;
3572
3573 // It matched; do some magic.
3574 if (Sel == Sema::AbstractArrayType) {
3575 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3576 << T << TL.getSourceRange();
3577 } else {
3578 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3579 << Sel << T << TL.getSourceRange();
3580 }
3581 Info.DiagnoseAbstractType();
3582 }
3583};
3584
3585void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3586 Sema::AbstractDiagSelID Sel) {
3587 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3588}
3589
3590}
3591
3592/// Check for invalid uses of an abstract type in a method declaration.
3593static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3594 CXXMethodDecl *MD) {
3595 // No need to do the check on definitions, which require that
3596 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003597 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003598 return;
3599
3600 // For safety's sake, just ignore it if we don't have type source
3601 // information. This should never happen for non-implicit methods,
3602 // but...
3603 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3604 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3605}
3606
3607/// Check for invalid uses of an abstract type within a class definition.
3608static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3609 CXXRecordDecl *RD) {
3610 for (CXXRecordDecl::decl_iterator
3611 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3612 Decl *D = *I;
3613 if (D->isImplicit()) continue;
3614
3615 // Methods and method templates.
3616 if (isa<CXXMethodDecl>(D)) {
3617 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3618 } else if (isa<FunctionTemplateDecl>(D)) {
3619 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3620 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3621
3622 // Fields and static variables.
3623 } else if (isa<FieldDecl>(D)) {
3624 FieldDecl *FD = cast<FieldDecl>(D);
3625 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3626 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3627 } else if (isa<VarDecl>(D)) {
3628 VarDecl *VD = cast<VarDecl>(D);
3629 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3630 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3631
3632 // Nested classes and class templates.
3633 } else if (isa<CXXRecordDecl>(D)) {
3634 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3635 } else if (isa<ClassTemplateDecl>(D)) {
3636 CheckAbstractClassUsage(Info,
3637 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3638 }
3639 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003640}
3641
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003642/// \brief Perform semantic checks on a class definition that has been
3643/// completing, introducing implicitly-declared members, checking for
3644/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003645void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003646 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003647 return;
3648
John McCall94c3b562010-08-18 09:41:07 +00003649 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3650 AbstractUsageInfo Info(*this, Record);
3651 CheckAbstractClassUsage(Info, Record);
3652 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003653
3654 // If this is not an aggregate type and has no user-declared constructor,
3655 // complain about any non-static data members of reference or const scalar
3656 // type, since they will never get initializers.
3657 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003658 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3659 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003660 bool Complained = false;
3661 for (RecordDecl::field_iterator F = Record->field_begin(),
3662 FEnd = Record->field_end();
3663 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003664 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003665 continue;
3666
Douglas Gregor325e5932010-04-15 00:00:53 +00003667 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003668 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003669 if (!Complained) {
3670 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3671 << Record->getTagKind() << Record;
3672 Complained = true;
3673 }
3674
3675 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3676 << F->getType()->isReferenceType()
3677 << F->getDeclName();
3678 }
3679 }
3680 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003681
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003682 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003683 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003684
3685 if (Record->getIdentifier()) {
3686 // C++ [class.mem]p13:
3687 // If T is the name of a class, then each of the following shall have a
3688 // name different from T:
3689 // - every member of every anonymous union that is a member of class T.
3690 //
3691 // C++ [class.mem]p14:
3692 // In addition, if class T has a user-declared constructor (12.1), every
3693 // non-static data member of class T shall have a name different from T.
3694 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003695 R.first != R.second; ++R.first) {
3696 NamedDecl *D = *R.first;
3697 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3698 isa<IndirectFieldDecl>(D)) {
3699 Diag(D->getLocation(), diag::err_member_name_of_class)
3700 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003701 break;
3702 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003703 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003704 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003705
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003706 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003707 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003708 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003709 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003710 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3711 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3712 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003713
3714 // See if a method overloads virtual methods in a base
3715 /// class without overriding any.
3716 if (!Record->isDependentType()) {
3717 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3718 MEnd = Record->method_end();
3719 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003720 if (!(*M)->isStatic())
3721 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003722 }
3723 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003724
Richard Smith9f569cc2011-10-01 02:31:28 +00003725 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3726 // function that is not a constructor declares that member function to be
3727 // const. [...] The class of which that function is a member shall be
3728 // a literal type.
3729 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003730 // If the class has virtual bases, any constexpr members will already have
3731 // been diagnosed by the checks performed on the member declaration, so
3732 // suppress this (less useful) diagnostic.
3733 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3734 !Record->isLiteral() && !Record->getNumVBases()) {
3735 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3736 MEnd = Record->method_end();
3737 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003738 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003739 switch (Record->getTemplateSpecializationKind()) {
3740 case TSK_ImplicitInstantiation:
3741 case TSK_ExplicitInstantiationDeclaration:
3742 case TSK_ExplicitInstantiationDefinition:
3743 // If a template instantiates to a non-literal type, but its members
3744 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003745 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003746 continue;
3747
3748 case TSK_Undeclared:
3749 case TSK_ExplicitSpecialization:
3750 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3751 PDiag(diag::err_constexpr_method_non_literal));
3752 break;
3753 }
3754
3755 // Only produce one error per class.
3756 break;
3757 }
3758 }
3759 }
3760
Sebastian Redlf677ea32011-02-05 19:23:19 +00003761 // Declare inherited constructors. We do this eagerly here because:
3762 // - The standard requires an eager diagnostic for conflicting inherited
3763 // constructors from different classes.
3764 // - The lazy declaration of the other implicit constructors is so as to not
3765 // waste space and performance on classes that are not meant to be
3766 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3767 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003768 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003769
Sean Hunteb88ae52011-05-23 21:07:59 +00003770 if (!Record->isDependentType())
3771 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003772}
3773
3774void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003775 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3776 ME = Record->method_end();
3777 MI != ME; ++MI) {
3778 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3779 switch (getSpecialMember(*MI)) {
3780 case CXXDefaultConstructor:
3781 CheckExplicitlyDefaultedDefaultConstructor(
3782 cast<CXXConstructorDecl>(*MI));
3783 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003784
Sean Huntcb45a0f2011-05-12 22:46:25 +00003785 case CXXDestructor:
3786 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3787 break;
3788
3789 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003790 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3791 break;
3792
Sean Huntcb45a0f2011-05-12 22:46:25 +00003793 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003794 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003795 break;
3796
Sean Hunt82713172011-05-25 23:16:36 +00003797 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003798 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003799 break;
3800
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003801 case CXXMoveAssignment:
3802 CheckExplicitlyDefaultedMoveAssignment(*MI);
3803 break;
3804
3805 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003806 llvm_unreachable("non-special member explicitly defaulted!");
3807 }
Sean Hunt001cad92011-05-10 00:49:42 +00003808 }
3809 }
3810
Sean Hunt001cad92011-05-10 00:49:42 +00003811}
3812
3813void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3814 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3815
3816 // Whether this was the first-declared instance of the constructor.
3817 // This affects whether we implicitly add an exception spec (and, eventually,
3818 // constexpr). It is also ill-formed to explicitly default a constructor such
3819 // that it would be deleted. (C++0x [decl.fct.def.default])
3820 bool First = CD == CD->getCanonicalDecl();
3821
Sean Hunt49634cf2011-05-13 06:10:58 +00003822 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003823 if (CD->getNumParams() != 0) {
3824 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3825 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003826 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003827 }
3828
3829 ImplicitExceptionSpecification Spec
3830 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3831 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003832 if (EPI.ExceptionSpecType == EST_Delayed) {
3833 // Exception specification depends on some deferred part of the class. We'll
3834 // try again when the class's definition has been fully processed.
3835 return;
3836 }
Sean Hunt001cad92011-05-10 00:49:42 +00003837 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3838 *ExceptionType = Context.getFunctionType(
3839 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3840
Richard Smith61802452011-12-22 02:22:31 +00003841 // C++11 [dcl.fct.def.default]p2:
3842 // An explicitly-defaulted function may be declared constexpr only if it
3843 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003844 // Do not apply this rule to templates, since core issue 1358 makes such
3845 // functions always instantiate to constexpr functions.
3846 if (CD->isConstexpr() &&
3847 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003848 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3849 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3850 << CXXDefaultConstructor;
3851 HadError = true;
3852 }
3853 }
3854 // and may have an explicit exception-specification only if it is compatible
3855 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003856 if (CtorType->hasExceptionSpec()) {
3857 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003858 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003859 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003860 PDiag(),
3861 ExceptionType, SourceLocation(),
3862 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003863 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003864 }
Richard Smith61802452011-12-22 02:22:31 +00003865 }
3866
3867 // If a function is explicitly defaulted on its first declaration,
3868 if (First) {
3869 // -- it is implicitly considered to be constexpr if the implicit
3870 // definition would be,
3871 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3872
3873 // -- it is implicitly considered to have the same
3874 // exception-specification as if it had been implicitly declared
3875 //
3876 // FIXME: a compatible, but different, explicit exception specification
3877 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003878 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithe653ba22012-02-26 00:31:33 +00003879
3880 // Such a function is also trivial if the implicitly-declared function
3881 // would have been.
3882 CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
Sean Hunt001cad92011-05-10 00:49:42 +00003883 }
Sean Huntca46d132011-05-12 03:51:48 +00003884
Sean Hunt49634cf2011-05-13 06:10:58 +00003885 if (HadError) {
3886 CD->setInvalidDecl();
3887 return;
3888 }
3889
Sean Hunte16da072011-10-10 06:18:57 +00003890 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003891 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003892 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003893 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003894 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003895 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003896 CD->setInvalidDecl();
3897 }
3898 }
3899}
3900
3901void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3902 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3903
3904 // Whether this was the first-declared instance of the constructor.
3905 bool First = CD == CD->getCanonicalDecl();
3906
3907 bool HadError = false;
3908 if (CD->getNumParams() != 1) {
3909 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3910 << CD->getSourceRange();
3911 HadError = true;
3912 }
3913
3914 ImplicitExceptionSpecification Spec(Context);
3915 bool Const;
3916 llvm::tie(Spec, Const) =
3917 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3918
3919 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3920 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3921 *ExceptionType = Context.getFunctionType(
3922 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3923
3924 // Check for parameter type matching.
3925 // This is a copy ctor so we know it's a cv-qualified reference to T.
3926 QualType ArgType = CtorType->getArgType(0);
3927 if (ArgType->getPointeeType().isVolatileQualified()) {
3928 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3929 HadError = true;
3930 }
3931 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3932 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3933 HadError = true;
3934 }
3935
Richard Smith61802452011-12-22 02:22:31 +00003936 // C++11 [dcl.fct.def.default]p2:
3937 // An explicitly-defaulted function may be declared constexpr only if it
3938 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00003939 // Do not apply this rule to templates, since core issue 1358 makes such
3940 // functions always instantiate to constexpr functions.
3941 if (CD->isConstexpr() &&
3942 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00003943 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3944 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3945 << CXXCopyConstructor;
3946 HadError = true;
3947 }
3948 }
3949 // and may have an explicit exception-specification only if it is compatible
3950 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003951 if (CtorType->hasExceptionSpec()) {
3952 if (CheckEquivalentExceptionSpec(
3953 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003954 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003955 PDiag(),
3956 ExceptionType, SourceLocation(),
3957 CtorType, CD->getLocation())) {
3958 HadError = true;
3959 }
Richard Smith61802452011-12-22 02:22:31 +00003960 }
3961
3962 // If a function is explicitly defaulted on its first declaration,
3963 if (First) {
3964 // -- it is implicitly considered to be constexpr if the implicit
3965 // definition would be,
3966 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3967
3968 // -- it is implicitly considered to have the same
3969 // exception-specification as if it had been implicitly declared, and
3970 //
3971 // FIXME: a compatible, but different, explicit exception specification
3972 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003973 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003974
3975 // -- [...] it shall have the same parameter type as if it had been
3976 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003977 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00003978
3979 // Such a function is also trivial if the implicitly-declared function
3980 // would have been.
3981 CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00003982 }
3983
3984 if (HadError) {
3985 CD->setInvalidDecl();
3986 return;
3987 }
3988
Sean Huntc32d6842011-10-11 04:55:36 +00003989 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003990 if (First) {
3991 CD->setDeletedAsWritten();
3992 } else {
3993 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003994 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003995 CD->setInvalidDecl();
3996 }
Sean Huntca46d132011-05-12 03:51:48 +00003997 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003998}
Sean Hunt001cad92011-05-10 00:49:42 +00003999
Sean Hunt2b188082011-05-14 05:23:28 +00004000void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4001 assert(MD->isExplicitlyDefaulted());
4002
4003 // Whether this was the first-declared instance of the operator
4004 bool First = MD == MD->getCanonicalDecl();
4005
4006 bool HadError = false;
4007 if (MD->getNumParams() != 1) {
4008 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4009 << MD->getSourceRange();
4010 HadError = true;
4011 }
4012
4013 QualType ReturnType =
4014 MD->getType()->getAs<FunctionType>()->getResultType();
4015 if (!ReturnType->isLValueReferenceType() ||
4016 !Context.hasSameType(
4017 Context.getCanonicalType(ReturnType->getPointeeType()),
4018 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4019 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4020 HadError = true;
4021 }
4022
4023 ImplicitExceptionSpecification Spec(Context);
4024 bool Const;
4025 llvm::tie(Spec, Const) =
4026 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4027
4028 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4029 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4030 *ExceptionType = Context.getFunctionType(
4031 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4032
Sean Hunt2b188082011-05-14 05:23:28 +00004033 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004034 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004035 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004036 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004037 } else {
4038 if (ArgType->getPointeeType().isVolatileQualified()) {
4039 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4040 HadError = true;
4041 }
4042 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4043 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4044 HadError = true;
4045 }
Sean Hunt2b188082011-05-14 05:23:28 +00004046 }
Sean Huntbe631222011-05-17 20:44:43 +00004047
Sean Hunt2b188082011-05-14 05:23:28 +00004048 if (OperType->getTypeQuals()) {
4049 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4050 HadError = true;
4051 }
4052
4053 if (OperType->hasExceptionSpec()) {
4054 if (CheckEquivalentExceptionSpec(
4055 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004056 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004057 PDiag(),
4058 ExceptionType, SourceLocation(),
4059 OperType, MD->getLocation())) {
4060 HadError = true;
4061 }
Richard Smith61802452011-12-22 02:22:31 +00004062 }
4063 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004064 // We set the declaration to have the computed exception spec here.
4065 // We duplicate the one parameter type.
4066 EPI.RefQualifier = OperType->getRefQualifier();
4067 EPI.ExtInfo = OperType->getExtInfo();
4068 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004069
4070 // Such a function is also trivial if the implicitly-declared function
4071 // would have been.
4072 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
Sean Hunt2b188082011-05-14 05:23:28 +00004073 }
4074
4075 if (HadError) {
4076 MD->setInvalidDecl();
4077 return;
4078 }
4079
Richard Smith7d5088a2012-02-18 02:02:13 +00004080 if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
Sean Hunt2b188082011-05-14 05:23:28 +00004081 if (First) {
4082 MD->setDeletedAsWritten();
4083 } else {
4084 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004085 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004086 MD->setInvalidDecl();
4087 }
4088 }
4089}
4090
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004091void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4092 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4093
4094 // Whether this was the first-declared instance of the constructor.
4095 bool First = CD == CD->getCanonicalDecl();
4096
4097 bool HadError = false;
4098 if (CD->getNumParams() != 1) {
4099 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4100 << CD->getSourceRange();
4101 HadError = true;
4102 }
4103
4104 ImplicitExceptionSpecification Spec(
4105 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4106
4107 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4108 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4109 *ExceptionType = Context.getFunctionType(
4110 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4111
4112 // Check for parameter type matching.
4113 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4114 QualType ArgType = CtorType->getArgType(0);
4115 if (ArgType->getPointeeType().isVolatileQualified()) {
4116 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4117 HadError = true;
4118 }
4119 if (ArgType->getPointeeType().isConstQualified()) {
4120 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4121 HadError = true;
4122 }
4123
Richard Smith61802452011-12-22 02:22:31 +00004124 // C++11 [dcl.fct.def.default]p2:
4125 // An explicitly-defaulted function may be declared constexpr only if it
4126 // would have been implicitly declared as constexpr,
Richard Smitheb273b72012-02-14 02:33:50 +00004127 // Do not apply this rule to templates, since core issue 1358 makes such
4128 // functions always instantiate to constexpr functions.
4129 if (CD->isConstexpr() &&
4130 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smith61802452011-12-22 02:22:31 +00004131 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4132 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4133 << CXXMoveConstructor;
4134 HadError = true;
4135 }
4136 }
4137 // and may have an explicit exception-specification only if it is compatible
4138 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004139 if (CtorType->hasExceptionSpec()) {
4140 if (CheckEquivalentExceptionSpec(
4141 PDiag(diag::err_incorrect_defaulted_exception_spec)
4142 << CXXMoveConstructor,
4143 PDiag(),
4144 ExceptionType, SourceLocation(),
4145 CtorType, CD->getLocation())) {
4146 HadError = true;
4147 }
Richard Smith61802452011-12-22 02:22:31 +00004148 }
4149
4150 // If a function is explicitly defaulted on its first declaration,
4151 if (First) {
4152 // -- it is implicitly considered to be constexpr if the implicit
4153 // definition would be,
4154 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4155
4156 // -- it is implicitly considered to have the same
4157 // exception-specification as if it had been implicitly declared, and
4158 //
4159 // FIXME: a compatible, but different, explicit exception specification
4160 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004161 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004162
4163 // -- [...] it shall have the same parameter type as if it had been
4164 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004165 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004166
4167 // Such a function is also trivial if the implicitly-declared function
4168 // would have been.
4169 CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004170 }
4171
4172 if (HadError) {
4173 CD->setInvalidDecl();
4174 return;
4175 }
4176
Sean Hunt769bb2d2011-10-11 06:43:29 +00004177 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004178 if (First) {
4179 CD->setDeletedAsWritten();
4180 } else {
4181 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4182 << CXXMoveConstructor;
4183 CD->setInvalidDecl();
4184 }
4185 }
4186}
4187
4188void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4189 assert(MD->isExplicitlyDefaulted());
4190
4191 // Whether this was the first-declared instance of the operator
4192 bool First = MD == MD->getCanonicalDecl();
4193
4194 bool HadError = false;
4195 if (MD->getNumParams() != 1) {
4196 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4197 << MD->getSourceRange();
4198 HadError = true;
4199 }
4200
4201 QualType ReturnType =
4202 MD->getType()->getAs<FunctionType>()->getResultType();
4203 if (!ReturnType->isLValueReferenceType() ||
4204 !Context.hasSameType(
4205 Context.getCanonicalType(ReturnType->getPointeeType()),
4206 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4207 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4208 HadError = true;
4209 }
4210
4211 ImplicitExceptionSpecification Spec(
4212 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4213
4214 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4215 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4216 *ExceptionType = Context.getFunctionType(
4217 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4218
4219 QualType ArgType = OperType->getArgType(0);
4220 if (!ArgType->isRValueReferenceType()) {
4221 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4222 HadError = true;
4223 } else {
4224 if (ArgType->getPointeeType().isVolatileQualified()) {
4225 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4226 HadError = true;
4227 }
4228 if (ArgType->getPointeeType().isConstQualified()) {
4229 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4230 HadError = true;
4231 }
4232 }
4233
4234 if (OperType->getTypeQuals()) {
4235 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4236 HadError = true;
4237 }
4238
4239 if (OperType->hasExceptionSpec()) {
4240 if (CheckEquivalentExceptionSpec(
4241 PDiag(diag::err_incorrect_defaulted_exception_spec)
4242 << CXXMoveAssignment,
4243 PDiag(),
4244 ExceptionType, SourceLocation(),
4245 OperType, MD->getLocation())) {
4246 HadError = true;
4247 }
Richard Smith61802452011-12-22 02:22:31 +00004248 }
4249 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004250 // We set the declaration to have the computed exception spec here.
4251 // We duplicate the one parameter type.
4252 EPI.RefQualifier = OperType->getRefQualifier();
4253 EPI.ExtInfo = OperType->getExtInfo();
4254 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004255
4256 // Such a function is also trivial if the implicitly-declared function
4257 // would have been.
4258 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004259 }
4260
4261 if (HadError) {
4262 MD->setInvalidDecl();
4263 return;
4264 }
4265
Richard Smith7d5088a2012-02-18 02:02:13 +00004266 if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004267 if (First) {
4268 MD->setDeletedAsWritten();
4269 } else {
4270 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4271 << CXXMoveAssignment;
4272 MD->setInvalidDecl();
4273 }
4274 }
4275}
4276
Sean Huntcb45a0f2011-05-12 22:46:25 +00004277void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4278 assert(DD->isExplicitlyDefaulted());
4279
4280 // Whether this was the first-declared instance of the destructor.
4281 bool First = DD == DD->getCanonicalDecl();
4282
4283 ImplicitExceptionSpecification Spec
4284 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4285 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4286 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4287 *ExceptionType = Context.getFunctionType(
4288 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4289
4290 if (DtorType->hasExceptionSpec()) {
4291 if (CheckEquivalentExceptionSpec(
4292 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004293 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004294 PDiag(),
4295 ExceptionType, SourceLocation(),
4296 DtorType, DD->getLocation())) {
4297 DD->setInvalidDecl();
4298 return;
4299 }
Richard Smith61802452011-12-22 02:22:31 +00004300 }
4301 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004302 // We set the declaration to have the computed exception spec here.
4303 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004304 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004305 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smithe653ba22012-02-26 00:31:33 +00004306
4307 // Such a function is also trivial if the implicitly-declared function
4308 // would have been.
4309 DD->setTrivial(DD->getParent()->hasTrivialDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00004310 }
4311
Richard Smith7d5088a2012-02-18 02:02:13 +00004312 if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004313 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004314 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004315 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004316 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004317 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004318 DD->setInvalidDecl();
4319 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004320 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321}
4322
Richard Smith7d5088a2012-02-18 02:02:13 +00004323namespace {
4324struct SpecialMemberDeletionInfo {
4325 Sema &S;
4326 CXXMethodDecl *MD;
4327 Sema::CXXSpecialMember CSM;
4328
4329 // Properties of the special member, computed for convenience.
4330 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4331 SourceLocation Loc;
4332
4333 bool AllFieldsAreConst;
4334
4335 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4336 Sema::CXXSpecialMember CSM)
4337 : S(S), MD(MD), CSM(CSM),
4338 IsConstructor(false), IsAssignment(false), IsMove(false),
4339 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4340 AllFieldsAreConst(true) {
4341 switch (CSM) {
4342 case Sema::CXXDefaultConstructor:
4343 case Sema::CXXCopyConstructor:
4344 IsConstructor = true;
4345 break;
4346 case Sema::CXXMoveConstructor:
4347 IsConstructor = true;
4348 IsMove = true;
4349 break;
4350 case Sema::CXXCopyAssignment:
4351 IsAssignment = true;
4352 break;
4353 case Sema::CXXMoveAssignment:
4354 IsAssignment = true;
4355 IsMove = true;
4356 break;
4357 case Sema::CXXDestructor:
4358 break;
4359 case Sema::CXXInvalid:
4360 llvm_unreachable("invalid special member kind");
4361 }
4362
4363 if (MD->getNumParams()) {
4364 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4365 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4366 }
4367 }
4368
4369 bool inUnion() const { return MD->getParent()->isUnion(); }
4370
4371 /// Look up the corresponding special member in the given class.
4372 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4373 unsigned TQ = MD->getTypeQualifiers();
4374 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4375 MD->getRefQualifier() == RQ_RValue,
4376 TQ & Qualifiers::Const,
4377 TQ & Qualifiers::Volatile);
4378 }
4379
Richard Smith9a561d52012-02-26 09:11:52 +00004380 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, FieldDecl *Field);
4381
Richard Smith7d5088a2012-02-18 02:02:13 +00004382 bool shouldDeleteForBase(CXXRecordDecl *BaseDecl, bool IsVirtualBase);
4383 bool shouldDeleteForField(FieldDecl *FD);
4384 bool shouldDeleteForAllConstMembers();
4385};
4386}
4387
Richard Smith9a561d52012-02-26 09:11:52 +00004388/// Check whether we should delete a special member function due to having a
4389/// direct or virtual base class or static data member of class type M.
4390bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4391 CXXRecordDecl *Class, FieldDecl *Field) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004392 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
4393 // -- any direct or virtual base class [...] has a type with a destructor
4394 // that is deleted or inaccessible
4395 if (!IsAssignment) {
Richard Smith9a561d52012-02-26 09:11:52 +00004396 CXXDestructorDecl *Dtor = S.LookupDestructor(Class);
4397 if (Dtor->isDeleted())
Richard Smith7d5088a2012-02-18 02:02:13 +00004398 return true;
Richard Smith9a561d52012-02-26 09:11:52 +00004399 if (S.CheckDestructorAccess(Loc, Dtor, S.PDiag()) != Sema::AR_accessible)
4400 return true;
4401
4402 // C++11 [class.dtor]p5:
4403 // -- X is a union-like class that has a variant member with a non-trivial
4404 // destructor
4405 if (CSM == Sema::CXXDestructor && Field && Field->getParent()->isUnion() &&
4406 !Dtor->isTrivial())
Richard Smith7d5088a2012-02-18 02:02:13 +00004407 return true;
4408 }
4409
4410 // C++11 [class.ctor]p5:
4411 // -- any direct or virtual base class [...] has class type M [...] and
4412 // either M has no default constructor or overload resolution as applied
4413 // to M's default constructor results in an ambiguity or in a function
4414 // that is deleted or inaccessible
4415 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4416 // -- a direct or virtual base class B that cannot be copied/moved because
4417 // overload resolution, as applied to B's corresponding special member,
4418 // results in an ambiguity or a function that is deleted or inaccessible
4419 // from the defaulted special member
Richard Smith9a561d52012-02-26 09:11:52 +00004420 // FIXME: in-class initializers should be handled here
Richard Smith7d5088a2012-02-18 02:02:13 +00004421 if (CSM != Sema::CXXDestructor) {
Richard Smith9a561d52012-02-26 09:11:52 +00004422 Sema::SpecialMemberOverloadResult *SMOR = lookupIn(Class);
Richard Smith7d5088a2012-02-18 02:02:13 +00004423 if (!SMOR->hasSuccess())
4424 return true;
4425
Richard Smith9a561d52012-02-26 09:11:52 +00004426 CXXMethodDecl *Member = SMOR->getMethod();
4427 // A member of a union must have a trivial corresponding special member.
4428 if (Field && Field->getParent()->isUnion() && !Member->isTrivial())
4429 return true;
4430
Richard Smith7d5088a2012-02-18 02:02:13 +00004431 if (IsConstructor) {
Richard Smith9a561d52012-02-26 09:11:52 +00004432 CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Member);
4433 if (S.CheckConstructorAccess(Loc, Ctor, Ctor->getAccess(), S.PDiag())
4434 != Sema::AR_accessible)
Richard Smith7d5088a2012-02-18 02:02:13 +00004435 return true;
4436
4437 // -- for the move constructor, a [...] direct or virtual base class with
4438 // a type that does not have a move constructor and is not trivially
4439 // copyable.
Richard Smith9a561d52012-02-26 09:11:52 +00004440 if (IsMove && !Ctor->isMoveConstructor() && !Class->isTriviallyCopyable())
Richard Smith7d5088a2012-02-18 02:02:13 +00004441 return true;
4442 } else {
4443 assert(IsAssignment && "unexpected kind of special member");
Richard Smith9a561d52012-02-26 09:11:52 +00004444 if (S.CheckDirectMemberAccess(Loc, Member, S.PDiag())
Richard Smith7d5088a2012-02-18 02:02:13 +00004445 != Sema::AR_accessible)
4446 return true;
4447
4448 // -- for the move assignment operator, a direct base class with a type
4449 // that does not have a move assignment operator and is not trivially
4450 // copyable.
Richard Smith9a561d52012-02-26 09:11:52 +00004451 if (IsMove && !Member->isMoveAssignmentOperator() &&
4452 !Class->isTriviallyCopyable())
Richard Smith7d5088a2012-02-18 02:02:13 +00004453 return true;
4454 }
4455 }
4456
Richard Smith9a561d52012-02-26 09:11:52 +00004457 return false;
4458}
4459
4460/// Check whether we should delete a special member function due to the class
4461/// having a particular direct or virtual base class.
4462bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXRecordDecl *BaseDecl,
4463 bool IsVirtualBase) {
4464 // C++11 [class.copy]p23:
4465 // -- for the move assignment operator, any direct or indirect virtual
4466 // base class.
4467 if (CSM == Sema::CXXMoveAssignment && IsVirtualBase)
4468 return true;
4469
4470 if (shouldDeleteForClassSubobject(BaseDecl, 0))
4471 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004472
4473 return false;
4474}
4475
4476/// Check whether we should delete a special member function due to the class
4477/// having a particular non-static data member.
4478bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4479 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4480 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4481
4482 if (CSM == Sema::CXXDefaultConstructor) {
4483 // For a default constructor, all references must be initialized in-class
4484 // and, if a union, it must have a non-const member.
4485 if (FieldType->isReferenceType() && !FD->hasInClassInitializer())
4486 return true;
4487
4488 if (inUnion() && !FieldType.isConstQualified())
4489 AllFieldsAreConst = false;
Richard Smith79363f52012-02-27 06:07:25 +00004490
4491 // C++11 [class.ctor]p5: any non-variant non-static data member of
4492 // const-qualified type (or array thereof) with no
4493 // brace-or-equal-initializer does not have a user-provided default
4494 // constructor.
4495 if (!inUnion() && FieldType.isConstQualified() &&
4496 !FD->hasInClassInitializer() &&
4497 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor()))
4498 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004499 } else if (CSM == Sema::CXXCopyConstructor) {
4500 // For a copy constructor, data members must not be of rvalue reference
4501 // type.
4502 if (FieldType->isRValueReferenceType())
4503 return true;
4504 } else if (IsAssignment) {
4505 // For an assignment operator, data members must not be of reference type.
4506 if (FieldType->isReferenceType())
4507 return true;
4508 }
4509
4510 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004511 // Some additional restrictions exist on the variant members.
4512 if (!inUnion() && FieldRecord->isUnion() &&
4513 FieldRecord->isAnonymousStructOrUnion()) {
4514 bool AllVariantFieldsAreConst = true;
4515
4516 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4517 UE = FieldRecord->field_end();
4518 UI != UE; ++UI) {
4519 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004520
4521 if (!UnionFieldType.isConstQualified())
4522 AllVariantFieldsAreConst = false;
4523
Richard Smith9a561d52012-02-26 09:11:52 +00004524 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4525 if (UnionFieldRecord &&
4526 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4527 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004528 }
4529
4530 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004531 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4532 FieldRecord->field_begin() != FieldRecord->field_end())
Richard Smith7d5088a2012-02-18 02:02:13 +00004533 return true;
4534
4535 // Don't try to initialize the anonymous union
4536 // This is technically non-conformant, but sanity demands it.
4537 return false;
4538 }
4539
Richard Smith9a561d52012-02-26 09:11:52 +00004540 // When checking a constructor, the field's destructor must be accessible
4541 // and not deleted.
4542 if (IsConstructor) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004543 CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4544 if (FieldDtor->isDeleted())
4545 return true;
4546 if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4547 Sema::AR_accessible)
4548 return true;
4549 }
4550
4551 // Check that the corresponding member of the field is accessible,
4552 // unique, and non-deleted. We don't do this if it has an explicit
4553 // initialization when default-constructing.
Richard Smith9a561d52012-02-26 09:11:52 +00004554 if (!(CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004555 Sema::SpecialMemberOverloadResult *SMOR = lookupIn(FieldRecord);
4556 if (!SMOR->hasSuccess())
4557 return true;
4558
4559 CXXMethodDecl *FieldMember = SMOR->getMethod();
Richard Smith9a561d52012-02-26 09:11:52 +00004560
4561 // We need the corresponding member of a union to be trivial so that
4562 // we can safely process all members simultaneously.
4563 if (inUnion() && !FieldMember->isTrivial())
4564 return true;
4565
Richard Smith7d5088a2012-02-18 02:02:13 +00004566 if (IsConstructor) {
4567 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4568 if (S.CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4569 S.PDiag()) != Sema::AR_accessible)
4570 return true;
4571
4572 // For a move operation, the corresponding operation must actually
4573 // be a move operation (and not a copy selected by overload
4574 // resolution) unless we are working on a trivially copyable class.
4575 if (IsMove && !FieldCtor->isMoveConstructor() &&
4576 !FieldRecord->isTriviallyCopyable())
4577 return true;
Richard Smith9a561d52012-02-26 09:11:52 +00004578 } else if (CSM == Sema::CXXDestructor) {
4579 CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4580 if (FieldDtor->isDeleted())
4581 return true;
4582 if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4583 Sema::AR_accessible)
4584 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004585 } else {
4586 assert(IsAssignment && "unexpected kind of special member");
4587 if (S.CheckDirectMemberAccess(Loc, FieldMember, S.PDiag())
4588 != Sema::AR_accessible)
4589 return true;
4590
4591 // -- for the move assignment operator, a non-static data member with a
4592 // type that does not have a move assignment operator and is not
4593 // trivially copyable.
4594 if (IsMove && !FieldMember->isMoveAssignmentOperator() &&
4595 !FieldRecord->isTriviallyCopyable())
4596 return true;
4597 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004598 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004599 } else if (IsAssignment && FieldType.isConstQualified()) {
4600 // C++11 [class.copy]p23:
4601 // -- a non-static data member of const non-class type (or array thereof)
4602 return true;
4603 }
4604
4605 return false;
4606}
4607
4608/// C++11 [class.ctor] p5:
4609/// A defaulted default constructor for a class X is defined as deleted if
4610/// X is a union and all of its variant members are of const-qualified type.
4611bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004612 // This is a silly definition, because it gives an empty union a deleted
4613 // default constructor. Don't do that.
4614 return CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4615 (MD->getParent()->field_begin() != MD->getParent()->field_end());
Richard Smith7d5088a2012-02-18 02:02:13 +00004616}
4617
4618/// Determine whether a defaulted special member function should be defined as
4619/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4620/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Sean Hunte16da072011-10-10 06:18:57 +00004621bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4622 assert(!MD->isInvalidDecl());
4623 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004624 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004625 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004626 return false;
4627
Richard Smith9a561d52012-02-26 09:11:52 +00004628 // FIXME: Provide the ability to diagnose why a special member was deleted.
4629
Richard Smith7d5088a2012-02-18 02:02:13 +00004630 // C++11 [expr.lambda.prim]p19:
4631 // The closure type associated with a lambda-expression has a
4632 // deleted (8.4.3) default constructor and a deleted copy
4633 // assignment operator.
4634 if (RD->isLambda() &&
4635 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment))
4636 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004637
Richard Smith9a561d52012-02-26 09:11:52 +00004638 // C++11 [class.dtor]p5:
4639 // -- for a virtual destructor, lookup of the non-array deallocation function
4640 // results in an ambiguity or in a function that is deleted or inaccessible
4641 if (CSM == Sema::CXXDestructor && MD->isVirtual()) {
4642 FunctionDecl *OperatorDelete = 0;
4643 DeclarationName Name =
4644 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4645 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4646 OperatorDelete, false))
4647 return true;
4648 }
4649
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 // For an anonymous struct or union, the copy and assignment special members
4651 // will never be used, so skip the check. For an anonymous union declared at
4652 // namespace scope, the constructor and destructor are used.
4653 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4654 RD->isAnonymousStructOrUnion())
4655 return false;
Sean Hunt71a682f2011-05-18 03:41:58 +00004656
Sean Huntc32d6842011-10-11 04:55:36 +00004657 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004658 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004659
Richard Smith7d5088a2012-02-18 02:02:13 +00004660 SpecialMemberDeletionInfo SMI(*this, MD, CSM);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004661
Sean Huntcdee3fe2011-05-11 22:34:38 +00004662 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004663 BE = RD->bases_end(); BI != BE; ++BI)
4664 if (!BI->isVirtual() &&
4665 SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), false))
4666 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004667
4668 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 BE = RD->vbases_end(); BI != BE; ++BI)
4670 if (SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), true))
4671 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004672
4673 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004674 FE = RD->field_end(); FI != FE; ++FI)
4675 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4676 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004677 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004678
Richard Smith7d5088a2012-02-18 02:02:13 +00004679 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004680 return true;
4681
4682 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004683}
4684
4685/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004686namespace {
4687 struct FindHiddenVirtualMethodData {
4688 Sema *S;
4689 CXXMethodDecl *Method;
4690 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004691 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004692 };
4693}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004694
4695/// \brief Member lookup function that determines whether a given C++
4696/// method overloads virtual methods in a base class without overriding any,
4697/// to be used with CXXRecordDecl::lookupInBases().
4698static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4699 CXXBasePath &Path,
4700 void *UserData) {
4701 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4702
4703 FindHiddenVirtualMethodData &Data
4704 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4705
4706 DeclarationName Name = Data.Method->getDeclName();
4707 assert(Name.getNameKind() == DeclarationName::Identifier);
4708
4709 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004710 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004711 for (Path.Decls = BaseRecord->lookup(Name);
4712 Path.Decls.first != Path.Decls.second;
4713 ++Path.Decls.first) {
4714 NamedDecl *D = *Path.Decls.first;
4715 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004716 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004717 foundSameNameMethod = true;
4718 // Interested only in hidden virtual methods.
4719 if (!MD->isVirtual())
4720 continue;
4721 // If the method we are checking overrides a method from its base
4722 // don't warn about the other overloaded methods.
4723 if (!Data.S->IsOverload(Data.Method, MD, false))
4724 return true;
4725 // Collect the overload only if its hidden.
4726 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4727 overloadedMethods.push_back(MD);
4728 }
4729 }
4730
4731 if (foundSameNameMethod)
4732 Data.OverloadedMethods.append(overloadedMethods.begin(),
4733 overloadedMethods.end());
4734 return foundSameNameMethod;
4735}
4736
4737/// \brief See if a method overloads virtual methods in a base class without
4738/// overriding any.
4739void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4740 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004741 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004742 return;
4743 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4744 return;
4745
4746 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4747 /*bool RecordPaths=*/false,
4748 /*bool DetectVirtual=*/false);
4749 FindHiddenVirtualMethodData Data;
4750 Data.Method = MD;
4751 Data.S = this;
4752
4753 // Keep the base methods that were overriden or introduced in the subclass
4754 // by 'using' in a set. A base method not in this set is hidden.
4755 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4756 res.first != res.second; ++res.first) {
4757 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4758 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4759 E = MD->end_overridden_methods();
4760 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004761 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004762 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4763 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004764 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004765 }
4766
4767 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4768 !Data.OverloadedMethods.empty()) {
4769 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4770 << MD << (Data.OverloadedMethods.size() > 1);
4771
4772 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4773 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4774 Diag(overloadedMD->getLocation(),
4775 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4776 }
4777 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004778}
4779
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004780void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004781 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004782 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004783 SourceLocation RBrac,
4784 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004785 if (!TagDecl)
4786 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004787
Douglas Gregor42af25f2009-05-11 19:58:34 +00004788 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004789
David Blaikie77b6de02011-09-22 02:58:26 +00004790 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004791 // strict aliasing violation!
4792 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004793 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004794
Douglas Gregor23c94db2010-07-02 17:43:08 +00004795 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004796 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004797}
4798
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004799/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4800/// special functions, such as the default constructor, copy
4801/// constructor, or destructor, to the given C++ class (C++
4802/// [special]p1). This routine can only be executed just before the
4803/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004804void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004805 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004806 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004807
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004808 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004809 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004810
Richard Smithb701d3d2011-12-24 21:56:24 +00004811 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4812 ++ASTContext::NumImplicitMoveConstructors;
4813
Douglas Gregora376d102010-07-02 21:50:04 +00004814 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4815 ++ASTContext::NumImplicitCopyAssignmentOperators;
4816
4817 // If we have a dynamic class, then the copy assignment operator may be
4818 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4819 // it shows up in the right place in the vtable and that we diagnose
4820 // problems with the implicit exception specification.
4821 if (ClassDecl->isDynamicClass())
4822 DeclareImplicitCopyAssignment(ClassDecl);
4823 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004824
Richard Smithb701d3d2011-12-24 21:56:24 +00004825 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
4826 ++ASTContext::NumImplicitMoveAssignmentOperators;
4827
4828 // Likewise for the move assignment operator.
4829 if (ClassDecl->isDynamicClass())
4830 DeclareImplicitMoveAssignment(ClassDecl);
4831 }
4832
Douglas Gregor4923aa22010-07-02 20:37:36 +00004833 if (!ClassDecl->hasUserDeclaredDestructor()) {
4834 ++ASTContext::NumImplicitDestructors;
4835
4836 // If we have a dynamic class, then the destructor may be virtual, so we
4837 // have to declare the destructor immediately. This ensures that, e.g., it
4838 // shows up in the right place in the vtable and that we diagnose problems
4839 // with the implicit exception specification.
4840 if (ClassDecl->isDynamicClass())
4841 DeclareImplicitDestructor(ClassDecl);
4842 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004843}
4844
Francois Pichet8387e2a2011-04-22 22:18:13 +00004845void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4846 if (!D)
4847 return;
4848
4849 int NumParamList = D->getNumTemplateParameterLists();
4850 for (int i = 0; i < NumParamList; i++) {
4851 TemplateParameterList* Params = D->getTemplateParameterList(i);
4852 for (TemplateParameterList::iterator Param = Params->begin(),
4853 ParamEnd = Params->end();
4854 Param != ParamEnd; ++Param) {
4855 NamedDecl *Named = cast<NamedDecl>(*Param);
4856 if (Named->getDeclName()) {
4857 S->AddDecl(Named);
4858 IdResolver.AddDecl(Named);
4859 }
4860 }
4861 }
4862}
4863
John McCalld226f652010-08-21 09:40:31 +00004864void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004865 if (!D)
4866 return;
4867
4868 TemplateParameterList *Params = 0;
4869 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4870 Params = Template->getTemplateParameters();
4871 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4872 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4873 Params = PartialSpec->getTemplateParameters();
4874 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004875 return;
4876
Douglas Gregor6569d682009-05-27 23:11:45 +00004877 for (TemplateParameterList::iterator Param = Params->begin(),
4878 ParamEnd = Params->end();
4879 Param != ParamEnd; ++Param) {
4880 NamedDecl *Named = cast<NamedDecl>(*Param);
4881 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004882 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004883 IdResolver.AddDecl(Named);
4884 }
4885 }
4886}
4887
John McCalld226f652010-08-21 09:40:31 +00004888void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004889 if (!RecordD) return;
4890 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004891 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004892 PushDeclContext(S, Record);
4893}
4894
John McCalld226f652010-08-21 09:40:31 +00004895void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004896 if (!RecordD) return;
4897 PopDeclContext();
4898}
4899
Douglas Gregor72b505b2008-12-16 21:30:33 +00004900/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4901/// parsing a top-level (non-nested) C++ class, and we are now
4902/// parsing those parts of the given Method declaration that could
4903/// not be parsed earlier (C++ [class.mem]p2), such as default
4904/// arguments. This action should enter the scope of the given
4905/// Method declaration as if we had just parsed the qualified method
4906/// name. However, it should not bring the parameters into scope;
4907/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004908void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004909}
4910
4911/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4912/// C++ method declaration. We're (re-)introducing the given
4913/// function parameter into scope for use in parsing later parts of
4914/// the method declaration. For example, we could see an
4915/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004916void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004917 if (!ParamD)
4918 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004919
John McCalld226f652010-08-21 09:40:31 +00004920 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004921
4922 // If this parameter has an unparsed default argument, clear it out
4923 // to make way for the parsed default argument.
4924 if (Param->hasUnparsedDefaultArg())
4925 Param->setDefaultArg(0);
4926
John McCalld226f652010-08-21 09:40:31 +00004927 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004928 if (Param->getDeclName())
4929 IdResolver.AddDecl(Param);
4930}
4931
4932/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4933/// processing the delayed method declaration for Method. The method
4934/// declaration is now considered finished. There may be a separate
4935/// ActOnStartOfFunctionDef action later (not necessarily
4936/// immediately!) for this method, if it was also defined inside the
4937/// class body.
John McCalld226f652010-08-21 09:40:31 +00004938void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004939 if (!MethodD)
4940 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004942 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004943
John McCalld226f652010-08-21 09:40:31 +00004944 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004945
4946 // Now that we have our default arguments, check the constructor
4947 // again. It could produce additional diagnostics or affect whether
4948 // the class has implicitly-declared destructors, among other
4949 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004950 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4951 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004952
4953 // Check the default arguments, which we may have added.
4954 if (!Method->isInvalidDecl())
4955 CheckCXXDefaultArguments(Method);
4956}
4957
Douglas Gregor42a552f2008-11-05 20:51:48 +00004958/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004959/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004960/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004961/// emit diagnostics and set the invalid bit to true. In any case, the type
4962/// will be updated to reflect a well-formed type for the constructor and
4963/// returned.
4964QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004965 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004966 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004967
4968 // C++ [class.ctor]p3:
4969 // A constructor shall not be virtual (10.3) or static (9.4). A
4970 // constructor can be invoked for a const, volatile or const
4971 // volatile object. A constructor shall not be declared const,
4972 // volatile, or const volatile (9.3.2).
4973 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004974 if (!D.isInvalidType())
4975 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4976 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4977 << SourceRange(D.getIdentifierLoc());
4978 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004979 }
John McCalld931b082010-08-26 03:08:43 +00004980 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004981 if (!D.isInvalidType())
4982 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4983 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4984 << SourceRange(D.getIdentifierLoc());
4985 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004986 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004987 }
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004990 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004991 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4993 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004994 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4996 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004997 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4999 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005000 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005001 }
Mike Stump1eb44332009-09-09 15:08:12 +00005002
Douglas Gregorc938c162011-01-26 05:01:58 +00005003 // C++0x [class.ctor]p4:
5004 // A constructor shall not be declared with a ref-qualifier.
5005 if (FTI.hasRefQualifier()) {
5006 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5007 << FTI.RefQualifierIsLValueRef
5008 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5009 D.setInvalidType();
5010 }
5011
Douglas Gregor42a552f2008-11-05 20:51:48 +00005012 // Rebuild the function type "R" without any type qualifiers (in
5013 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005014 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005015 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005016 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5017 return R;
5018
5019 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5020 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005021 EPI.RefQualifier = RQ_None;
5022
Chris Lattner65401802009-04-25 08:28:21 +00005023 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005024 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005025}
5026
Douglas Gregor72b505b2008-12-16 21:30:33 +00005027/// CheckConstructor - Checks a fully-formed constructor for
5028/// well-formedness, issuing any diagnostics required. Returns true if
5029/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005030void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005031 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005032 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5033 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005034 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005035
5036 // C++ [class.copy]p3:
5037 // A declaration of a constructor for a class X is ill-formed if
5038 // its first parameter is of type (optionally cv-qualified) X and
5039 // either there are no other parameters or else all other
5040 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005041 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005042 ((Constructor->getNumParams() == 1) ||
5043 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005044 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5045 Constructor->getTemplateSpecializationKind()
5046 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005047 QualType ParamType = Constructor->getParamDecl(0)->getType();
5048 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5049 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005050 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005051 const char *ConstRef
5052 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5053 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005054 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005055 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005056
5057 // FIXME: Rather that making the constructor invalid, we should endeavor
5058 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005059 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005060 }
5061 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005062}
5063
John McCall15442822010-08-04 01:04:25 +00005064/// CheckDestructor - Checks a fully-formed destructor definition for
5065/// well-formedness, issuing any diagnostics required. Returns true
5066/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005067bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005068 CXXRecordDecl *RD = Destructor->getParent();
5069
5070 if (Destructor->isVirtual()) {
5071 SourceLocation Loc;
5072
5073 if (!Destructor->isImplicit())
5074 Loc = Destructor->getLocation();
5075 else
5076 Loc = RD->getLocation();
5077
5078 // If we have a virtual destructor, look up the deallocation function
5079 FunctionDecl *OperatorDelete = 0;
5080 DeclarationName Name =
5081 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005082 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005083 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005084
Eli Friedman5f2987c2012-02-02 03:46:19 +00005085 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005086
5087 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005088 }
Anders Carlsson37909802009-11-30 21:24:50 +00005089
5090 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005091}
5092
Mike Stump1eb44332009-09-09 15:08:12 +00005093static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005094FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5095 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5096 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005097 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005098}
5099
Douglas Gregor42a552f2008-11-05 20:51:48 +00005100/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5101/// the well-formednes of the destructor declarator @p D with type @p
5102/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005103/// emit diagnostics and set the declarator to invalid. Even if this happens,
5104/// will be updated to reflect a well-formed type for the destructor and
5105/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005106QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005107 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005108 // C++ [class.dtor]p1:
5109 // [...] A typedef-name that names a class is a class-name
5110 // (7.1.3); however, a typedef-name that names a class shall not
5111 // be used as the identifier in the declarator for a destructor
5112 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005113 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005114 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005115 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005116 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005117 else if (const TemplateSpecializationType *TST =
5118 DeclaratorType->getAs<TemplateSpecializationType>())
5119 if (TST->isTypeAlias())
5120 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5121 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005122
5123 // C++ [class.dtor]p2:
5124 // A destructor is used to destroy objects of its class type. A
5125 // destructor takes no parameters, and no return type can be
5126 // specified for it (not even void). The address of a destructor
5127 // shall not be taken. A destructor shall not be static. A
5128 // destructor can be invoked for a const, volatile or const
5129 // volatile object. A destructor shall not be declared const,
5130 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005131 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005132 if (!D.isInvalidType())
5133 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5134 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005135 << SourceRange(D.getIdentifierLoc())
5136 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5137
John McCalld931b082010-08-26 03:08:43 +00005138 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005139 }
Chris Lattner65401802009-04-25 08:28:21 +00005140 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005141 // Destructors don't have return types, but the parser will
5142 // happily parse something like:
5143 //
5144 // class X {
5145 // float ~X();
5146 // };
5147 //
5148 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005149 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5150 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5151 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005152 }
Mike Stump1eb44332009-09-09 15:08:12 +00005153
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005154 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005155 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005156 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005157 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5158 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005159 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005160 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5161 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005162 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005163 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5164 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005165 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005166 }
5167
Douglas Gregorc938c162011-01-26 05:01:58 +00005168 // C++0x [class.dtor]p2:
5169 // A destructor shall not be declared with a ref-qualifier.
5170 if (FTI.hasRefQualifier()) {
5171 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5172 << FTI.RefQualifierIsLValueRef
5173 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5174 D.setInvalidType();
5175 }
5176
Douglas Gregor42a552f2008-11-05 20:51:48 +00005177 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005178 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005179 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5180
5181 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005182 FTI.freeArgs();
5183 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005184 }
5185
Mike Stump1eb44332009-09-09 15:08:12 +00005186 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005187 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005188 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005189 D.setInvalidType();
5190 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005191
5192 // Rebuild the function type "R" without any type qualifiers or
5193 // parameters (in case any of the errors above fired) and with
5194 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005195 // types.
John McCalle23cf432010-12-14 08:05:40 +00005196 if (!D.isInvalidType())
5197 return R;
5198
Douglas Gregord92ec472010-07-01 05:10:53 +00005199 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005200 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5201 EPI.Variadic = false;
5202 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005203 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005204 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005205}
5206
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005207/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5208/// well-formednes of the conversion function declarator @p D with
5209/// type @p R. If there are any errors in the declarator, this routine
5210/// will emit diagnostics and return true. Otherwise, it will return
5211/// false. Either way, the type @p R will be updated to reflect a
5212/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005213void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005214 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005215 // C++ [class.conv.fct]p1:
5216 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005217 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005218 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005219 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005220 if (!D.isInvalidType())
5221 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5222 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5223 << SourceRange(D.getIdentifierLoc());
5224 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005225 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005226 }
John McCalla3f81372010-04-13 00:04:31 +00005227
5228 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5229
Chris Lattner6e475012009-04-25 08:35:12 +00005230 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005231 // Conversion functions don't have return types, but the parser will
5232 // happily parse something like:
5233 //
5234 // class X {
5235 // float operator bool();
5236 // };
5237 //
5238 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005239 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5240 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5241 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005242 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005243 }
5244
John McCalla3f81372010-04-13 00:04:31 +00005245 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5246
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005247 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005248 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005249 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5250
5251 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005252 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005253 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005254 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005255 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005256 D.setInvalidType();
5257 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005258
John McCalla3f81372010-04-13 00:04:31 +00005259 // Diagnose "&operator bool()" and other such nonsense. This
5260 // is actually a gcc extension which we don't support.
5261 if (Proto->getResultType() != ConvType) {
5262 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5263 << Proto->getResultType();
5264 D.setInvalidType();
5265 ConvType = Proto->getResultType();
5266 }
5267
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005268 // C++ [class.conv.fct]p4:
5269 // The conversion-type-id shall not represent a function type nor
5270 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005271 if (ConvType->isArrayType()) {
5272 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5273 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005274 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005275 } else if (ConvType->isFunctionType()) {
5276 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5277 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005278 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005279 }
5280
5281 // Rebuild the function type "R" without any parameters (in case any
5282 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005283 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005284 if (D.isInvalidType())
5285 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005286
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005287 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005288 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005289 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005290 getLangOptions().CPlusPlus0x ?
5291 diag::warn_cxx98_compat_explicit_conversion_functions :
5292 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005293 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005294}
5295
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005296/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5297/// the declaration of the given C++ conversion function. This routine
5298/// is responsible for recording the conversion function in the C++
5299/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005300Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005301 assert(Conversion && "Expected to receive a conversion function declaration");
5302
Douglas Gregor9d350972008-12-12 08:25:50 +00005303 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005304
5305 // Make sure we aren't redeclaring the conversion function.
5306 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005307
5308 // C++ [class.conv.fct]p1:
5309 // [...] A conversion function is never used to convert a
5310 // (possibly cv-qualified) object to the (possibly cv-qualified)
5311 // same object type (or a reference to it), to a (possibly
5312 // cv-qualified) base class of that type (or a reference to it),
5313 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005314 // FIXME: Suppress this warning if the conversion function ends up being a
5315 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005316 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005317 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005318 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005319 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005320 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5321 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005322 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005323 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005324 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5325 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005326 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005327 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005328 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005329 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005330 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005331 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005332 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005333 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005334 }
5335
Douglas Gregore80622f2010-09-29 04:25:11 +00005336 if (FunctionTemplateDecl *ConversionTemplate
5337 = Conversion->getDescribedFunctionTemplate())
5338 return ConversionTemplate;
5339
John McCalld226f652010-08-21 09:40:31 +00005340 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005341}
5342
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005343//===----------------------------------------------------------------------===//
5344// Namespace Handling
5345//===----------------------------------------------------------------------===//
5346
John McCallea318642010-08-26 09:15:37 +00005347
5348
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005349/// ActOnStartNamespaceDef - This is called at the start of a namespace
5350/// definition.
John McCalld226f652010-08-21 09:40:31 +00005351Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005352 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005353 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005354 SourceLocation IdentLoc,
5355 IdentifierInfo *II,
5356 SourceLocation LBrace,
5357 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005358 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5359 // For anonymous namespace, take the location of the left brace.
5360 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005361 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005362 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005363 bool IsStd = false;
5364 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005365 Scope *DeclRegionScope = NamespcScope->getParent();
5366
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005367 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005368 if (II) {
5369 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005370 // The identifier in an original-namespace-definition shall not
5371 // have been previously defined in the declarative region in
5372 // which the original-namespace-definition appears. The
5373 // identifier in an original-namespace-definition is the name of
5374 // the namespace. Subsequently in that declarative region, it is
5375 // treated as an original-namespace-name.
5376 //
5377 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005378 // look through using directives, just look for any ordinary names.
5379
5380 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005381 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5382 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005383 NamedDecl *PrevDecl = 0;
5384 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005385 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005386 R.first != R.second; ++R.first) {
5387 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5388 PrevDecl = *R.first;
5389 break;
5390 }
5391 }
5392
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005393 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5394
5395 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005396 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005397 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005398 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005399 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005400 // The user probably just forgot the 'inline', so suggest that it
5401 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005402 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005403 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5404 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005405 Diag(Loc, diag::err_inline_namespace_mismatch)
5406 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005407 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005408 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5409
5410 IsInline = PrevNS->isInline();
5411 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005412 } else if (PrevDecl) {
5413 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005414 Diag(Loc, diag::err_redefinition_different_kind)
5415 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005416 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005417 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005418 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005419 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005420 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005421 // This is the first "real" definition of the namespace "std", so update
5422 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005423 PrevNS = getStdNamespace();
5424 IsStd = true;
5425 AddToKnown = !IsInline;
5426 } else {
5427 // We've seen this namespace for the first time.
5428 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005429 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005430 } else {
John McCall9aeed322009-10-01 00:25:31 +00005431 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005432
5433 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005434 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005435 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005436 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005437 } else {
5438 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005439 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005440 }
5441
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005442 if (PrevNS && IsInline != PrevNS->isInline()) {
5443 // inline-ness must match
5444 Diag(Loc, diag::err_inline_namespace_mismatch)
5445 << IsInline;
5446 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005447
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005448 // Recover by ignoring the new namespace's inline status.
5449 IsInline = PrevNS->isInline();
5450 }
5451 }
5452
5453 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5454 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005455 if (IsInvalid)
5456 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005457
5458 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005459
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005460 // FIXME: Should we be merging attributes?
5461 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005462 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005463
5464 if (IsStd)
5465 StdNamespace = Namespc;
5466 if (AddToKnown)
5467 KnownNamespaces[Namespc] = false;
5468
5469 if (II) {
5470 PushOnScopeChains(Namespc, DeclRegionScope);
5471 } else {
5472 // Link the anonymous namespace into its parent.
5473 DeclContext *Parent = CurContext->getRedeclContext();
5474 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5475 TU->setAnonymousNamespace(Namespc);
5476 } else {
5477 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005478 }
John McCall9aeed322009-10-01 00:25:31 +00005479
Douglas Gregora4181472010-03-24 00:46:35 +00005480 CurContext->addDecl(Namespc);
5481
John McCall9aeed322009-10-01 00:25:31 +00005482 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5483 // behaves as if it were replaced by
5484 // namespace unique { /* empty body */ }
5485 // using namespace unique;
5486 // namespace unique { namespace-body }
5487 // where all occurrences of 'unique' in a translation unit are
5488 // replaced by the same identifier and this identifier differs
5489 // from all other identifiers in the entire program.
5490
5491 // We just create the namespace with an empty name and then add an
5492 // implicit using declaration, just like the standard suggests.
5493 //
5494 // CodeGen enforces the "universally unique" aspect by giving all
5495 // declarations semantically contained within an anonymous
5496 // namespace internal linkage.
5497
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005498 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005499 UsingDirectiveDecl* UD
5500 = UsingDirectiveDecl::Create(Context, CurContext,
5501 /* 'using' */ LBrace,
5502 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005503 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005504 /* identifier */ SourceLocation(),
5505 Namespc,
5506 /* Ancestor */ CurContext);
5507 UD->setImplicit();
5508 CurContext->addDecl(UD);
5509 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005510 }
5511
5512 // Although we could have an invalid decl (i.e. the namespace name is a
5513 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005514 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5515 // for the namespace has the declarations that showed up in that particular
5516 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005517 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005518 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005519}
5520
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005521/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5522/// is a namespace alias, returns the namespace it points to.
5523static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5524 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5525 return AD->getNamespace();
5526 return dyn_cast_or_null<NamespaceDecl>(D);
5527}
5528
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005529/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5530/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005531void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005532 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5533 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005534 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005535 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005536 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005537 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005538}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005539
John McCall384aff82010-08-25 07:42:41 +00005540CXXRecordDecl *Sema::getStdBadAlloc() const {
5541 return cast_or_null<CXXRecordDecl>(
5542 StdBadAlloc.get(Context.getExternalSource()));
5543}
5544
5545NamespaceDecl *Sema::getStdNamespace() const {
5546 return cast_or_null<NamespaceDecl>(
5547 StdNamespace.get(Context.getExternalSource()));
5548}
5549
Douglas Gregor66992202010-06-29 17:53:46 +00005550/// \brief Retrieve the special "std" namespace, which may require us to
5551/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005552NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005553 if (!StdNamespace) {
5554 // The "std" namespace has not yet been defined, so build one implicitly.
5555 StdNamespace = NamespaceDecl::Create(Context,
5556 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005557 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005558 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005559 &PP.getIdentifierTable().get("std"),
5560 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005561 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005562 }
5563
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005564 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005565}
5566
Sebastian Redl395e04d2012-01-17 22:49:33 +00005567bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5568 assert(getLangOptions().CPlusPlus &&
5569 "Looking for std::initializer_list outside of C++.");
5570
5571 // We're looking for implicit instantiations of
5572 // template <typename E> class std::initializer_list.
5573
5574 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5575 return false;
5576
Sebastian Redl84760e32012-01-17 22:49:58 +00005577 ClassTemplateDecl *Template = 0;
5578 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005579
Sebastian Redl84760e32012-01-17 22:49:58 +00005580 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005581
Sebastian Redl84760e32012-01-17 22:49:58 +00005582 ClassTemplateSpecializationDecl *Specialization =
5583 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5584 if (!Specialization)
5585 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005586
Sebastian Redl84760e32012-01-17 22:49:58 +00005587 Template = Specialization->getSpecializedTemplate();
5588 Arguments = Specialization->getTemplateArgs().data();
5589 } else if (const TemplateSpecializationType *TST =
5590 Ty->getAs<TemplateSpecializationType>()) {
5591 Template = dyn_cast_or_null<ClassTemplateDecl>(
5592 TST->getTemplateName().getAsTemplateDecl());
5593 Arguments = TST->getArgs();
5594 }
5595 if (!Template)
5596 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005597
5598 if (!StdInitializerList) {
5599 // Haven't recognized std::initializer_list yet, maybe this is it.
5600 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5601 if (TemplateClass->getIdentifier() !=
5602 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005603 !getStdNamespace()->InEnclosingNamespaceSetOf(
5604 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005605 return false;
5606 // This is a template called std::initializer_list, but is it the right
5607 // template?
5608 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005609 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005610 return false;
5611 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5612 return false;
5613
5614 // It's the right template.
5615 StdInitializerList = Template;
5616 }
5617
5618 if (Template != StdInitializerList)
5619 return false;
5620
5621 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005622 if (Element)
5623 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005624 return true;
5625}
5626
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005627static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5628 NamespaceDecl *Std = S.getStdNamespace();
5629 if (!Std) {
5630 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5631 return 0;
5632 }
5633
5634 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5635 Loc, Sema::LookupOrdinaryName);
5636 if (!S.LookupQualifiedName(Result, Std)) {
5637 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5638 return 0;
5639 }
5640 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5641 if (!Template) {
5642 Result.suppressDiagnostics();
5643 // We found something weird. Complain about the first thing we found.
5644 NamedDecl *Found = *Result.begin();
5645 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5646 return 0;
5647 }
5648
5649 // We found some template called std::initializer_list. Now verify that it's
5650 // correct.
5651 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005652 if (Params->getMinRequiredArguments() != 1 ||
5653 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005654 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5655 return 0;
5656 }
5657
5658 return Template;
5659}
5660
5661QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5662 if (!StdInitializerList) {
5663 StdInitializerList = LookupStdInitializerList(*this, Loc);
5664 if (!StdInitializerList)
5665 return QualType();
5666 }
5667
5668 TemplateArgumentListInfo Args(Loc, Loc);
5669 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5670 Context.getTrivialTypeSourceInfo(Element,
5671 Loc)));
5672 return Context.getCanonicalType(
5673 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5674}
5675
Sebastian Redl98d36062012-01-17 22:50:14 +00005676bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5677 // C++ [dcl.init.list]p2:
5678 // A constructor is an initializer-list constructor if its first parameter
5679 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5680 // std::initializer_list<E> for some type E, and either there are no other
5681 // parameters or else all other parameters have default arguments.
5682 if (Ctor->getNumParams() < 1 ||
5683 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5684 return false;
5685
5686 QualType ArgType = Ctor->getParamDecl(0)->getType();
5687 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5688 ArgType = RT->getPointeeType().getUnqualifiedType();
5689
5690 return isStdInitializerList(ArgType, 0);
5691}
5692
Douglas Gregor9172aa62011-03-26 22:25:30 +00005693/// \brief Determine whether a using statement is in a context where it will be
5694/// apply in all contexts.
5695static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5696 switch (CurContext->getDeclKind()) {
5697 case Decl::TranslationUnit:
5698 return true;
5699 case Decl::LinkageSpec:
5700 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5701 default:
5702 return false;
5703 }
5704}
5705
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005706namespace {
5707
5708// Callback to only accept typo corrections that are namespaces.
5709class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5710 public:
5711 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5712 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5713 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5714 }
5715 return false;
5716 }
5717};
5718
5719}
5720
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005721static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5722 CXXScopeSpec &SS,
5723 SourceLocation IdentLoc,
5724 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005725 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005726 R.clear();
5727 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005728 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005729 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005730 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5731 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5732 if (DeclContext *DC = S.computeDeclContext(SS, false))
5733 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5734 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5735 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5736 else
5737 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5738 << Ident << CorrectedQuotedStr
5739 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005740
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005741 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5742 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005743
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005744 Ident = Corrected.getCorrectionAsIdentifierInfo();
5745 R.addDecl(Corrected.getCorrectionDecl());
5746 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005747 }
5748 return false;
5749}
5750
John McCalld226f652010-08-21 09:40:31 +00005751Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005752 SourceLocation UsingLoc,
5753 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005754 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005755 SourceLocation IdentLoc,
5756 IdentifierInfo *NamespcName,
5757 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005758 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5759 assert(NamespcName && "Invalid NamespcName.");
5760 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005761
5762 // This can only happen along a recovery path.
5763 while (S->getFlags() & Scope::TemplateParamScope)
5764 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005765 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005766
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005767 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005768 NestedNameSpecifier *Qualifier = 0;
5769 if (SS.isSet())
5770 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5771
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005772 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005773 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5774 LookupParsedName(R, S, &SS);
5775 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005776 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005777
Douglas Gregor66992202010-06-29 17:53:46 +00005778 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005779 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005780 // Allow "using namespace std;" or "using namespace ::std;" even if
5781 // "std" hasn't been defined yet, for GCC compatibility.
5782 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5783 NamespcName->isStr("std")) {
5784 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005785 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005786 R.resolveKind();
5787 }
5788 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005789 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005790 }
5791
John McCallf36e02d2009-10-09 21:13:30 +00005792 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005793 NamedDecl *Named = R.getFoundDecl();
5794 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5795 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005796 // C++ [namespace.udir]p1:
5797 // A using-directive specifies that the names in the nominated
5798 // namespace can be used in the scope in which the
5799 // using-directive appears after the using-directive. During
5800 // unqualified name lookup (3.4.1), the names appear as if they
5801 // were declared in the nearest enclosing namespace which
5802 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005803 // namespace. [Note: in this context, "contains" means "contains
5804 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005805
5806 // Find enclosing context containing both using-directive and
5807 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005808 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005809 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5810 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5811 CommonAncestor = CommonAncestor->getParent();
5812
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005813 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005814 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005815 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005816
Douglas Gregor9172aa62011-03-26 22:25:30 +00005817 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005818 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005819 Diag(IdentLoc, diag::warn_using_directive_in_header);
5820 }
5821
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005822 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005823 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005824 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005825 }
5826
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005827 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005828 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005829}
5830
5831void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5832 // If scope has associated entity, then using directive is at namespace
5833 // or translation unit scope. We add UsingDirectiveDecls, into
5834 // it's lookup structure.
5835 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005836 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005837 else
5838 // Otherwise it is block-sope. using-directives will affect lookup
5839 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005840 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005841}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005842
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005843
John McCalld226f652010-08-21 09:40:31 +00005844Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005845 AccessSpecifier AS,
5846 bool HasUsingKeyword,
5847 SourceLocation UsingLoc,
5848 CXXScopeSpec &SS,
5849 UnqualifiedId &Name,
5850 AttributeList *AttrList,
5851 bool IsTypeName,
5852 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005853 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005854
Douglas Gregor12c118a2009-11-04 16:30:06 +00005855 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005856 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005857 case UnqualifiedId::IK_Identifier:
5858 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005859 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005860 case UnqualifiedId::IK_ConversionFunctionId:
5861 break;
5862
5863 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005864 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005865 // C++0x inherited constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005866 Diag(Name.getLocStart(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005867 getLangOptions().CPlusPlus0x ?
5868 diag::warn_cxx98_compat_using_decl_constructor :
5869 diag::err_using_decl_constructor)
5870 << SS.getRange();
5871
John McCall604e7f12009-12-08 07:46:18 +00005872 if (getLangOptions().CPlusPlus0x) break;
5873
John McCalld226f652010-08-21 09:40:31 +00005874 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005875
5876 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005877 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005878 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005879 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005880
5881 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005882 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005883 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005884 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005885 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005886
5887 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5888 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005889 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005890 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005891
John McCall60fa3cf2009-12-11 02:10:03 +00005892 // Warn about using declarations.
5893 // TODO: store that the declaration was written without 'using' and
5894 // talk about access decls instead of using decls in the
5895 // diagnostics.
5896 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005897 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005898
5899 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005900 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005901 }
5902
Douglas Gregor56c04582010-12-16 00:46:58 +00005903 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5904 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5905 return 0;
5906
John McCall9488ea12009-11-17 05:59:44 +00005907 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005908 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005909 /* IsInstantiation */ false,
5910 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005911 if (UD)
5912 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005913
John McCalld226f652010-08-21 09:40:31 +00005914 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005915}
5916
Douglas Gregor09acc982010-07-07 23:08:52 +00005917/// \brief Determine whether a using declaration considers the given
5918/// declarations as "equivalent", e.g., if they are redeclarations of
5919/// the same entity or are both typedefs of the same type.
5920static bool
5921IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5922 bool &SuppressRedeclaration) {
5923 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5924 SuppressRedeclaration = false;
5925 return true;
5926 }
5927
Richard Smith162e1c12011-04-15 14:24:37 +00005928 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5929 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005930 SuppressRedeclaration = true;
5931 return Context.hasSameType(TD1->getUnderlyingType(),
5932 TD2->getUnderlyingType());
5933 }
5934
5935 return false;
5936}
5937
5938
John McCall9f54ad42009-12-10 09:41:52 +00005939/// Determines whether to create a using shadow decl for a particular
5940/// decl, given the set of decls existing prior to this using lookup.
5941bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5942 const LookupResult &Previous) {
5943 // Diagnose finding a decl which is not from a base class of the
5944 // current class. We do this now because there are cases where this
5945 // function will silently decide not to build a shadow decl, which
5946 // will pre-empt further diagnostics.
5947 //
5948 // We don't need to do this in C++0x because we do the check once on
5949 // the qualifier.
5950 //
5951 // FIXME: diagnose the following if we care enough:
5952 // struct A { int foo; };
5953 // struct B : A { using A::foo; };
5954 // template <class T> struct C : A {};
5955 // template <class T> struct D : C<T> { using B::foo; } // <---
5956 // This is invalid (during instantiation) in C++03 because B::foo
5957 // resolves to the using decl in B, which is not a base class of D<T>.
5958 // We can't diagnose it immediately because C<T> is an unknown
5959 // specialization. The UsingShadowDecl in D<T> then points directly
5960 // to A::foo, which will look well-formed when we instantiate.
5961 // The right solution is to not collapse the shadow-decl chain.
5962 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5963 DeclContext *OrigDC = Orig->getDeclContext();
5964
5965 // Handle enums and anonymous structs.
5966 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5967 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5968 while (OrigRec->isAnonymousStructOrUnion())
5969 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5970
5971 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5972 if (OrigDC == CurContext) {
5973 Diag(Using->getLocation(),
5974 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005975 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005976 Diag(Orig->getLocation(), diag::note_using_decl_target);
5977 return true;
5978 }
5979
Douglas Gregordc355712011-02-25 00:36:19 +00005980 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005981 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005982 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005983 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005984 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005985 Diag(Orig->getLocation(), diag::note_using_decl_target);
5986 return true;
5987 }
5988 }
5989
5990 if (Previous.empty()) return false;
5991
5992 NamedDecl *Target = Orig;
5993 if (isa<UsingShadowDecl>(Target))
5994 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5995
John McCalld7533ec2009-12-11 02:33:26 +00005996 // If the target happens to be one of the previous declarations, we
5997 // don't have a conflict.
5998 //
5999 // FIXME: but we might be increasing its access, in which case we
6000 // should redeclare it.
6001 NamedDecl *NonTag = 0, *Tag = 0;
6002 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6003 I != E; ++I) {
6004 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006005 bool Result;
6006 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6007 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006008
6009 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6010 }
6011
John McCall9f54ad42009-12-10 09:41:52 +00006012 if (Target->isFunctionOrFunctionTemplate()) {
6013 FunctionDecl *FD;
6014 if (isa<FunctionTemplateDecl>(Target))
6015 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6016 else
6017 FD = cast<FunctionDecl>(Target);
6018
6019 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006020 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006021 case Ovl_Overload:
6022 return false;
6023
6024 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006025 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006026 break;
6027
6028 // We found a decl with the exact signature.
6029 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006030 // If we're in a record, we want to hide the target, so we
6031 // return true (without a diagnostic) to tell the caller not to
6032 // build a shadow decl.
6033 if (CurContext->isRecord())
6034 return true;
6035
6036 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006037 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006038 break;
6039 }
6040
6041 Diag(Target->getLocation(), diag::note_using_decl_target);
6042 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6043 return true;
6044 }
6045
6046 // Target is not a function.
6047
John McCall9f54ad42009-12-10 09:41:52 +00006048 if (isa<TagDecl>(Target)) {
6049 // No conflict between a tag and a non-tag.
6050 if (!Tag) return false;
6051
John McCall41ce66f2009-12-10 19:51:03 +00006052 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006053 Diag(Target->getLocation(), diag::note_using_decl_target);
6054 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6055 return true;
6056 }
6057
6058 // No conflict between a tag and a non-tag.
6059 if (!NonTag) return false;
6060
John McCall41ce66f2009-12-10 19:51:03 +00006061 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006062 Diag(Target->getLocation(), diag::note_using_decl_target);
6063 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6064 return true;
6065}
6066
John McCall9488ea12009-11-17 05:59:44 +00006067/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006068UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006069 UsingDecl *UD,
6070 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006071
6072 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006073 NamedDecl *Target = Orig;
6074 if (isa<UsingShadowDecl>(Target)) {
6075 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6076 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006077 }
6078
6079 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006080 = UsingShadowDecl::Create(Context, CurContext,
6081 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006082 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006083
6084 Shadow->setAccess(UD->getAccess());
6085 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6086 Shadow->setInvalidDecl();
6087
John McCall9488ea12009-11-17 05:59:44 +00006088 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006089 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006090 else
John McCall604e7f12009-12-08 07:46:18 +00006091 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006092
John McCall604e7f12009-12-08 07:46:18 +00006093
John McCall9f54ad42009-12-10 09:41:52 +00006094 return Shadow;
6095}
John McCall604e7f12009-12-08 07:46:18 +00006096
John McCall9f54ad42009-12-10 09:41:52 +00006097/// Hides a using shadow declaration. This is required by the current
6098/// using-decl implementation when a resolvable using declaration in a
6099/// class is followed by a declaration which would hide or override
6100/// one or more of the using decl's targets; for example:
6101///
6102/// struct Base { void foo(int); };
6103/// struct Derived : Base {
6104/// using Base::foo;
6105/// void foo(int);
6106/// };
6107///
6108/// The governing language is C++03 [namespace.udecl]p12:
6109///
6110/// When a using-declaration brings names from a base class into a
6111/// derived class scope, member functions in the derived class
6112/// override and/or hide member functions with the same name and
6113/// parameter types in a base class (rather than conflicting).
6114///
6115/// There are two ways to implement this:
6116/// (1) optimistically create shadow decls when they're not hidden
6117/// by existing declarations, or
6118/// (2) don't create any shadow decls (or at least don't make them
6119/// visible) until we've fully parsed/instantiated the class.
6120/// The problem with (1) is that we might have to retroactively remove
6121/// a shadow decl, which requires several O(n) operations because the
6122/// decl structures are (very reasonably) not designed for removal.
6123/// (2) avoids this but is very fiddly and phase-dependent.
6124void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006125 if (Shadow->getDeclName().getNameKind() ==
6126 DeclarationName::CXXConversionFunctionName)
6127 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6128
John McCall9f54ad42009-12-10 09:41:52 +00006129 // Remove it from the DeclContext...
6130 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006131
John McCall9f54ad42009-12-10 09:41:52 +00006132 // ...and the scope, if applicable...
6133 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006134 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006135 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006136 }
6137
John McCall9f54ad42009-12-10 09:41:52 +00006138 // ...and the using decl.
6139 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6140
6141 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006142 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006143}
6144
John McCall7ba107a2009-11-18 02:36:19 +00006145/// Builds a using declaration.
6146///
6147/// \param IsInstantiation - Whether this call arises from an
6148/// instantiation of an unresolved using declaration. We treat
6149/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006150NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6151 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006152 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006153 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006154 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006155 bool IsInstantiation,
6156 bool IsTypeName,
6157 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006158 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006159 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006160 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006161
Anders Carlsson550b14b2009-08-28 05:49:21 +00006162 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006163
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006164 if (SS.isEmpty()) {
6165 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006166 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006167 }
Mike Stump1eb44332009-09-09 15:08:12 +00006168
John McCall9f54ad42009-12-10 09:41:52 +00006169 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006170 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006171 ForRedeclaration);
6172 Previous.setHideTags(false);
6173 if (S) {
6174 LookupName(Previous, S);
6175
6176 // It is really dumb that we have to do this.
6177 LookupResult::Filter F = Previous.makeFilter();
6178 while (F.hasNext()) {
6179 NamedDecl *D = F.next();
6180 if (!isDeclInScope(D, CurContext, S))
6181 F.erase();
6182 }
6183 F.done();
6184 } else {
6185 assert(IsInstantiation && "no scope in non-instantiation");
6186 assert(CurContext->isRecord() && "scope not record in instantiation");
6187 LookupQualifiedName(Previous, CurContext);
6188 }
6189
John McCall9f54ad42009-12-10 09:41:52 +00006190 // Check for invalid redeclarations.
6191 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6192 return 0;
6193
6194 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006195 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6196 return 0;
6197
John McCallaf8e6ed2009-11-12 03:15:40 +00006198 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006199 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006200 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006201 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006202 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006203 // FIXME: not all declaration name kinds are legal here
6204 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6205 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006206 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006207 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006208 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006209 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6210 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006211 }
John McCalled976492009-12-04 22:46:56 +00006212 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006213 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6214 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006215 }
John McCalled976492009-12-04 22:46:56 +00006216 D->setAccess(AS);
6217 CurContext->addDecl(D);
6218
6219 if (!LookupContext) return D;
6220 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006221
John McCall77bb1aa2010-05-01 00:40:08 +00006222 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006223 UD->setInvalidDecl();
6224 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006225 }
6226
Sebastian Redlf677ea32011-02-05 19:23:19 +00006227 // Constructor inheriting using decls get special treatment.
6228 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006229 if (CheckInheritedConstructorUsingDecl(UD))
6230 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006231 return UD;
6232 }
6233
6234 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006235
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006236 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006237
John McCall604e7f12009-12-08 07:46:18 +00006238 // Unlike most lookups, we don't always want to hide tag
6239 // declarations: tag names are visible through the using declaration
6240 // even if hidden by ordinary names, *except* in a dependent context
6241 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006242 if (!IsInstantiation)
6243 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006244
John McCalla24dc2e2009-11-17 02:14:36 +00006245 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006246
John McCallf36e02d2009-10-09 21:13:30 +00006247 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006248 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006249 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006250 UD->setInvalidDecl();
6251 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006252 }
6253
John McCalled976492009-12-04 22:46:56 +00006254 if (R.isAmbiguous()) {
6255 UD->setInvalidDecl();
6256 return UD;
6257 }
Mike Stump1eb44332009-09-09 15:08:12 +00006258
John McCall7ba107a2009-11-18 02:36:19 +00006259 if (IsTypeName) {
6260 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006261 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006262 Diag(IdentLoc, diag::err_using_typename_non_type);
6263 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6264 Diag((*I)->getUnderlyingDecl()->getLocation(),
6265 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006266 UD->setInvalidDecl();
6267 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006268 }
6269 } else {
6270 // If we asked for a non-typename and we got a type, error out,
6271 // but only if this is an instantiation of an unresolved using
6272 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006273 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006274 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6275 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006276 UD->setInvalidDecl();
6277 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006278 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006279 }
6280
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006281 // C++0x N2914 [namespace.udecl]p6:
6282 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006283 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006284 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6285 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006286 UD->setInvalidDecl();
6287 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006288 }
Mike Stump1eb44332009-09-09 15:08:12 +00006289
John McCall9f54ad42009-12-10 09:41:52 +00006290 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6291 if (!CheckUsingShadowDecl(UD, *I, Previous))
6292 BuildUsingShadowDecl(S, UD, *I);
6293 }
John McCall9488ea12009-11-17 05:59:44 +00006294
6295 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006296}
6297
Sebastian Redlf677ea32011-02-05 19:23:19 +00006298/// Additional checks for a using declaration referring to a constructor name.
6299bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6300 if (UD->isTypeName()) {
6301 // FIXME: Cannot specify typename when specifying constructor
6302 return true;
6303 }
6304
Douglas Gregordc355712011-02-25 00:36:19 +00006305 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006306 assert(SourceType &&
6307 "Using decl naming constructor doesn't have type in scope spec.");
6308 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6309
6310 // Check whether the named type is a direct base class.
6311 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6312 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6313 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6314 BaseIt != BaseE; ++BaseIt) {
6315 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6316 if (CanonicalSourceType == BaseType)
6317 break;
6318 }
6319
6320 if (BaseIt == BaseE) {
6321 // Did not find SourceType in the bases.
6322 Diag(UD->getUsingLocation(),
6323 diag::err_using_decl_constructor_not_in_direct_base)
6324 << UD->getNameInfo().getSourceRange()
6325 << QualType(SourceType, 0) << TargetClass;
6326 return true;
6327 }
6328
6329 BaseIt->setInheritConstructors();
6330
6331 return false;
6332}
6333
John McCall9f54ad42009-12-10 09:41:52 +00006334/// Checks that the given using declaration is not an invalid
6335/// redeclaration. Note that this is checking only for the using decl
6336/// itself, not for any ill-formedness among the UsingShadowDecls.
6337bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6338 bool isTypeName,
6339 const CXXScopeSpec &SS,
6340 SourceLocation NameLoc,
6341 const LookupResult &Prev) {
6342 // C++03 [namespace.udecl]p8:
6343 // C++0x [namespace.udecl]p10:
6344 // A using-declaration is a declaration and can therefore be used
6345 // repeatedly where (and only where) multiple declarations are
6346 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006347 //
John McCall8a726212010-11-29 18:01:58 +00006348 // That's in non-member contexts.
6349 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006350 return false;
6351
6352 NestedNameSpecifier *Qual
6353 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6354
6355 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6356 NamedDecl *D = *I;
6357
6358 bool DTypename;
6359 NestedNameSpecifier *DQual;
6360 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6361 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006362 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006363 } else if (UnresolvedUsingValueDecl *UD
6364 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6365 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006366 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006367 } else if (UnresolvedUsingTypenameDecl *UD
6368 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6369 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006370 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006371 } else continue;
6372
6373 // using decls differ if one says 'typename' and the other doesn't.
6374 // FIXME: non-dependent using decls?
6375 if (isTypeName != DTypename) continue;
6376
6377 // using decls differ if they name different scopes (but note that
6378 // template instantiation can cause this check to trigger when it
6379 // didn't before instantiation).
6380 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6381 Context.getCanonicalNestedNameSpecifier(DQual))
6382 continue;
6383
6384 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006385 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006386 return true;
6387 }
6388
6389 return false;
6390}
6391
John McCall604e7f12009-12-08 07:46:18 +00006392
John McCalled976492009-12-04 22:46:56 +00006393/// Checks that the given nested-name qualifier used in a using decl
6394/// in the current context is appropriately related to the current
6395/// scope. If an error is found, diagnoses it and returns true.
6396bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6397 const CXXScopeSpec &SS,
6398 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006399 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006400
John McCall604e7f12009-12-08 07:46:18 +00006401 if (!CurContext->isRecord()) {
6402 // C++03 [namespace.udecl]p3:
6403 // C++0x [namespace.udecl]p8:
6404 // A using-declaration for a class member shall be a member-declaration.
6405
6406 // If we weren't able to compute a valid scope, it must be a
6407 // dependent class scope.
6408 if (!NamedContext || NamedContext->isRecord()) {
6409 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6410 << SS.getRange();
6411 return true;
6412 }
6413
6414 // Otherwise, everything is known to be fine.
6415 return false;
6416 }
6417
6418 // The current scope is a record.
6419
6420 // If the named context is dependent, we can't decide much.
6421 if (!NamedContext) {
6422 // FIXME: in C++0x, we can diagnose if we can prove that the
6423 // nested-name-specifier does not refer to a base class, which is
6424 // still possible in some cases.
6425
6426 // Otherwise we have to conservatively report that things might be
6427 // okay.
6428 return false;
6429 }
6430
6431 if (!NamedContext->isRecord()) {
6432 // Ideally this would point at the last name in the specifier,
6433 // but we don't have that level of source info.
6434 Diag(SS.getRange().getBegin(),
6435 diag::err_using_decl_nested_name_specifier_is_not_class)
6436 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6437 return true;
6438 }
6439
Douglas Gregor6fb07292010-12-21 07:41:49 +00006440 if (!NamedContext->isDependentContext() &&
6441 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6442 return true;
6443
John McCall604e7f12009-12-08 07:46:18 +00006444 if (getLangOptions().CPlusPlus0x) {
6445 // C++0x [namespace.udecl]p3:
6446 // In a using-declaration used as a member-declaration, the
6447 // nested-name-specifier shall name a base class of the class
6448 // being defined.
6449
6450 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6451 cast<CXXRecordDecl>(NamedContext))) {
6452 if (CurContext == NamedContext) {
6453 Diag(NameLoc,
6454 diag::err_using_decl_nested_name_specifier_is_current_class)
6455 << SS.getRange();
6456 return true;
6457 }
6458
6459 Diag(SS.getRange().getBegin(),
6460 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6461 << (NestedNameSpecifier*) SS.getScopeRep()
6462 << cast<CXXRecordDecl>(CurContext)
6463 << SS.getRange();
6464 return true;
6465 }
6466
6467 return false;
6468 }
6469
6470 // C++03 [namespace.udecl]p4:
6471 // A using-declaration used as a member-declaration shall refer
6472 // to a member of a base class of the class being defined [etc.].
6473
6474 // Salient point: SS doesn't have to name a base class as long as
6475 // lookup only finds members from base classes. Therefore we can
6476 // diagnose here only if we can prove that that can't happen,
6477 // i.e. if the class hierarchies provably don't intersect.
6478
6479 // TODO: it would be nice if "definitely valid" results were cached
6480 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6481 // need to be repeated.
6482
6483 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006484 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006485
6486 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6487 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6488 Data->Bases.insert(Base);
6489 return true;
6490 }
6491
6492 bool hasDependentBases(const CXXRecordDecl *Class) {
6493 return !Class->forallBases(collect, this);
6494 }
6495
6496 /// Returns true if the base is dependent or is one of the
6497 /// accumulated base classes.
6498 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6499 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6500 return !Data->Bases.count(Base);
6501 }
6502
6503 bool mightShareBases(const CXXRecordDecl *Class) {
6504 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6505 }
6506 };
6507
6508 UserData Data;
6509
6510 // Returns false if we find a dependent base.
6511 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6512 return false;
6513
6514 // Returns false if the class has a dependent base or if it or one
6515 // of its bases is present in the base set of the current context.
6516 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6517 return false;
6518
6519 Diag(SS.getRange().getBegin(),
6520 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6521 << (NestedNameSpecifier*) SS.getScopeRep()
6522 << cast<CXXRecordDecl>(CurContext)
6523 << SS.getRange();
6524
6525 return true;
John McCalled976492009-12-04 22:46:56 +00006526}
6527
Richard Smith162e1c12011-04-15 14:24:37 +00006528Decl *Sema::ActOnAliasDeclaration(Scope *S,
6529 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006530 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006531 SourceLocation UsingLoc,
6532 UnqualifiedId &Name,
6533 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006534 // Skip up to the relevant declaration scope.
6535 while (S->getFlags() & Scope::TemplateParamScope)
6536 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006537 assert((S->getFlags() & Scope::DeclScope) &&
6538 "got alias-declaration outside of declaration scope");
6539
6540 if (Type.isInvalid())
6541 return 0;
6542
6543 bool Invalid = false;
6544 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6545 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006546 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006547
6548 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6549 return 0;
6550
6551 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006552 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006553 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006554 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6555 TInfo->getTypeLoc().getBeginLoc());
6556 }
Richard Smith162e1c12011-04-15 14:24:37 +00006557
6558 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6559 LookupName(Previous, S);
6560
6561 // Warn about shadowing the name of a template parameter.
6562 if (Previous.isSingleResult() &&
6563 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006564 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006565 Previous.clear();
6566 }
6567
6568 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6569 "name in alias declaration must be an identifier");
6570 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6571 Name.StartLocation,
6572 Name.Identifier, TInfo);
6573
6574 NewTD->setAccess(AS);
6575
6576 if (Invalid)
6577 NewTD->setInvalidDecl();
6578
Richard Smith3e4c6c42011-05-05 21:57:07 +00006579 CheckTypedefForVariablyModifiedType(S, NewTD);
6580 Invalid |= NewTD->isInvalidDecl();
6581
Richard Smith162e1c12011-04-15 14:24:37 +00006582 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006583
6584 NamedDecl *NewND;
6585 if (TemplateParamLists.size()) {
6586 TypeAliasTemplateDecl *OldDecl = 0;
6587 TemplateParameterList *OldTemplateParams = 0;
6588
6589 if (TemplateParamLists.size() != 1) {
6590 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6591 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6592 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6593 }
6594 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6595
6596 // Only consider previous declarations in the same scope.
6597 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6598 /*ExplicitInstantiationOrSpecialization*/false);
6599 if (!Previous.empty()) {
6600 Redeclaration = true;
6601
6602 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6603 if (!OldDecl && !Invalid) {
6604 Diag(UsingLoc, diag::err_redefinition_different_kind)
6605 << Name.Identifier;
6606
6607 NamedDecl *OldD = Previous.getRepresentativeDecl();
6608 if (OldD->getLocation().isValid())
6609 Diag(OldD->getLocation(), diag::note_previous_definition);
6610
6611 Invalid = true;
6612 }
6613
6614 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6615 if (TemplateParameterListsAreEqual(TemplateParams,
6616 OldDecl->getTemplateParameters(),
6617 /*Complain=*/true,
6618 TPL_TemplateMatch))
6619 OldTemplateParams = OldDecl->getTemplateParameters();
6620 else
6621 Invalid = true;
6622
6623 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6624 if (!Invalid &&
6625 !Context.hasSameType(OldTD->getUnderlyingType(),
6626 NewTD->getUnderlyingType())) {
6627 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6628 // but we can't reasonably accept it.
6629 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6630 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6631 if (OldTD->getLocation().isValid())
6632 Diag(OldTD->getLocation(), diag::note_previous_definition);
6633 Invalid = true;
6634 }
6635 }
6636 }
6637
6638 // Merge any previous default template arguments into our parameters,
6639 // and check the parameter list.
6640 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6641 TPC_TypeAliasTemplate))
6642 return 0;
6643
6644 TypeAliasTemplateDecl *NewDecl =
6645 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6646 Name.Identifier, TemplateParams,
6647 NewTD);
6648
6649 NewDecl->setAccess(AS);
6650
6651 if (Invalid)
6652 NewDecl->setInvalidDecl();
6653 else if (OldDecl)
6654 NewDecl->setPreviousDeclaration(OldDecl);
6655
6656 NewND = NewDecl;
6657 } else {
6658 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6659 NewND = NewTD;
6660 }
Richard Smith162e1c12011-04-15 14:24:37 +00006661
6662 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006663 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006664
Richard Smith3e4c6c42011-05-05 21:57:07 +00006665 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006666}
6667
John McCalld226f652010-08-21 09:40:31 +00006668Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006669 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006670 SourceLocation AliasLoc,
6671 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006672 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006673 SourceLocation IdentLoc,
6674 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006675
Anders Carlsson81c85c42009-03-28 23:53:49 +00006676 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006677 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6678 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006679
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006680 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006681 NamedDecl *PrevDecl
6682 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6683 ForRedeclaration);
6684 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6685 PrevDecl = 0;
6686
6687 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006688 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006689 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006690 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006691 // FIXME: At some point, we'll want to create the (redundant)
6692 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006693 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006694 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006695 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006696 }
Mike Stump1eb44332009-09-09 15:08:12 +00006697
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006698 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6699 diag::err_redefinition_different_kind;
6700 Diag(AliasLoc, DiagID) << Alias;
6701 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006702 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006703 }
6704
John McCalla24dc2e2009-11-17 02:14:36 +00006705 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006706 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006707
John McCallf36e02d2009-10-09 21:13:30 +00006708 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006709 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006710 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006711 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006712 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006713 }
Mike Stump1eb44332009-09-09 15:08:12 +00006714
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006715 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006716 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006717 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006718 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006719
John McCall3dbd3d52010-02-16 06:53:13 +00006720 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006721 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006722}
6723
Douglas Gregor39957dc2010-05-01 15:04:51 +00006724namespace {
6725 /// \brief Scoped object used to handle the state changes required in Sema
6726 /// to implicitly define the body of a C++ member function;
6727 class ImplicitlyDefinedFunctionScope {
6728 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006729 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006730
6731 public:
6732 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006733 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006734 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006735 S.PushFunctionScope();
6736 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6737 }
6738
6739 ~ImplicitlyDefinedFunctionScope() {
6740 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006741 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006742 }
6743 };
6744}
6745
Sean Hunt001cad92011-05-10 00:49:42 +00006746Sema::ImplicitExceptionSpecification
6747Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006748 // C++ [except.spec]p14:
6749 // An implicitly declared special member function (Clause 12) shall have an
6750 // exception-specification. [...]
6751 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006752 if (ClassDecl->isInvalidDecl())
6753 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006754
Sebastian Redl60618fa2011-03-12 11:50:43 +00006755 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006756 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6757 BEnd = ClassDecl->bases_end();
6758 B != BEnd; ++B) {
6759 if (B->isVirtual()) // Handled below.
6760 continue;
6761
Douglas Gregor18274032010-07-03 00:47:00 +00006762 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6763 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006764 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6765 // If this is a deleted function, add it anyway. This might be conformant
6766 // with the standard. This might not. I'm not sure. It might not matter.
6767 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006768 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006769 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006770 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006771
6772 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006773 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6774 BEnd = ClassDecl->vbases_end();
6775 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006776 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6777 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006778 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6779 // If this is a deleted function, add it anyway. This might be conformant
6780 // with the standard. This might not. I'm not sure. It might not matter.
6781 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006782 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006783 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006784 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006785
6786 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006787 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6788 FEnd = ClassDecl->field_end();
6789 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006790 if (F->hasInClassInitializer()) {
6791 if (Expr *E = F->getInClassInitializer())
6792 ExceptSpec.CalledExpr(E);
6793 else if (!F->isInvalidDecl())
6794 ExceptSpec.SetDelayed();
6795 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006796 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006797 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6798 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6799 // If this is a deleted function, add it anyway. This might be conformant
6800 // with the standard. This might not. I'm not sure. It might not matter.
6801 // In particular, the problem is that this function never gets called. It
6802 // might just be ill-formed because this function attempts to refer to
6803 // a deleted function here.
6804 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006805 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006806 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006807 }
John McCalle23cf432010-12-14 08:05:40 +00006808
Sean Hunt001cad92011-05-10 00:49:42 +00006809 return ExceptSpec;
6810}
6811
6812CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6813 CXXRecordDecl *ClassDecl) {
6814 // C++ [class.ctor]p5:
6815 // A default constructor for a class X is a constructor of class X
6816 // that can be called without an argument. If there is no
6817 // user-declared constructor for class X, a default constructor is
6818 // implicitly declared. An implicitly-declared default constructor
6819 // is an inline public member of its class.
6820 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6821 "Should not build implicit default constructor!");
6822
6823 ImplicitExceptionSpecification Spec =
6824 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6825 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006826
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006827 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006828 CanQualType ClassType
6829 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006830 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006831 DeclarationName Name
6832 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006833 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006834 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6835 Context, ClassDecl, ClassLoc, NameInfo,
6836 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6837 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6838 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6839 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006840 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006841 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006842 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006843 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006844
6845 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006846 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6847
Douglas Gregor23c94db2010-07-02 17:43:08 +00006848 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006849 PushOnScopeChains(DefaultCon, S, false);
6850 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006851
Sean Hunte16da072011-10-10 06:18:57 +00006852 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006853 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006854
Douglas Gregor32df23e2010-07-01 22:02:46 +00006855 return DefaultCon;
6856}
6857
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006858void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6859 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006860 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006861 !Constructor->doesThisDeclarationHaveABody() &&
6862 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006863 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006864
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006865 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006866 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006867
Douglas Gregor39957dc2010-05-01 15:04:51 +00006868 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006869 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006870 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006871 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006872 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006873 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006874 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006875 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006876 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006877
6878 SourceLocation Loc = Constructor->getLocation();
6879 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6880
6881 Constructor->setUsed();
6882 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006883
6884 if (ASTMutationListener *L = getASTMutationListener()) {
6885 L->CompletedImplicitDefinition(Constructor);
6886 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006887}
6888
Richard Smith7a614d82011-06-11 17:19:42 +00006889/// Get any existing defaulted default constructor for the given class. Do not
6890/// implicitly define one if it does not exist.
6891static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6892 CXXRecordDecl *D) {
6893 ASTContext &Context = Self.Context;
6894 QualType ClassType = Context.getTypeDeclType(D);
6895 DeclarationName ConstructorName
6896 = Context.DeclarationNames.getCXXConstructorName(
6897 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6898
6899 DeclContext::lookup_const_iterator Con, ConEnd;
6900 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6901 Con != ConEnd; ++Con) {
6902 // A function template cannot be defaulted.
6903 if (isa<FunctionTemplateDecl>(*Con))
6904 continue;
6905
6906 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6907 if (Constructor->isDefaultConstructor())
6908 return Constructor->isDefaulted() ? Constructor : 0;
6909 }
6910 return 0;
6911}
6912
6913void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6914 if (!D) return;
6915 AdjustDeclIfTemplate(D);
6916
6917 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6918 CXXConstructorDecl *CtorDecl
6919 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6920
6921 if (!CtorDecl) return;
6922
6923 // Compute the exception specification for the default constructor.
6924 const FunctionProtoType *CtorTy =
6925 CtorDecl->getType()->castAs<FunctionProtoType>();
6926 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6927 ImplicitExceptionSpecification Spec =
6928 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6929 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6930 assert(EPI.ExceptionSpecType != EST_Delayed);
6931
6932 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6933 }
6934
6935 // If the default constructor is explicitly defaulted, checking the exception
6936 // specification is deferred until now.
6937 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6938 !ClassDecl->isDependentType())
6939 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6940}
6941
Sebastian Redlf677ea32011-02-05 19:23:19 +00006942void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6943 // We start with an initial pass over the base classes to collect those that
6944 // inherit constructors from. If there are none, we can forgo all further
6945 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006946 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006947 BasesVector BasesToInheritFrom;
6948 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6949 BaseE = ClassDecl->bases_end();
6950 BaseIt != BaseE; ++BaseIt) {
6951 if (BaseIt->getInheritConstructors()) {
6952 QualType Base = BaseIt->getType();
6953 if (Base->isDependentType()) {
6954 // If we inherit constructors from anything that is dependent, just
6955 // abort processing altogether. We'll get another chance for the
6956 // instantiations.
6957 return;
6958 }
6959 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6960 }
6961 }
6962 if (BasesToInheritFrom.empty())
6963 return;
6964
6965 // Now collect the constructors that we already have in the current class.
6966 // Those take precedence over inherited constructors.
6967 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6968 // unless there is a user-declared constructor with the same signature in
6969 // the class where the using-declaration appears.
6970 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6971 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6972 CtorE = ClassDecl->ctor_end();
6973 CtorIt != CtorE; ++CtorIt) {
6974 ExistingConstructors.insert(
6975 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6976 }
6977
6978 Scope *S = getScopeForContext(ClassDecl);
6979 DeclarationName CreatedCtorName =
6980 Context.DeclarationNames.getCXXConstructorName(
6981 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6982
6983 // Now comes the true work.
6984 // First, we keep a map from constructor types to the base that introduced
6985 // them. Needed for finding conflicting constructors. We also keep the
6986 // actually inserted declarations in there, for pretty diagnostics.
6987 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6988 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6989 ConstructorToSourceMap InheritedConstructors;
6990 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6991 BaseE = BasesToInheritFrom.end();
6992 BaseIt != BaseE; ++BaseIt) {
6993 const RecordType *Base = *BaseIt;
6994 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6995 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6996 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6997 CtorE = BaseDecl->ctor_end();
6998 CtorIt != CtorE; ++CtorIt) {
6999 // Find the using declaration for inheriting this base's constructors.
7000 DeclarationName Name =
7001 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7002 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7003 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7004 SourceLocation UsingLoc = UD ? UD->getLocation() :
7005 ClassDecl->getLocation();
7006
7007 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7008 // from the class X named in the using-declaration consists of actual
7009 // constructors and notional constructors that result from the
7010 // transformation of defaulted parameters as follows:
7011 // - all non-template default constructors of X, and
7012 // - for each non-template constructor of X that has at least one
7013 // parameter with a default argument, the set of constructors that
7014 // results from omitting any ellipsis parameter specification and
7015 // successively omitting parameters with a default argument from the
7016 // end of the parameter-type-list.
7017 CXXConstructorDecl *BaseCtor = *CtorIt;
7018 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7019 const FunctionProtoType *BaseCtorType =
7020 BaseCtor->getType()->getAs<FunctionProtoType>();
7021
7022 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7023 maxParams = BaseCtor->getNumParams();
7024 params <= maxParams; ++params) {
7025 // Skip default constructors. They're never inherited.
7026 if (params == 0)
7027 continue;
7028 // Skip copy and move constructors for the same reason.
7029 if (CanBeCopyOrMove && params == 1)
7030 continue;
7031
7032 // Build up a function type for this particular constructor.
7033 // FIXME: The working paper does not consider that the exception spec
7034 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007035 // source. This code doesn't yet, either. When it does, this code will
7036 // need to be delayed until after exception specifications and in-class
7037 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007038 const Type *NewCtorType;
7039 if (params == maxParams)
7040 NewCtorType = BaseCtorType;
7041 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007042 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007043 for (unsigned i = 0; i < params; ++i) {
7044 Args.push_back(BaseCtorType->getArgType(i));
7045 }
7046 FunctionProtoType::ExtProtoInfo ExtInfo =
7047 BaseCtorType->getExtProtoInfo();
7048 ExtInfo.Variadic = false;
7049 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7050 Args.data(), params, ExtInfo)
7051 .getTypePtr();
7052 }
7053 const Type *CanonicalNewCtorType =
7054 Context.getCanonicalType(NewCtorType);
7055
7056 // Now that we have the type, first check if the class already has a
7057 // constructor with this signature.
7058 if (ExistingConstructors.count(CanonicalNewCtorType))
7059 continue;
7060
7061 // Then we check if we have already declared an inherited constructor
7062 // with this signature.
7063 std::pair<ConstructorToSourceMap::iterator, bool> result =
7064 InheritedConstructors.insert(std::make_pair(
7065 CanonicalNewCtorType,
7066 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7067 if (!result.second) {
7068 // Already in the map. If it came from a different class, that's an
7069 // error. Not if it's from the same.
7070 CanQualType PreviousBase = result.first->second.first;
7071 if (CanonicalBase != PreviousBase) {
7072 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7073 const CXXConstructorDecl *PrevBaseCtor =
7074 PrevCtor->getInheritedConstructor();
7075 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7076
7077 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7078 Diag(BaseCtor->getLocation(),
7079 diag::note_using_decl_constructor_conflict_current_ctor);
7080 Diag(PrevBaseCtor->getLocation(),
7081 diag::note_using_decl_constructor_conflict_previous_ctor);
7082 Diag(PrevCtor->getLocation(),
7083 diag::note_using_decl_constructor_conflict_previous_using);
7084 }
7085 continue;
7086 }
7087
7088 // OK, we're there, now add the constructor.
7089 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007090 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007091 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7092 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007093 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7094 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007095 /*ImplicitlyDeclared=*/true,
7096 // FIXME: Due to a defect in the standard, we treat inherited
7097 // constructors as constexpr even if that makes them ill-formed.
7098 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007099 NewCtor->setAccess(BaseCtor->getAccess());
7100
7101 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007102 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007103 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007104 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7105 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007106 /*IdentifierInfo=*/0,
7107 BaseCtorType->getArgType(i),
7108 /*TInfo=*/0, SC_None,
7109 SC_None, /*DefaultArg=*/0));
7110 }
David Blaikie4278c652011-09-21 18:16:56 +00007111 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007112 NewCtor->setInheritedConstructor(BaseCtor);
7113
7114 PushOnScopeChains(NewCtor, S, false);
7115 ClassDecl->addDecl(NewCtor);
7116 result.first->second.second = NewCtor;
7117 }
7118 }
7119 }
7120}
7121
Sean Huntcb45a0f2011-05-12 22:46:25 +00007122Sema::ImplicitExceptionSpecification
7123Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007124 // C++ [except.spec]p14:
7125 // An implicitly declared special member function (Clause 12) shall have
7126 // an exception-specification.
7127 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007128 if (ClassDecl->isInvalidDecl())
7129 return ExceptSpec;
7130
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007131 // Direct base-class destructors.
7132 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7133 BEnd = ClassDecl->bases_end();
7134 B != BEnd; ++B) {
7135 if (B->isVirtual()) // Handled below.
7136 continue;
7137
7138 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7139 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007140 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007141 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007142
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007143 // Virtual base-class destructors.
7144 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7145 BEnd = ClassDecl->vbases_end();
7146 B != BEnd; ++B) {
7147 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7148 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007149 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007150 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007151
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007152 // Field destructors.
7153 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7154 FEnd = ClassDecl->field_end();
7155 F != FEnd; ++F) {
7156 if (const RecordType *RecordTy
7157 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7158 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007159 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007160 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007161
Sean Huntcb45a0f2011-05-12 22:46:25 +00007162 return ExceptSpec;
7163}
7164
7165CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7166 // C++ [class.dtor]p2:
7167 // If a class has no user-declared destructor, a destructor is
7168 // declared implicitly. An implicitly-declared destructor is an
7169 // inline public member of its class.
7170
7171 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007172 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007173 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7174
Douglas Gregor4923aa22010-07-02 20:37:36 +00007175 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007176 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007177
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007178 CanQualType ClassType
7179 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007180 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007181 DeclarationName Name
7182 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007183 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007184 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007185 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7186 /*isInline=*/true,
7187 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007188 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007189 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007190 Destructor->setImplicit();
7191 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007192
7193 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007194 ++ASTContext::NumImplicitDestructorsDeclared;
7195
7196 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007197 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007198 PushOnScopeChains(Destructor, S, false);
7199 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007200
7201 // This could be uniqued if it ever proves significant.
7202 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007203
Richard Smith9a561d52012-02-26 09:11:52 +00007204 AddOverriddenMethods(ClassDecl, Destructor);
7205
Richard Smith7d5088a2012-02-18 02:02:13 +00007206 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007207 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007208
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007209 return Destructor;
7210}
7211
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007212void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007213 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007214 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007215 !Destructor->doesThisDeclarationHaveABody() &&
7216 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007217 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007218 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007219 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007220
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007221 if (Destructor->isInvalidDecl())
7222 return;
7223
Douglas Gregor39957dc2010-05-01 15:04:51 +00007224 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007225
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007226 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007227 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7228 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007229
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007230 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007231 Diag(CurrentLocation, diag::note_member_synthesized_at)
7232 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7233
7234 Destructor->setInvalidDecl();
7235 return;
7236 }
7237
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007238 SourceLocation Loc = Destructor->getLocation();
7239 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007240 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007241 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007242 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007243
7244 if (ASTMutationListener *L = getASTMutationListener()) {
7245 L->CompletedImplicitDefinition(Destructor);
7246 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007247}
7248
Sebastian Redl0ee33912011-05-19 05:13:44 +00007249void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7250 CXXDestructorDecl *destructor) {
7251 // C++11 [class.dtor]p3:
7252 // A declaration of a destructor that does not have an exception-
7253 // specification is implicitly considered to have the same exception-
7254 // specification as an implicit declaration.
7255 const FunctionProtoType *dtorType = destructor->getType()->
7256 getAs<FunctionProtoType>();
7257 if (dtorType->hasExceptionSpec())
7258 return;
7259
7260 ImplicitExceptionSpecification exceptSpec =
7261 ComputeDefaultedDtorExceptionSpec(classDecl);
7262
Chandler Carruth3f224b22011-09-20 04:55:26 +00007263 // Replace the destructor's type, building off the existing one. Fortunately,
7264 // the only thing of interest in the destructor type is its extended info.
7265 // The return and arguments are fixed.
7266 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007267 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7268 epi.NumExceptions = exceptSpec.size();
7269 epi.Exceptions = exceptSpec.data();
7270 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7271
7272 destructor->setType(ty);
7273
7274 // FIXME: If the destructor has a body that could throw, and the newly created
7275 // spec doesn't allow exceptions, we should emit a warning, because this
7276 // change in behavior can break conforming C++03 programs at runtime.
7277 // However, we don't have a body yet, so it needs to be done somewhere else.
7278}
7279
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007280/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007281/// \c To.
7282///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007283/// This routine is used to copy/move the members of a class with an
7284/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007285/// copied are arrays, this routine builds for loops to copy them.
7286///
7287/// \param S The Sema object used for type-checking.
7288///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007289/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007290///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007291/// \param T The type of the expressions being copied/moved. Both expressions
7292/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007293///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007294/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007295///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007296/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007297///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007298/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007299/// Otherwise, it's a non-static member subobject.
7300///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007301/// \param Copying Whether we're copying or moving.
7302///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007303/// \param Depth Internal parameter recording the depth of the recursion.
7304///
7305/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007306static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007307BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007308 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007309 bool CopyingBaseSubobject, bool Copying,
7310 unsigned Depth = 0) {
7311 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007312 // Each subobject is assigned in the manner appropriate to its type:
7313 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007314 // - if the subobject is of class type, as if by a call to operator= with
7315 // the subobject as the object expression and the corresponding
7316 // subobject of x as a single function argument (as if by explicit
7317 // qualification; that is, ignoring any possible virtual overriding
7318 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007319 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7320 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7321
7322 // Look for operator=.
7323 DeclarationName Name
7324 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7325 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7326 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7327
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007328 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007329 LookupResult::Filter F = OpLookup.makeFilter();
7330 while (F.hasNext()) {
7331 NamedDecl *D = F.next();
7332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007333 if (Copying ? Method->isCopyAssignmentOperator() :
7334 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007335 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007336
Douglas Gregor06a9f362010-05-01 20:49:11 +00007337 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007338 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007339 F.done();
7340
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007341 // Suppress the protected check (C++ [class.protected]) for each of the
7342 // assignment operators we found. This strange dance is required when
7343 // we're assigning via a base classes's copy-assignment operator. To
7344 // ensure that we're getting the right base class subobject (without
7345 // ambiguities), we need to cast "this" to that subobject type; to
7346 // ensure that we don't go through the virtual call mechanism, we need
7347 // to qualify the operator= name with the base class (see below). However,
7348 // this means that if the base class has a protected copy assignment
7349 // operator, the protected member access check will fail. So, we
7350 // rewrite "protected" access to "public" access in this case, since we
7351 // know by construction that we're calling from a derived class.
7352 if (CopyingBaseSubobject) {
7353 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7354 L != LEnd; ++L) {
7355 if (L.getAccess() == AS_protected)
7356 L.setAccess(AS_public);
7357 }
7358 }
7359
Douglas Gregor06a9f362010-05-01 20:49:11 +00007360 // Create the nested-name-specifier that will be used to qualify the
7361 // reference to operator=; this is required to suppress the virtual
7362 // call mechanism.
7363 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007364 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007365 SS.MakeTrivial(S.Context,
7366 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007367 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007368 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007369
7370 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007371 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007372 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007373 /*TemplateKWLoc=*/SourceLocation(),
7374 /*FirstQualifierInScope=*/0,
7375 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376 /*TemplateArgs=*/0,
7377 /*SuppressQualifierCheck=*/true);
7378 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007379 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007380
7381 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007382
John McCall60d7b3a2010-08-24 06:29:42 +00007383 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007384 OpEqualRef.takeAs<Expr>(),
7385 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007386 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007387 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007388
7389 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007390 }
John McCallb0207482010-03-16 06:11:48 +00007391
Douglas Gregor06a9f362010-05-01 20:49:11 +00007392 // - if the subobject is of scalar type, the built-in assignment
7393 // operator is used.
7394 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7395 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007396 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007397 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007398 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007399
7400 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007401 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007402
7403 // - if the subobject is an array, each element is assigned, in the
7404 // manner appropriate to the element type;
7405
7406 // Construct a loop over the array bounds, e.g.,
7407 //
7408 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7409 //
7410 // that will copy each of the array elements.
7411 QualType SizeType = S.Context.getSizeType();
7412
7413 // Create the iteration variable.
7414 IdentifierInfo *IterationVarName = 0;
7415 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007416 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007417 llvm::raw_svector_ostream OS(Str);
7418 OS << "__i" << Depth;
7419 IterationVarName = &S.Context.Idents.get(OS.str());
7420 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007421 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007422 IterationVarName, SizeType,
7423 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007424 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007425
7426 // Initialize the iteration variable to zero.
7427 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007428 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007429
7430 // Create a reference to the iteration variable; we'll use this several
7431 // times throughout.
7432 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007433 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007434 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007435 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7436 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7437
Douglas Gregor06a9f362010-05-01 20:49:11 +00007438 // Create the DeclStmt that holds the iteration variable.
7439 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7440
7441 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007442 llvm::APInt Upper
7443 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007444 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007445 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007446 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7447 BO_NE, S.Context.BoolTy,
7448 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007449
7450 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007451 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007452 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7453 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007454
7455 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007456 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007457 IterationVarRefRVal,
7458 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007459 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007460 IterationVarRefRVal,
7461 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007462 if (!Copying) // Cast to rvalue
7463 From = CastForMoving(S, From);
7464
7465 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007466 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7467 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007468 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007469 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007470 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007471
7472 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007473 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007474 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007475 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007476 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007477}
7478
Sean Hunt30de05c2011-05-14 05:23:20 +00007479std::pair<Sema::ImplicitExceptionSpecification, bool>
7480Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7481 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007482 if (ClassDecl->isInvalidDecl())
7483 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7484
Douglas Gregord3c35902010-07-01 16:36:15 +00007485 // C++ [class.copy]p10:
7486 // If the class definition does not explicitly declare a copy
7487 // assignment operator, one is declared implicitly.
7488 // The implicitly-defined copy assignment operator for a class X
7489 // will have the form
7490 //
7491 // X& X::operator=(const X&)
7492 //
7493 // if
7494 bool HasConstCopyAssignment = true;
7495
7496 // -- each direct base class B of X has a copy assignment operator
7497 // whose parameter is of type const B&, const volatile B& or B,
7498 // and
7499 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7500 BaseEnd = ClassDecl->bases_end();
7501 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007502 // We'll handle this below
7503 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7504 continue;
7505
Douglas Gregord3c35902010-07-01 16:36:15 +00007506 assert(!Base->getType()->isDependentType() &&
7507 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007508 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7509 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7510 &HasConstCopyAssignment);
7511 }
7512
Richard Smithebaf0e62011-10-18 20:49:44 +00007513 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007514 if (LangOpts.CPlusPlus0x) {
7515 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7516 BaseEnd = ClassDecl->vbases_end();
7517 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7518 assert(!Base->getType()->isDependentType() &&
7519 "Cannot generate implicit members for class with dependent bases.");
7520 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7521 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7522 &HasConstCopyAssignment);
7523 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007524 }
7525
7526 // -- for all the nonstatic data members of X that are of a class
7527 // type M (or array thereof), each such class type has a copy
7528 // assignment operator whose parameter is of type const M&,
7529 // const volatile M& or M.
7530 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7531 FieldEnd = ClassDecl->field_end();
7532 HasConstCopyAssignment && Field != FieldEnd;
7533 ++Field) {
7534 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007535 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7536 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7537 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007538 }
7539 }
7540
7541 // Otherwise, the implicitly declared copy assignment operator will
7542 // have the form
7543 //
7544 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007545
Douglas Gregorb87786f2010-07-01 17:48:08 +00007546 // C++ [except.spec]p14:
7547 // An implicitly declared special member function (Clause 12) shall have an
7548 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007549
7550 // It is unspecified whether or not an implicit copy assignment operator
7551 // attempts to deduplicate calls to assignment operators of virtual bases are
7552 // made. As such, this exception specification is effectively unspecified.
7553 // Based on a similar decision made for constness in C++0x, we're erring on
7554 // the side of assuming such calls to be made regardless of whether they
7555 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007556 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007557 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007558 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7559 BaseEnd = ClassDecl->bases_end();
7560 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007561 if (Base->isVirtual())
7562 continue;
7563
Douglas Gregora376d102010-07-02 21:50:04 +00007564 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007565 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007566 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7567 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007568 ExceptSpec.CalledDecl(CopyAssign);
7569 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007570
7571 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7572 BaseEnd = ClassDecl->vbases_end();
7573 Base != BaseEnd; ++Base) {
7574 CXXRecordDecl *BaseClassDecl
7575 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7576 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7577 ArgQuals, false, 0))
7578 ExceptSpec.CalledDecl(CopyAssign);
7579 }
7580
Douglas Gregorb87786f2010-07-01 17:48:08 +00007581 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7582 FieldEnd = ClassDecl->field_end();
7583 Field != FieldEnd;
7584 ++Field) {
7585 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007586 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7587 if (CXXMethodDecl *CopyAssign =
7588 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7589 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007590 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007591 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007592
Sean Hunt30de05c2011-05-14 05:23:20 +00007593 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7594}
7595
7596CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7597 // Note: The following rules are largely analoguous to the copy
7598 // constructor rules. Note that virtual bases are not taken into account
7599 // for determining the argument type of the operator. Note also that
7600 // operators taking an object instead of a reference are allowed.
7601
7602 ImplicitExceptionSpecification Spec(Context);
7603 bool Const;
7604 llvm::tie(Spec, Const) =
7605 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7606
7607 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7608 QualType RetType = Context.getLValueReferenceType(ArgType);
7609 if (Const)
7610 ArgType = ArgType.withConst();
7611 ArgType = Context.getLValueReferenceType(ArgType);
7612
Douglas Gregord3c35902010-07-01 16:36:15 +00007613 // An implicitly-declared copy assignment operator is an inline public
7614 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007615 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007616 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007617 SourceLocation ClassLoc = ClassDecl->getLocation();
7618 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007619 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007620 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007621 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007622 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007623 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007624 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007625 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007626 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007627 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007628 CopyAssignment->setImplicit();
7629 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007630
7631 // Add the parameter to the operator.
7632 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007633 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007634 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007635 SC_None,
7636 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007637 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007638
Douglas Gregora376d102010-07-02 21:50:04 +00007639 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007640 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007641
Douglas Gregor23c94db2010-07-02 17:43:08 +00007642 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007643 PushOnScopeChains(CopyAssignment, S, false);
7644 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007645
Nico Weberafcc96a2012-01-23 03:19:29 +00007646 // C++0x [class.copy]p19:
7647 // .... If the class definition does not explicitly declare a copy
7648 // assignment operator, there is no user-declared move constructor, and
7649 // there is no user-declared move assignment operator, a copy assignment
7650 // operator is implicitly declared as defaulted.
7651 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007652 !getLangOptions().MicrosoftMode) ||
7653 ClassDecl->hasUserDeclaredMoveAssignment() ||
Richard Smith7d5088a2012-02-18 02:02:13 +00007654 ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007655 CopyAssignment->setDeletedAsWritten();
7656
Douglas Gregord3c35902010-07-01 16:36:15 +00007657 AddOverriddenMethods(ClassDecl, CopyAssignment);
7658 return CopyAssignment;
7659}
7660
Douglas Gregor06a9f362010-05-01 20:49:11 +00007661void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7662 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007663 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007664 CopyAssignOperator->isOverloadedOperator() &&
7665 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007666 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7667 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007668 "DefineImplicitCopyAssignment called for wrong function");
7669
7670 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7671
7672 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7673 CopyAssignOperator->setInvalidDecl();
7674 return;
7675 }
7676
7677 CopyAssignOperator->setUsed();
7678
7679 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007680 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007681
7682 // C++0x [class.copy]p30:
7683 // The implicitly-defined or explicitly-defaulted copy assignment operator
7684 // for a non-union class X performs memberwise copy assignment of its
7685 // subobjects. The direct base classes of X are assigned first, in the
7686 // order of their declaration in the base-specifier-list, and then the
7687 // immediate non-static data members of X are assigned, in the order in
7688 // which they were declared in the class definition.
7689
7690 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007691 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007692
7693 // The parameter for the "other" object, which we are copying from.
7694 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7695 Qualifiers OtherQuals = Other->getType().getQualifiers();
7696 QualType OtherRefType = Other->getType();
7697 if (const LValueReferenceType *OtherRef
7698 = OtherRefType->getAs<LValueReferenceType>()) {
7699 OtherRefType = OtherRef->getPointeeType();
7700 OtherQuals = OtherRefType.getQualifiers();
7701 }
7702
7703 // Our location for everything implicitly-generated.
7704 SourceLocation Loc = CopyAssignOperator->getLocation();
7705
7706 // Construct a reference to the "other" object. We'll be using this
7707 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007708 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709 assert(OtherRef && "Reference to parameter cannot fail!");
7710
7711 // Construct the "this" pointer. We'll be using this throughout the generated
7712 // ASTs.
7713 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7714 assert(This && "Reference to this cannot fail!");
7715
7716 // Assign base classes.
7717 bool Invalid = false;
7718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7719 E = ClassDecl->bases_end(); Base != E; ++Base) {
7720 // Form the assignment:
7721 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7722 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007723 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007724 Invalid = true;
7725 continue;
7726 }
7727
John McCallf871d0c2010-08-07 06:22:56 +00007728 CXXCastPath BasePath;
7729 BasePath.push_back(Base);
7730
Douglas Gregor06a9f362010-05-01 20:49:11 +00007731 // Construct the "from" expression, which is an implicit cast to the
7732 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007733 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007734 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7735 CK_UncheckedDerivedToBase,
7736 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007737
7738 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007739 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007740
7741 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007742 To = ImpCastExprToType(To.take(),
7743 Context.getCVRQualifiedType(BaseType,
7744 CopyAssignOperator->getTypeQualifiers()),
7745 CK_UncheckedDerivedToBase,
7746 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007747
7748 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007749 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007750 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007751 /*CopyingBaseSubobject=*/true,
7752 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007753 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007754 Diag(CurrentLocation, diag::note_member_synthesized_at)
7755 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7756 CopyAssignOperator->setInvalidDecl();
7757 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007758 }
7759
7760 // Success! Record the copy.
7761 Statements.push_back(Copy.takeAs<Expr>());
7762 }
7763
7764 // \brief Reference to the __builtin_memcpy function.
7765 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007766 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007767 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007768
7769 // Assign non-static members.
7770 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7771 FieldEnd = ClassDecl->field_end();
7772 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007773 if (Field->isUnnamedBitfield())
7774 continue;
7775
Douglas Gregor06a9f362010-05-01 20:49:11 +00007776 // Check for members of reference type; we can't copy those.
7777 if (Field->getType()->isReferenceType()) {
7778 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7779 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7780 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007781 Diag(CurrentLocation, diag::note_member_synthesized_at)
7782 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007783 Invalid = true;
7784 continue;
7785 }
7786
7787 // Check for members of const-qualified, non-class type.
7788 QualType BaseType = Context.getBaseElementType(Field->getType());
7789 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7790 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7791 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7792 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007793 Diag(CurrentLocation, diag::note_member_synthesized_at)
7794 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007795 Invalid = true;
7796 continue;
7797 }
John McCallb77115d2011-06-17 00:18:42 +00007798
7799 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007800 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7801 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007802
7803 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007804 if (FieldType->isIncompleteArrayType()) {
7805 assert(ClassDecl->hasFlexibleArrayMember() &&
7806 "Incomplete array type is not valid");
7807 continue;
7808 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007809
7810 // Build references to the field in the object we're copying from and to.
7811 CXXScopeSpec SS; // Intentionally empty
7812 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7813 LookupMemberName);
7814 MemberLookup.addDecl(*Field);
7815 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007816 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007817 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007818 SS, SourceLocation(), 0,
7819 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007820 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007821 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007822 SS, SourceLocation(), 0,
7823 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007824 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7825 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7826
7827 // If the field should be copied with __builtin_memcpy rather than via
7828 // explicit assignments, do so. This optimization only applies for arrays
7829 // of scalars and arrays of class type with trivial copy-assignment
7830 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007831 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007832 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007833 // Compute the size of the memory buffer to be copied.
7834 QualType SizeType = Context.getSizeType();
7835 llvm::APInt Size(Context.getTypeSize(SizeType),
7836 Context.getTypeSizeInChars(BaseType).getQuantity());
7837 for (const ConstantArrayType *Array
7838 = Context.getAsConstantArrayType(FieldType);
7839 Array;
7840 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007841 llvm::APInt ArraySize
7842 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007843 Size *= ArraySize;
7844 }
7845
7846 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007847 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7848 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007849
7850 bool NeedsCollectableMemCpy =
7851 (BaseType->isRecordType() &&
7852 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7853
7854 if (NeedsCollectableMemCpy) {
7855 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007856 // Create a reference to the __builtin_objc_memmove_collectable function.
7857 LookupResult R(*this,
7858 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007859 Loc, LookupOrdinaryName);
7860 LookupName(R, TUScope, true);
7861
7862 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7863 if (!CollectableMemCpy) {
7864 // Something went horribly wrong earlier, and we will have
7865 // complained about it.
7866 Invalid = true;
7867 continue;
7868 }
7869
7870 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7871 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007872 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007873 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7874 }
7875 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007876 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007877 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007878 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7879 LookupOrdinaryName);
7880 LookupName(R, TUScope, true);
7881
7882 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7883 if (!BuiltinMemCpy) {
7884 // Something went horribly wrong earlier, and we will have complained
7885 // about it.
7886 Invalid = true;
7887 continue;
7888 }
7889
7890 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7891 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007892 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007893 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7894 }
7895
John McCallca0408f2010-08-23 06:44:23 +00007896 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007897 CallArgs.push_back(To.takeAs<Expr>());
7898 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007899 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007900 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007901 if (NeedsCollectableMemCpy)
7902 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007903 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007904 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007905 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007906 else
7907 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007908 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007909 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007910 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007911
Douglas Gregor06a9f362010-05-01 20:49:11 +00007912 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7913 Statements.push_back(Call.takeAs<Expr>());
7914 continue;
7915 }
7916
7917 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007918 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007919 To.get(), From.get(),
7920 /*CopyingBaseSubobject=*/false,
7921 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007922 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007923 Diag(CurrentLocation, diag::note_member_synthesized_at)
7924 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7925 CopyAssignOperator->setInvalidDecl();
7926 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007927 }
7928
7929 // Success! Record the copy.
7930 Statements.push_back(Copy.takeAs<Stmt>());
7931 }
7932
7933 if (!Invalid) {
7934 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007935 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007936
John McCall60d7b3a2010-08-24 06:29:42 +00007937 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007938 if (Return.isInvalid())
7939 Invalid = true;
7940 else {
7941 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007942
7943 if (Trap.hasErrorOccurred()) {
7944 Diag(CurrentLocation, diag::note_member_synthesized_at)
7945 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7946 Invalid = true;
7947 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007948 }
7949 }
7950
7951 if (Invalid) {
7952 CopyAssignOperator->setInvalidDecl();
7953 return;
7954 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007955
7956 StmtResult Body;
7957 {
7958 CompoundScopeRAII CompoundScope(*this);
7959 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7960 /*isStmtExpr=*/false);
7961 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7962 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007963 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007964
7965 if (ASTMutationListener *L = getASTMutationListener()) {
7966 L->CompletedImplicitDefinition(CopyAssignOperator);
7967 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007968}
7969
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007970Sema::ImplicitExceptionSpecification
7971Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7972 ImplicitExceptionSpecification ExceptSpec(Context);
7973
7974 if (ClassDecl->isInvalidDecl())
7975 return ExceptSpec;
7976
7977 // C++0x [except.spec]p14:
7978 // An implicitly declared special member function (Clause 12) shall have an
7979 // exception-specification. [...]
7980
7981 // It is unspecified whether or not an implicit move assignment operator
7982 // attempts to deduplicate calls to assignment operators of virtual bases are
7983 // made. As such, this exception specification is effectively unspecified.
7984 // Based on a similar decision made for constness in C++0x, we're erring on
7985 // the side of assuming such calls to be made regardless of whether they
7986 // actually happen.
7987 // Note that a move constructor is not implicitly declared when there are
7988 // virtual bases, but it can still be user-declared and explicitly defaulted.
7989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7990 BaseEnd = ClassDecl->bases_end();
7991 Base != BaseEnd; ++Base) {
7992 if (Base->isVirtual())
7993 continue;
7994
7995 CXXRecordDecl *BaseClassDecl
7996 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7997 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7998 false, 0))
7999 ExceptSpec.CalledDecl(MoveAssign);
8000 }
8001
8002 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8003 BaseEnd = ClassDecl->vbases_end();
8004 Base != BaseEnd; ++Base) {
8005 CXXRecordDecl *BaseClassDecl
8006 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8007 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8008 false, 0))
8009 ExceptSpec.CalledDecl(MoveAssign);
8010 }
8011
8012 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8013 FieldEnd = ClassDecl->field_end();
8014 Field != FieldEnd;
8015 ++Field) {
8016 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8017 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8018 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8019 false, 0))
8020 ExceptSpec.CalledDecl(MoveAssign);
8021 }
8022 }
8023
8024 return ExceptSpec;
8025}
8026
8027CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8028 // Note: The following rules are largely analoguous to the move
8029 // constructor rules.
8030
8031 ImplicitExceptionSpecification Spec(
8032 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8033
8034 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8035 QualType RetType = Context.getLValueReferenceType(ArgType);
8036 ArgType = Context.getRValueReferenceType(ArgType);
8037
8038 // An implicitly-declared move assignment operator is an inline public
8039 // member of its class.
8040 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8041 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8042 SourceLocation ClassLoc = ClassDecl->getLocation();
8043 DeclarationNameInfo NameInfo(Name, ClassLoc);
8044 CXXMethodDecl *MoveAssignment
8045 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8046 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8047 /*TInfo=*/0, /*isStatic=*/false,
8048 /*StorageClassAsWritten=*/SC_None,
8049 /*isInline=*/true,
8050 /*isConstexpr=*/false,
8051 SourceLocation());
8052 MoveAssignment->setAccess(AS_public);
8053 MoveAssignment->setDefaulted();
8054 MoveAssignment->setImplicit();
8055 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8056
8057 // Add the parameter to the operator.
8058 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8059 ClassLoc, ClassLoc, /*Id=*/0,
8060 ArgType, /*TInfo=*/0,
8061 SC_None,
8062 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008063 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008064
8065 // Note that we have added this copy-assignment operator.
8066 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8067
8068 // C++0x [class.copy]p9:
8069 // If the definition of a class X does not explicitly declare a move
8070 // assignment operator, one will be implicitly declared as defaulted if and
8071 // only if:
8072 // [...]
8073 // - the move assignment operator would not be implicitly defined as
8074 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008075 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008076 // Cache this result so that we don't try to generate this over and over
8077 // on every lookup, leaking memory and wasting time.
8078 ClassDecl->setFailedImplicitMoveAssignment();
8079 return 0;
8080 }
8081
8082 if (Scope *S = getScopeForContext(ClassDecl))
8083 PushOnScopeChains(MoveAssignment, S, false);
8084 ClassDecl->addDecl(MoveAssignment);
8085
8086 AddOverriddenMethods(ClassDecl, MoveAssignment);
8087 return MoveAssignment;
8088}
8089
8090void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8091 CXXMethodDecl *MoveAssignOperator) {
8092 assert((MoveAssignOperator->isDefaulted() &&
8093 MoveAssignOperator->isOverloadedOperator() &&
8094 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008095 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8096 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008097 "DefineImplicitMoveAssignment called for wrong function");
8098
8099 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8100
8101 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8102 MoveAssignOperator->setInvalidDecl();
8103 return;
8104 }
8105
8106 MoveAssignOperator->setUsed();
8107
8108 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8109 DiagnosticErrorTrap Trap(Diags);
8110
8111 // C++0x [class.copy]p28:
8112 // The implicitly-defined or move assignment operator for a non-union class
8113 // X performs memberwise move assignment of its subobjects. The direct base
8114 // classes of X are assigned first, in the order of their declaration in the
8115 // base-specifier-list, and then the immediate non-static data members of X
8116 // are assigned, in the order in which they were declared in the class
8117 // definition.
8118
8119 // The statements that form the synthesized function body.
8120 ASTOwningVector<Stmt*> Statements(*this);
8121
8122 // The parameter for the "other" object, which we are move from.
8123 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8124 QualType OtherRefType = Other->getType()->
8125 getAs<RValueReferenceType>()->getPointeeType();
8126 assert(OtherRefType.getQualifiers() == 0 &&
8127 "Bad argument type of defaulted move assignment");
8128
8129 // Our location for everything implicitly-generated.
8130 SourceLocation Loc = MoveAssignOperator->getLocation();
8131
8132 // Construct a reference to the "other" object. We'll be using this
8133 // throughout the generated ASTs.
8134 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8135 assert(OtherRef && "Reference to parameter cannot fail!");
8136 // Cast to rvalue.
8137 OtherRef = CastForMoving(*this, OtherRef);
8138
8139 // Construct the "this" pointer. We'll be using this throughout the generated
8140 // ASTs.
8141 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8142 assert(This && "Reference to this cannot fail!");
8143
8144 // Assign base classes.
8145 bool Invalid = false;
8146 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8147 E = ClassDecl->bases_end(); Base != E; ++Base) {
8148 // Form the assignment:
8149 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8150 QualType BaseType = Base->getType().getUnqualifiedType();
8151 if (!BaseType->isRecordType()) {
8152 Invalid = true;
8153 continue;
8154 }
8155
8156 CXXCastPath BasePath;
8157 BasePath.push_back(Base);
8158
8159 // Construct the "from" expression, which is an implicit cast to the
8160 // appropriately-qualified base type.
8161 Expr *From = OtherRef;
8162 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008163 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008164
8165 // Dereference "this".
8166 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8167
8168 // Implicitly cast "this" to the appropriately-qualified base type.
8169 To = ImpCastExprToType(To.take(),
8170 Context.getCVRQualifiedType(BaseType,
8171 MoveAssignOperator->getTypeQualifiers()),
8172 CK_UncheckedDerivedToBase,
8173 VK_LValue, &BasePath);
8174
8175 // Build the move.
8176 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8177 To.get(), From,
8178 /*CopyingBaseSubobject=*/true,
8179 /*Copying=*/false);
8180 if (Move.isInvalid()) {
8181 Diag(CurrentLocation, diag::note_member_synthesized_at)
8182 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8183 MoveAssignOperator->setInvalidDecl();
8184 return;
8185 }
8186
8187 // Success! Record the move.
8188 Statements.push_back(Move.takeAs<Expr>());
8189 }
8190
8191 // \brief Reference to the __builtin_memcpy function.
8192 Expr *BuiltinMemCpyRef = 0;
8193 // \brief Reference to the __builtin_objc_memmove_collectable function.
8194 Expr *CollectableMemCpyRef = 0;
8195
8196 // Assign non-static members.
8197 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8198 FieldEnd = ClassDecl->field_end();
8199 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008200 if (Field->isUnnamedBitfield())
8201 continue;
8202
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008203 // Check for members of reference type; we can't move those.
8204 if (Field->getType()->isReferenceType()) {
8205 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8206 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8207 Diag(Field->getLocation(), diag::note_declared_at);
8208 Diag(CurrentLocation, diag::note_member_synthesized_at)
8209 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8210 Invalid = true;
8211 continue;
8212 }
8213
8214 // Check for members of const-qualified, non-class type.
8215 QualType BaseType = Context.getBaseElementType(Field->getType());
8216 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8217 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8218 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8219 Diag(Field->getLocation(), diag::note_declared_at);
8220 Diag(CurrentLocation, diag::note_member_synthesized_at)
8221 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8222 Invalid = true;
8223 continue;
8224 }
8225
8226 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008227 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8228 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008229
8230 QualType FieldType = Field->getType().getNonReferenceType();
8231 if (FieldType->isIncompleteArrayType()) {
8232 assert(ClassDecl->hasFlexibleArrayMember() &&
8233 "Incomplete array type is not valid");
8234 continue;
8235 }
8236
8237 // Build references to the field in the object we're copying from and to.
8238 CXXScopeSpec SS; // Intentionally empty
8239 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8240 LookupMemberName);
8241 MemberLookup.addDecl(*Field);
8242 MemberLookup.resolveKind();
8243 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8244 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008245 SS, SourceLocation(), 0,
8246 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008247 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8248 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008249 SS, SourceLocation(), 0,
8250 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008251 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8252 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8253
8254 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8255 "Member reference with rvalue base must be rvalue except for reference "
8256 "members, which aren't allowed for move assignment.");
8257
8258 // If the field should be copied with __builtin_memcpy rather than via
8259 // explicit assignments, do so. This optimization only applies for arrays
8260 // of scalars and arrays of class type with trivial move-assignment
8261 // operators.
8262 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8263 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8264 // Compute the size of the memory buffer to be copied.
8265 QualType SizeType = Context.getSizeType();
8266 llvm::APInt Size(Context.getTypeSize(SizeType),
8267 Context.getTypeSizeInChars(BaseType).getQuantity());
8268 for (const ConstantArrayType *Array
8269 = Context.getAsConstantArrayType(FieldType);
8270 Array;
8271 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8272 llvm::APInt ArraySize
8273 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8274 Size *= ArraySize;
8275 }
8276
Douglas Gregor45d3d712011-09-01 02:09:07 +00008277 // Take the address of the field references for "from" and "to". We
8278 // directly construct UnaryOperators here because semantic analysis
8279 // does not permit us to take the address of an xvalue.
8280 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8281 Context.getPointerType(From.get()->getType()),
8282 VK_RValue, OK_Ordinary, Loc);
8283 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8284 Context.getPointerType(To.get()->getType()),
8285 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008286
8287 bool NeedsCollectableMemCpy =
8288 (BaseType->isRecordType() &&
8289 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8290
8291 if (NeedsCollectableMemCpy) {
8292 if (!CollectableMemCpyRef) {
8293 // Create a reference to the __builtin_objc_memmove_collectable function.
8294 LookupResult R(*this,
8295 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8296 Loc, LookupOrdinaryName);
8297 LookupName(R, TUScope, true);
8298
8299 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8300 if (!CollectableMemCpy) {
8301 // Something went horribly wrong earlier, and we will have
8302 // complained about it.
8303 Invalid = true;
8304 continue;
8305 }
8306
8307 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8308 CollectableMemCpy->getType(),
8309 VK_LValue, Loc, 0).take();
8310 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8311 }
8312 }
8313 // Create a reference to the __builtin_memcpy builtin function.
8314 else if (!BuiltinMemCpyRef) {
8315 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8316 LookupOrdinaryName);
8317 LookupName(R, TUScope, true);
8318
8319 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8320 if (!BuiltinMemCpy) {
8321 // Something went horribly wrong earlier, and we will have complained
8322 // about it.
8323 Invalid = true;
8324 continue;
8325 }
8326
8327 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8328 BuiltinMemCpy->getType(),
8329 VK_LValue, Loc, 0).take();
8330 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8331 }
8332
8333 ASTOwningVector<Expr*> CallArgs(*this);
8334 CallArgs.push_back(To.takeAs<Expr>());
8335 CallArgs.push_back(From.takeAs<Expr>());
8336 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8337 ExprResult Call = ExprError();
8338 if (NeedsCollectableMemCpy)
8339 Call = ActOnCallExpr(/*Scope=*/0,
8340 CollectableMemCpyRef,
8341 Loc, move_arg(CallArgs),
8342 Loc);
8343 else
8344 Call = ActOnCallExpr(/*Scope=*/0,
8345 BuiltinMemCpyRef,
8346 Loc, move_arg(CallArgs),
8347 Loc);
8348
8349 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8350 Statements.push_back(Call.takeAs<Expr>());
8351 continue;
8352 }
8353
8354 // Build the move of this field.
8355 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8356 To.get(), From.get(),
8357 /*CopyingBaseSubobject=*/false,
8358 /*Copying=*/false);
8359 if (Move.isInvalid()) {
8360 Diag(CurrentLocation, diag::note_member_synthesized_at)
8361 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8362 MoveAssignOperator->setInvalidDecl();
8363 return;
8364 }
8365
8366 // Success! Record the copy.
8367 Statements.push_back(Move.takeAs<Stmt>());
8368 }
8369
8370 if (!Invalid) {
8371 // Add a "return *this;"
8372 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8373
8374 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8375 if (Return.isInvalid())
8376 Invalid = true;
8377 else {
8378 Statements.push_back(Return.takeAs<Stmt>());
8379
8380 if (Trap.hasErrorOccurred()) {
8381 Diag(CurrentLocation, diag::note_member_synthesized_at)
8382 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8383 Invalid = true;
8384 }
8385 }
8386 }
8387
8388 if (Invalid) {
8389 MoveAssignOperator->setInvalidDecl();
8390 return;
8391 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008392
8393 StmtResult Body;
8394 {
8395 CompoundScopeRAII CompoundScope(*this);
8396 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8397 /*isStmtExpr=*/false);
8398 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8399 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008400 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8401
8402 if (ASTMutationListener *L = getASTMutationListener()) {
8403 L->CompletedImplicitDefinition(MoveAssignOperator);
8404 }
8405}
8406
Sean Hunt49634cf2011-05-13 06:10:58 +00008407std::pair<Sema::ImplicitExceptionSpecification, bool>
8408Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008409 if (ClassDecl->isInvalidDecl())
8410 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8411
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008412 // C++ [class.copy]p5:
8413 // The implicitly-declared copy constructor for a class X will
8414 // have the form
8415 //
8416 // X::X(const X&)
8417 //
8418 // if
Sean Huntc530d172011-06-10 04:44:37 +00008419 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008420 bool HasConstCopyConstructor = true;
8421
8422 // -- each direct or virtual base class B of X has a copy
8423 // constructor whose first parameter is of type const B& or
8424 // const volatile B&, and
8425 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8426 BaseEnd = ClassDecl->bases_end();
8427 HasConstCopyConstructor && Base != BaseEnd;
8428 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008429 // Virtual bases are handled below.
8430 if (Base->isVirtual())
8431 continue;
8432
Douglas Gregor22584312010-07-02 23:41:54 +00008433 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008434 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008435 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8436 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008437 }
8438
8439 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8440 BaseEnd = ClassDecl->vbases_end();
8441 HasConstCopyConstructor && Base != BaseEnd;
8442 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008443 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008444 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008445 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8446 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008447 }
8448
8449 // -- for all the nonstatic data members of X that are of a
8450 // class type M (or array thereof), each such class type
8451 // has a copy constructor whose first parameter is of type
8452 // const M& or const volatile M&.
8453 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8454 FieldEnd = ClassDecl->field_end();
8455 HasConstCopyConstructor && Field != FieldEnd;
8456 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008457 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008458 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008459 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8460 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008461 }
8462 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008463 // Otherwise, the implicitly declared copy constructor will have
8464 // the form
8465 //
8466 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008467
Douglas Gregor0d405db2010-07-01 20:59:04 +00008468 // C++ [except.spec]p14:
8469 // An implicitly declared special member function (Clause 12) shall have an
8470 // exception-specification. [...]
8471 ImplicitExceptionSpecification ExceptSpec(Context);
8472 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8473 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8474 BaseEnd = ClassDecl->bases_end();
8475 Base != BaseEnd;
8476 ++Base) {
8477 // Virtual bases are handled below.
8478 if (Base->isVirtual())
8479 continue;
8480
Douglas Gregor22584312010-07-02 23:41:54 +00008481 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008482 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008483 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008484 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008485 ExceptSpec.CalledDecl(CopyConstructor);
8486 }
8487 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8488 BaseEnd = ClassDecl->vbases_end();
8489 Base != BaseEnd;
8490 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008491 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008492 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008493 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008494 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008495 ExceptSpec.CalledDecl(CopyConstructor);
8496 }
8497 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8498 FieldEnd = ClassDecl->field_end();
8499 Field != FieldEnd;
8500 ++Field) {
8501 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008502 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8503 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008504 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008505 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008506 }
8507 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008508
Sean Hunt49634cf2011-05-13 06:10:58 +00008509 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8510}
8511
8512CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8513 CXXRecordDecl *ClassDecl) {
8514 // C++ [class.copy]p4:
8515 // If the class definition does not explicitly declare a copy
8516 // constructor, one is declared implicitly.
8517
8518 ImplicitExceptionSpecification Spec(Context);
8519 bool Const;
8520 llvm::tie(Spec, Const) =
8521 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8522
8523 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8524 QualType ArgType = ClassType;
8525 if (Const)
8526 ArgType = ArgType.withConst();
8527 ArgType = Context.getLValueReferenceType(ArgType);
8528
8529 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8530
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008531 DeclarationName Name
8532 = Context.DeclarationNames.getCXXConstructorName(
8533 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008534 SourceLocation ClassLoc = ClassDecl->getLocation();
8535 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008536
8537 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008538 // member of its class.
8539 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8540 Context, ClassDecl, ClassLoc, NameInfo,
8541 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8542 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8543 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8544 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008545 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008546 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008547 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008548
Douglas Gregor22584312010-07-02 23:41:54 +00008549 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008550 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8551
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008552 // Add the parameter to the constructor.
8553 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008554 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008555 /*IdentifierInfo=*/0,
8556 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008557 SC_None,
8558 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008559 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008560
Douglas Gregor23c94db2010-07-02 17:43:08 +00008561 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008562 PushOnScopeChains(CopyConstructor, S, false);
8563 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008564
Nico Weberafcc96a2012-01-23 03:19:29 +00008565 // C++11 [class.copy]p8:
8566 // ... If the class definition does not explicitly declare a copy
8567 // constructor, there is no user-declared move constructor, and there is no
8568 // user-declared move assignment operator, a copy constructor is implicitly
8569 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008570 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008571 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008572 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008573 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008574 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008575
8576 return CopyConstructor;
8577}
8578
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008579void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008580 CXXConstructorDecl *CopyConstructor) {
8581 assert((CopyConstructor->isDefaulted() &&
8582 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008583 !CopyConstructor->doesThisDeclarationHaveABody() &&
8584 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008585 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008586
Anders Carlsson63010a72010-04-23 16:24:12 +00008587 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008588 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008589
Douglas Gregor39957dc2010-05-01 15:04:51 +00008590 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008591 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008592
Sean Huntcbb67482011-01-08 20:30:50 +00008593 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008594 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008595 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008596 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008597 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008598 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008599 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008600 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8601 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008602 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008603 /*isStmtExpr=*/false)
8604 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008605 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008606 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008607
8608 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008609 if (ASTMutationListener *L = getASTMutationListener()) {
8610 L->CompletedImplicitDefinition(CopyConstructor);
8611 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008612}
8613
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008614Sema::ImplicitExceptionSpecification
8615Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8616 // C++ [except.spec]p14:
8617 // An implicitly declared special member function (Clause 12) shall have an
8618 // exception-specification. [...]
8619 ImplicitExceptionSpecification ExceptSpec(Context);
8620 if (ClassDecl->isInvalidDecl())
8621 return ExceptSpec;
8622
8623 // Direct base-class constructors.
8624 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8625 BEnd = ClassDecl->bases_end();
8626 B != BEnd; ++B) {
8627 if (B->isVirtual()) // Handled below.
8628 continue;
8629
8630 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8631 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8632 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8633 // If this is a deleted function, add it anyway. This might be conformant
8634 // with the standard. This might not. I'm not sure. It might not matter.
8635 if (Constructor)
8636 ExceptSpec.CalledDecl(Constructor);
8637 }
8638 }
8639
8640 // Virtual base-class constructors.
8641 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8642 BEnd = ClassDecl->vbases_end();
8643 B != BEnd; ++B) {
8644 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8645 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8646 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8647 // If this is a deleted function, add it anyway. This might be conformant
8648 // with the standard. This might not. I'm not sure. It might not matter.
8649 if (Constructor)
8650 ExceptSpec.CalledDecl(Constructor);
8651 }
8652 }
8653
8654 // Field constructors.
8655 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8656 FEnd = ClassDecl->field_end();
8657 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008658 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008659 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8660 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8661 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8662 // If this is a deleted function, add it anyway. This might be conformant
8663 // with the standard. This might not. I'm not sure. It might not matter.
8664 // In particular, the problem is that this function never gets called. It
8665 // might just be ill-formed because this function attempts to refer to
8666 // a deleted function here.
8667 if (Constructor)
8668 ExceptSpec.CalledDecl(Constructor);
8669 }
8670 }
8671
8672 return ExceptSpec;
8673}
8674
8675CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8676 CXXRecordDecl *ClassDecl) {
8677 ImplicitExceptionSpecification Spec(
8678 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8679
8680 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8681 QualType ArgType = Context.getRValueReferenceType(ClassType);
8682
8683 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8684
8685 DeclarationName Name
8686 = Context.DeclarationNames.getCXXConstructorName(
8687 Context.getCanonicalType(ClassType));
8688 SourceLocation ClassLoc = ClassDecl->getLocation();
8689 DeclarationNameInfo NameInfo(Name, ClassLoc);
8690
8691 // C++0x [class.copy]p11:
8692 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008693 // member of its class.
8694 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8695 Context, ClassDecl, ClassLoc, NameInfo,
8696 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8697 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8698 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8699 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008700 MoveConstructor->setAccess(AS_public);
8701 MoveConstructor->setDefaulted();
8702 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008703
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704 // Add the parameter to the constructor.
8705 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8706 ClassLoc, ClassLoc,
8707 /*IdentifierInfo=*/0,
8708 ArgType, /*TInfo=*/0,
8709 SC_None,
8710 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008711 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008712
8713 // C++0x [class.copy]p9:
8714 // If the definition of a class X does not explicitly declare a move
8715 // constructor, one will be implicitly declared as defaulted if and only if:
8716 // [...]
8717 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008718 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008719 // Cache this result so that we don't try to generate this over and over
8720 // on every lookup, leaking memory and wasting time.
8721 ClassDecl->setFailedImplicitMoveConstructor();
8722 return 0;
8723 }
8724
8725 // Note that we have declared this constructor.
8726 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8727
8728 if (Scope *S = getScopeForContext(ClassDecl))
8729 PushOnScopeChains(MoveConstructor, S, false);
8730 ClassDecl->addDecl(MoveConstructor);
8731
8732 return MoveConstructor;
8733}
8734
8735void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8736 CXXConstructorDecl *MoveConstructor) {
8737 assert((MoveConstructor->isDefaulted() &&
8738 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008739 !MoveConstructor->doesThisDeclarationHaveABody() &&
8740 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008741 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8742
8743 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8744 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8745
8746 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8747 DiagnosticErrorTrap Trap(Diags);
8748
8749 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8750 Trap.hasErrorOccurred()) {
8751 Diag(CurrentLocation, diag::note_member_synthesized_at)
8752 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8753 MoveConstructor->setInvalidDecl();
8754 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008755 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008756 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8757 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008758 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759 /*isStmtExpr=*/false)
8760 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008761 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008762 }
8763
8764 MoveConstructor->setUsed();
8765
8766 if (ASTMutationListener *L = getASTMutationListener()) {
8767 L->CompletedImplicitDefinition(MoveConstructor);
8768 }
8769}
8770
Douglas Gregore4e68d42012-02-15 19:33:52 +00008771bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8772 return FD->isDeleted() &&
8773 (FD->isDefaulted() || FD->isImplicit()) &&
8774 isa<CXXMethodDecl>(FD);
8775}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008776
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008777/// \brief Mark the call operator of the given lambda closure type as "used".
8778static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8779 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008780 = cast<CXXMethodDecl>(
8781 *Lambda->lookup(
8782 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008783 CallOperator->setReferenced();
8784 CallOperator->setUsed();
8785}
8786
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008787void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8788 SourceLocation CurrentLocation,
8789 CXXConversionDecl *Conv)
8790{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008791 CXXRecordDecl *Lambda = Conv->getParent();
8792
8793 // Make sure that the lambda call operator is marked used.
8794 markLambdaCallOperatorUsed(*this, Lambda);
8795
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008796 Conv->setUsed();
8797
8798 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8799 DiagnosticErrorTrap Trap(Diags);
8800
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008801 // Return the address of the __invoke function.
8802 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8803 CXXMethodDecl *Invoke
8804 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8805 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8806 VK_LValue, Conv->getLocation()).take();
8807 assert(FunctionRef && "Can't refer to __invoke function?");
8808 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8809 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8810 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008811 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008812
8813 // Fill in the __invoke function with a dummy implementation. IR generation
8814 // will fill in the actual details.
8815 Invoke->setUsed();
8816 Invoke->setReferenced();
8817 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8818 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008819
8820 if (ASTMutationListener *L = getASTMutationListener()) {
8821 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008822 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008823 }
8824}
8825
8826void Sema::DefineImplicitLambdaToBlockPointerConversion(
8827 SourceLocation CurrentLocation,
8828 CXXConversionDecl *Conv)
8829{
8830 Conv->setUsed();
8831
8832 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8833 DiagnosticErrorTrap Trap(Diags);
8834
Douglas Gregorac1303e2012-02-22 05:02:47 +00008835 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008836 Expr *This = ActOnCXXThis(CurrentLocation).take();
8837 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008838
Eli Friedman23f02672012-03-01 04:01:32 +00008839 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8840 Conv->getLocation(),
8841 Conv, DerefThis);
8842
8843 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8844 // behavior. Note that only the general conversion function does this
8845 // (since it's unusable otherwise); in the case where we inline the
8846 // block literal, it has block literal lifetime semantics.
8847 if (!BuildBlock.isInvalid() && !getLangOptions().ObjCAutoRefCount)
8848 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8849 CK_CopyAndAutoreleaseBlockObject,
8850 BuildBlock.get(), 0, VK_RValue);
8851
8852 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008853 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008854 Conv->setInvalidDecl();
8855 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008856 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008857
Douglas Gregorac1303e2012-02-22 05:02:47 +00008858 // Create the return statement that returns the block from the conversion
8859 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008860 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008861 if (Return.isInvalid()) {
8862 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8863 Conv->setInvalidDecl();
8864 return;
8865 }
8866
8867 // Set the body of the conversion function.
8868 Stmt *ReturnS = Return.take();
8869 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8870 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008871 Conv->getLocation()));
8872
Douglas Gregorac1303e2012-02-22 05:02:47 +00008873 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008874 if (ASTMutationListener *L = getASTMutationListener()) {
8875 L->CompletedImplicitDefinition(Conv);
8876 }
8877}
8878
Douglas Gregorf52757d2012-03-10 06:53:13 +00008879/// \brief Determine whether the given list arguments contains exactly one
8880/// "real" (non-default) argument.
8881static bool hasOneRealArgument(MultiExprArg Args) {
8882 switch (Args.size()) {
8883 case 0:
8884 return false;
8885
8886 default:
8887 if (!Args.get()[1]->isDefaultArgument())
8888 return false;
8889
8890 // fall through
8891 case 1:
8892 return !Args.get()[0]->isDefaultArgument();
8893 }
8894
8895 return false;
8896}
8897
John McCall60d7b3a2010-08-24 06:29:42 +00008898ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008899Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008900 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008901 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008902 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008903 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008904 unsigned ConstructKind,
8905 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008906 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008907
Douglas Gregor2f599792010-04-02 18:24:57 +00008908 // C++0x [class.copy]p34:
8909 // When certain criteria are met, an implementation is allowed to
8910 // omit the copy/move construction of a class object, even if the
8911 // copy/move constructor and/or destructor for the object have
8912 // side effects. [...]
8913 // - when a temporary class object that has not been bound to a
8914 // reference (12.2) would be copied/moved to a class object
8915 // with the same cv-unqualified type, the copy/move operation
8916 // can be omitted by constructing the temporary object
8917 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008918 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00008919 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008920 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008921 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008922 }
Mike Stump1eb44332009-09-09 15:08:12 +00008923
8924 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008925 Elidable, move(ExprArgs), HadMultipleCandidates,
8926 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008927}
8928
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008929/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8930/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008931ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008932Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8933 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008934 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008935 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008936 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008937 unsigned ConstructKind,
8938 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008939 unsigned NumExprs = ExprArgs.size();
8940 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008941
Nick Lewycky909a70d2011-03-25 01:44:32 +00008942 for (specific_attr_iterator<NonNullAttr>
8943 i = Constructor->specific_attr_begin<NonNullAttr>(),
8944 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8945 const NonNullAttr *NonNull = *i;
8946 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8947 }
8948
Eli Friedman5f2987c2012-02-02 03:46:19 +00008949 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008950 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008951 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008952 HadMultipleCandidates, /*FIXME*/false,
8953 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008954 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8955 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008956}
8957
Mike Stump1eb44332009-09-09 15:08:12 +00008958bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008959 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008960 MultiExprArg Exprs,
8961 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008962 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008963 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008964 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008965 move(Exprs), HadMultipleCandidates, false,
8966 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008967 if (TempResult.isInvalid())
8968 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008969
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008970 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008971 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00008972 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008973 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008974 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008975
Anders Carlssonfe2de492009-08-25 05:18:00 +00008976 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008977}
8978
John McCall68c6c9a2010-02-02 09:10:11 +00008979void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008980 if (VD->isInvalidDecl()) return;
8981
John McCall68c6c9a2010-02-02 09:10:11 +00008982 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008983 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00008984 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008985 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008986
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008987 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00008988 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008989 CheckDestructorAccess(VD->getLocation(), Destructor,
8990 PDiag(diag::err_access_dtor_var)
8991 << VD->getDeclName()
8992 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00008993 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008994
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008995 if (!VD->hasGlobalStorage()) return;
8996
8997 // Emit warning for non-trivial dtor in global scope (a real global,
8998 // class-static, function-static).
8999 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9000
9001 // TODO: this should be re-enabled for static locals by !CXAAtExit
9002 if (!VD->isStaticLocal())
9003 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009004}
9005
Douglas Gregor39da0b82009-09-09 23:08:42 +00009006/// \brief Given a constructor and the set of arguments provided for the
9007/// constructor, convert the arguments and add any required default arguments
9008/// to form a proper call to this constructor.
9009///
9010/// \returns true if an error occurred, false otherwise.
9011bool
9012Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9013 MultiExprArg ArgsPtr,
9014 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009015 ASTOwningVector<Expr*> &ConvertedArgs,
9016 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009017 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9018 unsigned NumArgs = ArgsPtr.size();
9019 Expr **Args = (Expr **)ArgsPtr.get();
9020
9021 const FunctionProtoType *Proto
9022 = Constructor->getType()->getAs<FunctionProtoType>();
9023 assert(Proto && "Constructor without a prototype?");
9024 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009025
9026 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009027 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009028 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009029 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009030 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009031
9032 VariadicCallType CallType =
9033 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009034 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009035 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9036 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009037 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009038 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009039
9040 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9041
9042 // FIXME: Missing call to CheckFunctionCall or equivalent
9043
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009044 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009045}
9046
Anders Carlsson20d45d22009-12-12 00:32:00 +00009047static inline bool
9048CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9049 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009050 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009051 if (isa<NamespaceDecl>(DC)) {
9052 return SemaRef.Diag(FnDecl->getLocation(),
9053 diag::err_operator_new_delete_declared_in_namespace)
9054 << FnDecl->getDeclName();
9055 }
9056
9057 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009058 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009059 return SemaRef.Diag(FnDecl->getLocation(),
9060 diag::err_operator_new_delete_declared_static)
9061 << FnDecl->getDeclName();
9062 }
9063
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009064 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009065}
9066
Anders Carlsson156c78e2009-12-13 17:53:43 +00009067static inline bool
9068CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9069 CanQualType ExpectedResultType,
9070 CanQualType ExpectedFirstParamType,
9071 unsigned DependentParamTypeDiag,
9072 unsigned InvalidParamTypeDiag) {
9073 QualType ResultType =
9074 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9075
9076 // Check that the result type is not dependent.
9077 if (ResultType->isDependentType())
9078 return SemaRef.Diag(FnDecl->getLocation(),
9079 diag::err_operator_new_delete_dependent_result_type)
9080 << FnDecl->getDeclName() << ExpectedResultType;
9081
9082 // Check that the result type is what we expect.
9083 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9084 return SemaRef.Diag(FnDecl->getLocation(),
9085 diag::err_operator_new_delete_invalid_result_type)
9086 << FnDecl->getDeclName() << ExpectedResultType;
9087
9088 // A function template must have at least 2 parameters.
9089 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9090 return SemaRef.Diag(FnDecl->getLocation(),
9091 diag::err_operator_new_delete_template_too_few_parameters)
9092 << FnDecl->getDeclName();
9093
9094 // The function decl must have at least 1 parameter.
9095 if (FnDecl->getNumParams() == 0)
9096 return SemaRef.Diag(FnDecl->getLocation(),
9097 diag::err_operator_new_delete_too_few_parameters)
9098 << FnDecl->getDeclName();
9099
9100 // Check the the first parameter type is not dependent.
9101 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9102 if (FirstParamType->isDependentType())
9103 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9104 << FnDecl->getDeclName() << ExpectedFirstParamType;
9105
9106 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009107 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009108 ExpectedFirstParamType)
9109 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9110 << FnDecl->getDeclName() << ExpectedFirstParamType;
9111
9112 return false;
9113}
9114
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009115static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009116CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009117 // C++ [basic.stc.dynamic.allocation]p1:
9118 // A program is ill-formed if an allocation function is declared in a
9119 // namespace scope other than global scope or declared static in global
9120 // scope.
9121 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9122 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009123
9124 CanQualType SizeTy =
9125 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9126
9127 // C++ [basic.stc.dynamic.allocation]p1:
9128 // The return type shall be void*. The first parameter shall have type
9129 // std::size_t.
9130 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9131 SizeTy,
9132 diag::err_operator_new_dependent_param_type,
9133 diag::err_operator_new_param_type))
9134 return true;
9135
9136 // C++ [basic.stc.dynamic.allocation]p1:
9137 // The first parameter shall not have an associated default argument.
9138 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009139 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009140 diag::err_operator_new_default_arg)
9141 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9142
9143 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009144}
9145
9146static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009147CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9148 // C++ [basic.stc.dynamic.deallocation]p1:
9149 // A program is ill-formed if deallocation functions are declared in a
9150 // namespace scope other than global scope or declared static in global
9151 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009152 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9153 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009154
9155 // C++ [basic.stc.dynamic.deallocation]p2:
9156 // Each deallocation function shall return void and its first parameter
9157 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009158 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9159 SemaRef.Context.VoidPtrTy,
9160 diag::err_operator_delete_dependent_param_type,
9161 diag::err_operator_delete_param_type))
9162 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009163
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009164 return false;
9165}
9166
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009167/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9168/// of this overloaded operator is well-formed. If so, returns false;
9169/// otherwise, emits appropriate diagnostics and returns true.
9170bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009171 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009172 "Expected an overloaded operator declaration");
9173
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009174 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9175
Mike Stump1eb44332009-09-09 15:08:12 +00009176 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009177 // The allocation and deallocation functions, operator new,
9178 // operator new[], operator delete and operator delete[], are
9179 // described completely in 3.7.3. The attributes and restrictions
9180 // found in the rest of this subclause do not apply to them unless
9181 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009182 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009183 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009184
Anders Carlssona3ccda52009-12-12 00:26:23 +00009185 if (Op == OO_New || Op == OO_Array_New)
9186 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009187
9188 // C++ [over.oper]p6:
9189 // An operator function shall either be a non-static member
9190 // function or be a non-member function and have at least one
9191 // parameter whose type is a class, a reference to a class, an
9192 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009193 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9194 if (MethodDecl->isStatic())
9195 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009196 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009197 } else {
9198 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009199 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9200 ParamEnd = FnDecl->param_end();
9201 Param != ParamEnd; ++Param) {
9202 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009203 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9204 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009205 ClassOrEnumParam = true;
9206 break;
9207 }
9208 }
9209
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009210 if (!ClassOrEnumParam)
9211 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009212 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009213 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009214 }
9215
9216 // C++ [over.oper]p8:
9217 // An operator function cannot have default arguments (8.3.6),
9218 // except where explicitly stated below.
9219 //
Mike Stump1eb44332009-09-09 15:08:12 +00009220 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009221 // (C++ [over.call]p1).
9222 if (Op != OO_Call) {
9223 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9224 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009225 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009226 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009227 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009228 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009229 }
9230 }
9231
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009232 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9233 { false, false, false }
9234#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9235 , { Unary, Binary, MemberOnly }
9236#include "clang/Basic/OperatorKinds.def"
9237 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009238
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009239 bool CanBeUnaryOperator = OperatorUses[Op][0];
9240 bool CanBeBinaryOperator = OperatorUses[Op][1];
9241 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009242
9243 // C++ [over.oper]p8:
9244 // [...] Operator functions cannot have more or fewer parameters
9245 // than the number required for the corresponding operator, as
9246 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009247 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009248 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009249 if (Op != OO_Call &&
9250 ((NumParams == 1 && !CanBeUnaryOperator) ||
9251 (NumParams == 2 && !CanBeBinaryOperator) ||
9252 (NumParams < 1) || (NumParams > 2))) {
9253 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009254 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009255 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009256 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009257 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009258 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009259 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009260 assert(CanBeBinaryOperator &&
9261 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009262 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009263 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009264
Chris Lattner416e46f2008-11-21 07:57:12 +00009265 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009266 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009267 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009268
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009269 // Overloaded operators other than operator() cannot be variadic.
9270 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009271 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009272 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009273 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009274 }
9275
9276 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009277 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9278 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009279 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009280 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009281 }
9282
9283 // C++ [over.inc]p1:
9284 // The user-defined function called operator++ implements the
9285 // prefix and postfix ++ operator. If this function is a member
9286 // function with no parameters, or a non-member function with one
9287 // parameter of class or enumeration type, it defines the prefix
9288 // increment operator ++ for objects of that type. If the function
9289 // is a member function with one parameter (which shall be of type
9290 // int) or a non-member function with two parameters (the second
9291 // of which shall be of type int), it defines the postfix
9292 // increment operator ++ for objects of that type.
9293 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9294 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9295 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009296 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009297 ParamIsInt = BT->getKind() == BuiltinType::Int;
9298
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009299 if (!ParamIsInt)
9300 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009301 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009302 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009303 }
9304
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009305 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009306}
Chris Lattner5a003a42008-12-17 07:09:26 +00009307
Sean Hunta6c058d2010-01-13 09:01:02 +00009308/// CheckLiteralOperatorDeclaration - Check whether the declaration
9309/// of this literal operator function is well-formed. If so, returns
9310/// false; otherwise, emits appropriate diagnostics and returns true.
9311bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009312 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009313 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9314 << FnDecl->getDeclName();
9315 return true;
9316 }
9317
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009318 if (FnDecl->isExternC()) {
9319 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9320 return true;
9321 }
9322
Sean Hunta6c058d2010-01-13 09:01:02 +00009323 bool Valid = false;
9324
Richard Smith36f5cfe2012-03-09 08:00:36 +00009325 // This might be the definition of a literal operator template.
9326 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9327 // This might be a specialization of a literal operator template.
9328 if (!TpDecl)
9329 TpDecl = FnDecl->getPrimaryTemplate();
9330
Sean Hunt216c2782010-04-07 23:11:06 +00009331 // template <char...> type operator "" name() is the only valid template
9332 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009333 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009334 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009335 // Must have only one template parameter
9336 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9337 if (Params->size() == 1) {
9338 NonTypeTemplateParmDecl *PmDecl =
9339 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009340
Sean Hunt216c2782010-04-07 23:11:06 +00009341 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009342 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9343 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9344 Valid = true;
9345 }
9346 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009347 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009348 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009349 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9350
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009351 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009352
Sean Hunt30019c02010-04-07 22:57:35 +00009353 // unsigned long long int, long double, and any character type are allowed
9354 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009355 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9356 Context.hasSameType(T, Context.LongDoubleTy) ||
9357 Context.hasSameType(T, Context.CharTy) ||
9358 Context.hasSameType(T, Context.WCharTy) ||
9359 Context.hasSameType(T, Context.Char16Ty) ||
9360 Context.hasSameType(T, Context.Char32Ty)) {
9361 if (++Param == FnDecl->param_end())
9362 Valid = true;
9363 goto FinishedParams;
9364 }
9365
Sean Hunt30019c02010-04-07 22:57:35 +00009366 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009367 const PointerType *PT = T->getAs<PointerType>();
9368 if (!PT)
9369 goto FinishedParams;
9370 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009371 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009372 goto FinishedParams;
9373 T = T.getUnqualifiedType();
9374
9375 // Move on to the second parameter;
9376 ++Param;
9377
9378 // If there is no second parameter, the first must be a const char *
9379 if (Param == FnDecl->param_end()) {
9380 if (Context.hasSameType(T, Context.CharTy))
9381 Valid = true;
9382 goto FinishedParams;
9383 }
9384
9385 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9386 // are allowed as the first parameter to a two-parameter function
9387 if (!(Context.hasSameType(T, Context.CharTy) ||
9388 Context.hasSameType(T, Context.WCharTy) ||
9389 Context.hasSameType(T, Context.Char16Ty) ||
9390 Context.hasSameType(T, Context.Char32Ty)))
9391 goto FinishedParams;
9392
9393 // The second and final parameter must be an std::size_t
9394 T = (*Param)->getType().getUnqualifiedType();
9395 if (Context.hasSameType(T, Context.getSizeType()) &&
9396 ++Param == FnDecl->param_end())
9397 Valid = true;
9398 }
9399
9400 // FIXME: This diagnostic is absolutely terrible.
9401FinishedParams:
9402 if (!Valid) {
9403 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9404 << FnDecl->getDeclName();
9405 return true;
9406 }
9407
Richard Smitha9e88b22012-03-09 08:16:22 +00009408 // A parameter-declaration-clause containing a default argument is not
9409 // equivalent to any of the permitted forms.
9410 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9411 ParamEnd = FnDecl->param_end();
9412 Param != ParamEnd; ++Param) {
9413 if ((*Param)->hasDefaultArg()) {
9414 Diag((*Param)->getDefaultArgRange().getBegin(),
9415 diag::err_literal_operator_default_argument)
9416 << (*Param)->getDefaultArgRange();
9417 break;
9418 }
9419 }
9420
Richard Smith2fb4ae32012-03-08 02:39:21 +00009421 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009422 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9423 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009424 // C++11 [usrlit.suffix]p1:
9425 // Literal suffix identifiers that do not start with an underscore
9426 // are reserved for future standardization.
9427 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009428 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009429
Sean Hunta6c058d2010-01-13 09:01:02 +00009430 return false;
9431}
9432
Douglas Gregor074149e2009-01-05 19:45:36 +00009433/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9434/// linkage specification, including the language and (if present)
9435/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9436/// the location of the language string literal, which is provided
9437/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9438/// the '{' brace. Otherwise, this linkage specification does not
9439/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009440Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9441 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009442 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009443 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009444 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009445 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009446 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009447 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009448 Language = LinkageSpecDecl::lang_cxx;
9449 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009450 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009451 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009452 }
Mike Stump1eb44332009-09-09 15:08:12 +00009453
Chris Lattnercc98eac2008-12-17 07:13:27 +00009454 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009455
Douglas Gregor074149e2009-01-05 19:45:36 +00009456 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009457 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009458 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009459 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009460 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009461}
9462
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009463/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009464/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9465/// valid, it's the position of the closing '}' brace in a linkage
9466/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009467Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009468 Decl *LinkageSpec,
9469 SourceLocation RBraceLoc) {
9470 if (LinkageSpec) {
9471 if (RBraceLoc.isValid()) {
9472 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9473 LSDecl->setRBraceLoc(RBraceLoc);
9474 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009475 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009476 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009477 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009478}
9479
Douglas Gregord308e622009-05-18 20:51:54 +00009480/// \brief Perform semantic analysis for the variable declaration that
9481/// occurs within a C++ catch clause, returning the newly-created
9482/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009483VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009484 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009485 SourceLocation StartLoc,
9486 SourceLocation Loc,
9487 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009488 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009489 QualType ExDeclType = TInfo->getType();
9490
Sebastian Redl4b07b292008-12-22 19:15:10 +00009491 // Arrays and functions decay.
9492 if (ExDeclType->isArrayType())
9493 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9494 else if (ExDeclType->isFunctionType())
9495 ExDeclType = Context.getPointerType(ExDeclType);
9496
9497 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9498 // The exception-declaration shall not denote a pointer or reference to an
9499 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009500 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009501 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009502 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009503 Invalid = true;
9504 }
Douglas Gregord308e622009-05-18 20:51:54 +00009505
Sebastian Redl4b07b292008-12-22 19:15:10 +00009506 QualType BaseType = ExDeclType;
9507 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009508 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009509 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009510 BaseType = Ptr->getPointeeType();
9511 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009512 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009513 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009514 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009515 BaseType = Ref->getPointeeType();
9516 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009517 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009518 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009519 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009520 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009521 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009522
Mike Stump1eb44332009-09-09 15:08:12 +00009523 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009524 RequireNonAbstractType(Loc, ExDeclType,
9525 diag::err_abstract_type_in_decl,
9526 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009527 Invalid = true;
9528
John McCall5a180392010-07-24 00:37:23 +00009529 // Only the non-fragile NeXT runtime currently supports C++ catches
9530 // of ObjC types, and no runtime supports catching ObjC types by value.
9531 if (!Invalid && getLangOptions().ObjC1) {
9532 QualType T = ExDeclType;
9533 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9534 T = RT->getPointeeType();
9535
9536 if (T->isObjCObjectType()) {
9537 Diag(Loc, diag::err_objc_object_catch);
9538 Invalid = true;
9539 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009540 if (!getLangOptions().ObjCNonFragileABI)
9541 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009542 }
9543 }
9544
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009545 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9546 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009547 ExDecl->setExceptionVariable(true);
9548
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009549 // In ARC, infer 'retaining' for variables of retainable type.
9550 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9551 Invalid = true;
9552
Douglas Gregorc41b8782011-07-06 18:14:43 +00009553 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009554 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009555 // C++ [except.handle]p16:
9556 // The object declared in an exception-declaration or, if the
9557 // exception-declaration does not specify a name, a temporary (12.2) is
9558 // copy-initialized (8.5) from the exception object. [...]
9559 // The object is destroyed when the handler exits, after the destruction
9560 // of any automatic objects initialized within the handler.
9561 //
9562 // We just pretend to initialize the object with itself, then make sure
9563 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009564 QualType initType = ExDeclType;
9565
9566 InitializedEntity entity =
9567 InitializedEntity::InitializeVariable(ExDecl);
9568 InitializationKind initKind =
9569 InitializationKind::CreateCopy(Loc, SourceLocation());
9570
9571 Expr *opaqueValue =
9572 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9573 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9574 ExprResult result = sequence.Perform(*this, entity, initKind,
9575 MultiExprArg(&opaqueValue, 1));
9576 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009577 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009578 else {
9579 // If the constructor used was non-trivial, set this as the
9580 // "initializer".
9581 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9582 if (!construct->getConstructor()->isTrivial()) {
9583 Expr *init = MaybeCreateExprWithCleanups(construct);
9584 ExDecl->setInit(init);
9585 }
9586
9587 // And make sure it's destructable.
9588 FinalizeVarWithDestructor(ExDecl, recordType);
9589 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009590 }
9591 }
9592
Douglas Gregord308e622009-05-18 20:51:54 +00009593 if (Invalid)
9594 ExDecl->setInvalidDecl();
9595
9596 return ExDecl;
9597}
9598
9599/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9600/// handler.
John McCalld226f652010-08-21 09:40:31 +00009601Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009602 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009603 bool Invalid = D.isInvalidType();
9604
9605 // Check for unexpanded parameter packs.
9606 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9607 UPPC_ExceptionType)) {
9608 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9609 D.getIdentifierLoc());
9610 Invalid = true;
9611 }
9612
Sebastian Redl4b07b292008-12-22 19:15:10 +00009613 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009614 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009615 LookupOrdinaryName,
9616 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009617 // The scope should be freshly made just for us. There is just no way
9618 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009619 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009620 if (PrevDecl->isTemplateParameter()) {
9621 // Maybe we will complain about the shadowed template parameter.
9622 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009623 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009624 }
9625 }
9626
Chris Lattnereaaebc72009-04-25 08:06:05 +00009627 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009628 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9629 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009630 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009631 }
9632
Douglas Gregor83cb9422010-09-09 17:09:21 +00009633 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009634 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009635 D.getIdentifierLoc(),
9636 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009637 if (Invalid)
9638 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009639
Sebastian Redl4b07b292008-12-22 19:15:10 +00009640 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009641 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009642 PushOnScopeChains(ExDecl, S);
9643 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009644 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009645
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009646 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009647 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009648}
Anders Carlssonfb311762009-03-14 00:25:26 +00009649
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009650Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009651 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009652 Expr *AssertMessageExpr_,
9653 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009654 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009655
Anders Carlssonc3082412009-03-14 00:33:21 +00009656 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009657 // In a static_assert-declaration, the constant-expression shall be a
9658 // constant expression that can be contextually converted to bool.
9659 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9660 if (Converted.isInvalid())
9661 return 0;
9662
Richard Smithdaaefc52011-12-14 23:32:26 +00009663 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009664 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9665 PDiag(diag::err_static_assert_expression_is_not_constant),
9666 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009667 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009668
Richard Smith0cc323c2012-03-05 23:20:05 +00009669 if (!Cond) {
9670 llvm::SmallString<256> MsgBuffer;
9671 llvm::raw_svector_ostream Msg(MsgBuffer);
9672 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009673 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009674 << Msg.str() << AssertExpr->getSourceRange();
9675 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009676 }
Mike Stump1eb44332009-09-09 15:08:12 +00009677
Douglas Gregor399ad972010-12-15 23:55:21 +00009678 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9679 return 0;
9680
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009681 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9682 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009683
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009684 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009685 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009686}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009687
Douglas Gregor1d869352010-04-07 16:53:43 +00009688/// \brief Perform semantic analysis of the given friend type declaration.
9689///
9690/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009691FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9692 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009693 TypeSourceInfo *TSInfo) {
9694 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9695
9696 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009697 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009698
Richard Smith6b130222011-10-18 21:39:00 +00009699 // C++03 [class.friend]p2:
9700 // An elaborated-type-specifier shall be used in a friend declaration
9701 // for a class.*
9702 //
9703 // * The class-key of the elaborated-type-specifier is required.
9704 if (!ActiveTemplateInstantiations.empty()) {
9705 // Do not complain about the form of friend template types during
9706 // template instantiation; we will already have complained when the
9707 // template was declared.
9708 } else if (!T->isElaboratedTypeSpecifier()) {
9709 // If we evaluated the type to a record type, suggest putting
9710 // a tag in front.
9711 if (const RecordType *RT = T->getAs<RecordType>()) {
9712 RecordDecl *RD = RT->getDecl();
9713
9714 std::string InsertionText = std::string(" ") + RD->getKindName();
9715
9716 Diag(TypeRange.getBegin(),
9717 getLangOptions().CPlusPlus0x ?
9718 diag::warn_cxx98_compat_unelaborated_friend_type :
9719 diag::ext_unelaborated_friend_type)
9720 << (unsigned) RD->getTagKind()
9721 << T
9722 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9723 InsertionText);
9724 } else {
9725 Diag(FriendLoc,
9726 getLangOptions().CPlusPlus0x ?
9727 diag::warn_cxx98_compat_nonclass_type_friend :
9728 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009729 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009730 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009731 }
Richard Smith6b130222011-10-18 21:39:00 +00009732 } else if (T->getAs<EnumType>()) {
9733 Diag(FriendLoc,
9734 getLangOptions().CPlusPlus0x ?
9735 diag::warn_cxx98_compat_enum_friend :
9736 diag::ext_enum_friend)
9737 << T
9738 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009739 }
9740
Douglas Gregor06245bf2010-04-07 17:57:12 +00009741 // C++0x [class.friend]p3:
9742 // If the type specifier in a friend declaration designates a (possibly
9743 // cv-qualified) class type, that class is declared as a friend; otherwise,
9744 // the friend declaration is ignored.
9745
9746 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9747 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009748
Abramo Bagnara0216df82011-10-29 20:52:52 +00009749 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009750}
9751
John McCall9a34edb2010-10-19 01:40:49 +00009752/// Handle a friend tag declaration where the scope specifier was
9753/// templated.
9754Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9755 unsigned TagSpec, SourceLocation TagLoc,
9756 CXXScopeSpec &SS,
9757 IdentifierInfo *Name, SourceLocation NameLoc,
9758 AttributeList *Attr,
9759 MultiTemplateParamsArg TempParamLists) {
9760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9761
9762 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009763 bool Invalid = false;
9764
9765 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009766 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009767 TempParamLists.get(),
9768 TempParamLists.size(),
9769 /*friend*/ true,
9770 isExplicitSpecialization,
9771 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009772 if (TemplateParams->size() > 0) {
9773 // This is a declaration of a class template.
9774 if (Invalid)
9775 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009776
Eric Christopher4110e132011-07-21 05:34:24 +00009777 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9778 SS, Name, NameLoc, Attr,
9779 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009780 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009781 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009782 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009783 } else {
9784 // The "template<>" header is extraneous.
9785 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9786 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9787 isExplicitSpecialization = true;
9788 }
9789 }
9790
9791 if (Invalid) return 0;
9792
John McCall9a34edb2010-10-19 01:40:49 +00009793 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009794 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009795 if (TempParamLists.get()[I]->size()) {
9796 isAllExplicitSpecializations = false;
9797 break;
9798 }
9799 }
9800
9801 // FIXME: don't ignore attributes.
9802
9803 // If it's explicit specializations all the way down, just forget
9804 // about the template header and build an appropriate non-templated
9805 // friend. TODO: for source fidelity, remember the headers.
9806 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009807 if (SS.isEmpty()) {
9808 bool Owned = false;
9809 bool IsDependent = false;
9810 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9811 Attr, AS_public,
9812 /*ModulePrivateLoc=*/SourceLocation(),
9813 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009814 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009815 /*ScopedEnumUsesClassTag=*/false,
9816 /*UnderlyingType=*/TypeResult());
9817 }
9818
Douglas Gregor2494dd02011-03-01 01:34:45 +00009819 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009820 ElaboratedTypeKeyword Keyword
9821 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009822 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009823 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009824 if (T.isNull())
9825 return 0;
9826
9827 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9828 if (isa<DependentNameType>(T)) {
9829 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009830 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009831 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009832 TL.setNameLoc(NameLoc);
9833 } else {
9834 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009835 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009836 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009837 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9838 }
9839
9840 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9841 TSI, FriendLoc);
9842 Friend->setAccess(AS_public);
9843 CurContext->addDecl(Friend);
9844 return Friend;
9845 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009846
9847 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9848
9849
John McCall9a34edb2010-10-19 01:40:49 +00009850
9851 // Handle the case of a templated-scope friend class. e.g.
9852 // template <class T> class A<T>::B;
9853 // FIXME: we don't support these right now.
9854 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9855 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9856 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9857 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009858 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009859 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009860 TL.setNameLoc(NameLoc);
9861
9862 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9863 TSI, FriendLoc);
9864 Friend->setAccess(AS_public);
9865 Friend->setUnsupportedFriend(true);
9866 CurContext->addDecl(Friend);
9867 return Friend;
9868}
9869
9870
John McCalldd4a3b02009-09-16 22:47:08 +00009871/// Handle a friend type declaration. This works in tandem with
9872/// ActOnTag.
9873///
9874/// Notes on friend class templates:
9875///
9876/// We generally treat friend class declarations as if they were
9877/// declaring a class. So, for example, the elaborated type specifier
9878/// in a friend declaration is required to obey the restrictions of a
9879/// class-head (i.e. no typedefs in the scope chain), template
9880/// parameters are required to match up with simple template-ids, &c.
9881/// However, unlike when declaring a template specialization, it's
9882/// okay to refer to a template specialization without an empty
9883/// template parameter declaration, e.g.
9884/// friend class A<T>::B<unsigned>;
9885/// We permit this as a special case; if there are any template
9886/// parameters present at all, require proper matching, i.e.
9887/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009888Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009889 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009890 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009891
9892 assert(DS.isFriendSpecified());
9893 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9894
John McCalldd4a3b02009-09-16 22:47:08 +00009895 // Try to convert the decl specifier to a type. This works for
9896 // friend templates because ActOnTag never produces a ClassTemplateDecl
9897 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009898 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009899 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9900 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009901 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009902 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009903
Douglas Gregor6ccab972010-12-16 01:14:37 +00009904 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9905 return 0;
9906
John McCalldd4a3b02009-09-16 22:47:08 +00009907 // This is definitely an error in C++98. It's probably meant to
9908 // be forbidden in C++0x, too, but the specification is just
9909 // poorly written.
9910 //
9911 // The problem is with declarations like the following:
9912 // template <T> friend A<T>::foo;
9913 // where deciding whether a class C is a friend or not now hinges
9914 // on whether there exists an instantiation of A that causes
9915 // 'foo' to equal C. There are restrictions on class-heads
9916 // (which we declare (by fiat) elaborated friend declarations to
9917 // be) that makes this tractable.
9918 //
9919 // FIXME: handle "template <> friend class A<T>;", which
9920 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009921 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009922 Diag(Loc, diag::err_tagless_friend_type_template)
9923 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009924 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009925 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009926
John McCall02cace72009-08-28 07:59:38 +00009927 // C++98 [class.friend]p1: A friend of a class is a function
9928 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009929 // This is fixed in DR77, which just barely didn't make the C++03
9930 // deadline. It's also a very silly restriction that seriously
9931 // affects inner classes and which nobody else seems to implement;
9932 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009933 //
9934 // But note that we could warn about it: it's always useless to
9935 // friend one of your own members (it's not, however, worthless to
9936 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009937
John McCalldd4a3b02009-09-16 22:47:08 +00009938 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009939 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009940 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009941 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009942 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009943 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009944 DS.getFriendSpecLoc());
9945 else
Abramo Bagnara0216df82011-10-29 20:52:52 +00009946 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +00009947
9948 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009949 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009950
John McCalldd4a3b02009-09-16 22:47:08 +00009951 D->setAccess(AS_public);
9952 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009953
John McCalld226f652010-08-21 09:40:31 +00009954 return D;
John McCall02cace72009-08-28 07:59:38 +00009955}
9956
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009957Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +00009958 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009959 const DeclSpec &DS = D.getDeclSpec();
9960
9961 assert(DS.isFriendSpecified());
9962 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9963
9964 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009965 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +00009966
9967 // C++ [class.friend]p1
9968 // A friend of a class is a function or class....
9969 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009970 // It *doesn't* see through dependent types, which is correct
9971 // according to [temp.arg.type]p3:
9972 // If a declaration acquires a function type through a
9973 // type dependent on a template-parameter and this causes
9974 // a declaration that does not use the syntactic form of a
9975 // function declarator to have a function type, the program
9976 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009977 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +00009978 Diag(Loc, diag::err_unexpected_friend);
9979
9980 // It might be worthwhile to try to recover by creating an
9981 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009982 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009983 }
9984
9985 // C++ [namespace.memdef]p3
9986 // - If a friend declaration in a non-local class first declares a
9987 // class or function, the friend class or function is a member
9988 // of the innermost enclosing namespace.
9989 // - The name of the friend is not found by simple name lookup
9990 // until a matching declaration is provided in that namespace
9991 // scope (either before or after the class declaration granting
9992 // friendship).
9993 // - If a friend function is called, its name may be found by the
9994 // name lookup that considers functions from namespaces and
9995 // classes associated with the types of the function arguments.
9996 // - When looking for a prior declaration of a class or a function
9997 // declared as a friend, scopes outside the innermost enclosing
9998 // namespace scope are not considered.
9999
John McCall337ec3d2010-10-12 23:13:28 +000010000 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010001 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10002 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010003 assert(Name);
10004
Douglas Gregor6ccab972010-12-16 01:14:37 +000010005 // Check for unexpanded parameter packs.
10006 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10007 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10008 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10009 return 0;
10010
John McCall67d1a672009-08-06 02:15:43 +000010011 // The context we found the declaration in, or in which we should
10012 // create the declaration.
10013 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010014 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010015 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010016 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010017
John McCall337ec3d2010-10-12 23:13:28 +000010018 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010019
John McCall337ec3d2010-10-12 23:13:28 +000010020 // There are four cases here.
10021 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010022 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010023 // there as appropriate.
10024 // Recover from invalid scope qualifiers as if they just weren't there.
10025 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010026 // C++0x [namespace.memdef]p3:
10027 // If the name in a friend declaration is neither qualified nor
10028 // a template-id and the declaration is a function or an
10029 // elaborated-type-specifier, the lookup to determine whether
10030 // the entity has been previously declared shall not consider
10031 // any scopes outside the innermost enclosing namespace.
10032 // C++0x [class.friend]p11:
10033 // If a friend declaration appears in a local class and the name
10034 // specified is an unqualified name, a prior declaration is
10035 // looked up without considering scopes that are outside the
10036 // innermost enclosing non-class scope. For a friend function
10037 // declaration, if there is no prior declaration, the program is
10038 // ill-formed.
10039 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010040 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010041
John McCall29ae6e52010-10-13 05:45:15 +000010042 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010043 DC = CurContext;
10044 while (true) {
10045 // Skip class contexts. If someone can cite chapter and verse
10046 // for this behavior, that would be nice --- it's what GCC and
10047 // EDG do, and it seems like a reasonable intent, but the spec
10048 // really only says that checks for unqualified existing
10049 // declarations should stop at the nearest enclosing namespace,
10050 // not that they should only consider the nearest enclosing
10051 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010052 while (DC->isRecord())
10053 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010054
John McCall68263142009-11-18 22:49:29 +000010055 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010056
10057 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010058 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010059 break;
John McCall29ae6e52010-10-13 05:45:15 +000010060
John McCall8a407372010-10-14 22:22:28 +000010061 if (isTemplateId) {
10062 if (isa<TranslationUnitDecl>(DC)) break;
10063 } else {
10064 if (DC->isFileContext()) break;
10065 }
John McCall67d1a672009-08-06 02:15:43 +000010066 DC = DC->getParent();
10067 }
10068
10069 // C++ [class.friend]p1: A friend of a class is a function or
10070 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010071 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010072 // Most C++ 98 compilers do seem to give an error here, so
10073 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010074 if (!Previous.empty() && DC->Equals(CurContext))
10075 Diag(DS.getFriendSpecLoc(),
10076 getLangOptions().CPlusPlus0x ?
10077 diag::warn_cxx98_compat_friend_is_member :
10078 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010079
John McCall380aaa42010-10-13 06:22:15 +000010080 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010081
Douglas Gregor883af832011-10-10 01:11:59 +000010082 // C++ [class.friend]p6:
10083 // A function can be defined in a friend declaration of a class if and
10084 // only if the class is a non-local class (9.8), the function name is
10085 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010086 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010087 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10088 }
10089
John McCall337ec3d2010-10-12 23:13:28 +000010090 // - There's a non-dependent scope specifier, in which case we
10091 // compute it and do a previous lookup there for a function
10092 // or function template.
10093 } else if (!SS.getScopeRep()->isDependent()) {
10094 DC = computeDeclContext(SS);
10095 if (!DC) return 0;
10096
10097 if (RequireCompleteDeclContext(SS, DC)) return 0;
10098
10099 LookupQualifiedName(Previous, DC);
10100
10101 // Ignore things found implicitly in the wrong scope.
10102 // TODO: better diagnostics for this case. Suggesting the right
10103 // qualified scope would be nice...
10104 LookupResult::Filter F = Previous.makeFilter();
10105 while (F.hasNext()) {
10106 NamedDecl *D = F.next();
10107 if (!DC->InEnclosingNamespaceSetOf(
10108 D->getDeclContext()->getRedeclContext()))
10109 F.erase();
10110 }
10111 F.done();
10112
10113 if (Previous.empty()) {
10114 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010115 Diag(Loc, diag::err_qualified_friend_not_found)
10116 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010117 return 0;
10118 }
10119
10120 // C++ [class.friend]p1: A friend of a class is a function or
10121 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010122 if (DC->Equals(CurContext))
10123 Diag(DS.getFriendSpecLoc(),
10124 getLangOptions().CPlusPlus0x ?
10125 diag::warn_cxx98_compat_friend_is_member :
10126 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010127
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010128 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010129 // C++ [class.friend]p6:
10130 // A function can be defined in a friend declaration of a class if and
10131 // only if the class is a non-local class (9.8), the function name is
10132 // unqualified, and the function has namespace scope.
10133 SemaDiagnosticBuilder DB
10134 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10135
10136 DB << SS.getScopeRep();
10137 if (DC->isFileContext())
10138 DB << FixItHint::CreateRemoval(SS.getRange());
10139 SS.clear();
10140 }
John McCall337ec3d2010-10-12 23:13:28 +000010141
10142 // - There's a scope specifier that does not match any template
10143 // parameter lists, in which case we use some arbitrary context,
10144 // create a method or method template, and wait for instantiation.
10145 // - There's a scope specifier that does match some template
10146 // parameter lists, which we don't handle right now.
10147 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010148 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010149 // C++ [class.friend]p6:
10150 // A function can be defined in a friend declaration of a class if and
10151 // only if the class is a non-local class (9.8), the function name is
10152 // unqualified, and the function has namespace scope.
10153 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10154 << SS.getScopeRep();
10155 }
10156
John McCall337ec3d2010-10-12 23:13:28 +000010157 DC = CurContext;
10158 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010159 }
Douglas Gregor883af832011-10-10 01:11:59 +000010160
John McCall29ae6e52010-10-13 05:45:15 +000010161 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010162 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010163 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10164 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10165 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010166 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010167 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10168 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010169 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010170 }
John McCall67d1a672009-08-06 02:15:43 +000010171 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010172
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010173 // FIXME: This is an egregious hack to cope with cases where the scope stack
10174 // does not contain the declaration context, i.e., in an out-of-line
10175 // definition of a class.
10176 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10177 if (!DCScope) {
10178 FakeDCScope.setEntity(DC);
10179 DCScope = &FakeDCScope;
10180 }
10181
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010182 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010183 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10184 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010185 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010186
Douglas Gregor182ddf02009-09-28 00:08:27 +000010187 assert(ND->getDeclContext() == DC);
10188 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010189
John McCallab88d972009-08-31 22:39:49 +000010190 // Add the function declaration to the appropriate lookup tables,
10191 // adjusting the redeclarations list as necessary. We don't
10192 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010193 //
John McCallab88d972009-08-31 22:39:49 +000010194 // Also update the scope-based lookup if the target context's
10195 // lookup context is in lexical scope.
10196 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010197 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010198 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010199 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010200 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010201 }
John McCall02cace72009-08-28 07:59:38 +000010202
10203 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010204 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010205 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010206 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010207 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010208
John McCall337ec3d2010-10-12 23:13:28 +000010209 if (ND->isInvalidDecl())
10210 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010211 else {
10212 FunctionDecl *FD;
10213 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10214 FD = FTD->getTemplatedDecl();
10215 else
10216 FD = cast<FunctionDecl>(ND);
10217
10218 // Mark templated-scope function declarations as unsupported.
10219 if (FD->getNumTemplateParameterLists())
10220 FrD->setUnsupportedFriend(true);
10221 }
John McCall337ec3d2010-10-12 23:13:28 +000010222
John McCalld226f652010-08-21 09:40:31 +000010223 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010224}
10225
John McCalld226f652010-08-21 09:40:31 +000010226void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10227 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010228
Sebastian Redl50de12f2009-03-24 22:27:57 +000010229 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10230 if (!Fn) {
10231 Diag(DelLoc, diag::err_deleted_non_function);
10232 return;
10233 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010234 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010235 Diag(DelLoc, diag::err_deleted_decl_not_first);
10236 Diag(Prev->getLocation(), diag::note_previous_declaration);
10237 // If the declaration wasn't the first, we delete the function anyway for
10238 // recovery.
10239 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010240 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010241
10242 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10243 if (!MD)
10244 return;
10245
10246 // A deleted special member function is trivial if the corresponding
10247 // implicitly-declared function would have been.
10248 switch (getSpecialMember(MD)) {
10249 case CXXInvalid:
10250 break;
10251 case CXXDefaultConstructor:
10252 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10253 break;
10254 case CXXCopyConstructor:
10255 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10256 break;
10257 case CXXMoveConstructor:
10258 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10259 break;
10260 case CXXCopyAssignment:
10261 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10262 break;
10263 case CXXMoveAssignment:
10264 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10265 break;
10266 case CXXDestructor:
10267 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10268 break;
10269 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010270}
Sebastian Redl13e88542009-04-27 21:33:24 +000010271
Sean Hunte4246a62011-05-12 06:15:49 +000010272void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10273 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10274
10275 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010276 if (MD->getParent()->isDependentType()) {
10277 MD->setDefaulted();
10278 MD->setExplicitlyDefaulted();
10279 return;
10280 }
10281
Sean Hunte4246a62011-05-12 06:15:49 +000010282 CXXSpecialMember Member = getSpecialMember(MD);
10283 if (Member == CXXInvalid) {
10284 Diag(DefaultLoc, diag::err_default_special_members);
10285 return;
10286 }
10287
10288 MD->setDefaulted();
10289 MD->setExplicitlyDefaulted();
10290
Sean Huntcd10dec2011-05-23 23:14:04 +000010291 // If this definition appears within the record, do the checking when
10292 // the record is complete.
10293 const FunctionDecl *Primary = MD;
10294 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10295 // Find the uninstantiated declaration that actually had the '= default'
10296 // on it.
10297 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10298
10299 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010300 return;
10301
10302 switch (Member) {
10303 case CXXDefaultConstructor: {
10304 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10305 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010306 if (!CD->isInvalidDecl())
10307 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10308 break;
10309 }
10310
10311 case CXXCopyConstructor: {
10312 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10313 CheckExplicitlyDefaultedCopyConstructor(CD);
10314 if (!CD->isInvalidDecl())
10315 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010316 break;
10317 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010318
Sean Hunt2b188082011-05-14 05:23:28 +000010319 case CXXCopyAssignment: {
10320 CheckExplicitlyDefaultedCopyAssignment(MD);
10321 if (!MD->isInvalidDecl())
10322 DefineImplicitCopyAssignment(DefaultLoc, MD);
10323 break;
10324 }
10325
Sean Huntcb45a0f2011-05-12 22:46:25 +000010326 case CXXDestructor: {
10327 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10328 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010329 if (!DD->isInvalidDecl())
10330 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010331 break;
10332 }
10333
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010334 case CXXMoveConstructor: {
10335 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10336 CheckExplicitlyDefaultedMoveConstructor(CD);
10337 if (!CD->isInvalidDecl())
10338 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010339 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010340 }
Sean Hunt82713172011-05-25 23:16:36 +000010341
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010342 case CXXMoveAssignment: {
10343 CheckExplicitlyDefaultedMoveAssignment(MD);
10344 if (!MD->isInvalidDecl())
10345 DefineImplicitMoveAssignment(DefaultLoc, MD);
10346 break;
10347 }
10348
10349 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010350 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010351 }
10352 } else {
10353 Diag(DefaultLoc, diag::err_default_special_members);
10354 }
10355}
10356
Sebastian Redl13e88542009-04-27 21:33:24 +000010357static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010358 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010359 Stmt *SubStmt = *CI;
10360 if (!SubStmt)
10361 continue;
10362 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010363 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010364 diag::err_return_in_constructor_handler);
10365 if (!isa<Expr>(SubStmt))
10366 SearchForReturnInStmt(Self, SubStmt);
10367 }
10368}
10369
10370void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10371 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10372 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10373 SearchForReturnInStmt(*this, Handler);
10374 }
10375}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010376
Mike Stump1eb44332009-09-09 15:08:12 +000010377bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010378 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010379 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10380 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010381
Chandler Carruth73857792010-02-15 11:53:20 +000010382 if (Context.hasSameType(NewTy, OldTy) ||
10383 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010384 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010385
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010386 // Check if the return types are covariant
10387 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010388
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010389 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010390 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10391 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010392 NewClassTy = NewPT->getPointeeType();
10393 OldClassTy = OldPT->getPointeeType();
10394 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010395 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10396 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10397 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10398 NewClassTy = NewRT->getPointeeType();
10399 OldClassTy = OldRT->getPointeeType();
10400 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010401 }
10402 }
Mike Stump1eb44332009-09-09 15:08:12 +000010403
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010404 // The return types aren't either both pointers or references to a class type.
10405 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010406 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010407 diag::err_different_return_type_for_overriding_virtual_function)
10408 << New->getDeclName() << NewTy << OldTy;
10409 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010410
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010411 return true;
10412 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010413
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010414 // C++ [class.virtual]p6:
10415 // If the return type of D::f differs from the return type of B::f, the
10416 // class type in the return type of D::f shall be complete at the point of
10417 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010418 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10419 if (!RT->isBeingDefined() &&
10420 RequireCompleteType(New->getLocation(), NewClassTy,
10421 PDiag(diag::err_covariant_return_incomplete)
10422 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010423 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010424 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010425
Douglas Gregora4923eb2009-11-16 21:35:15 +000010426 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010427 // Check if the new class derives from the old class.
10428 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10429 Diag(New->getLocation(),
10430 diag::err_covariant_return_not_derived)
10431 << New->getDeclName() << NewTy << OldTy;
10432 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10433 return true;
10434 }
Mike Stump1eb44332009-09-09 15:08:12 +000010435
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010436 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010437 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010438 diag::err_covariant_return_inaccessible_base,
10439 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10440 // FIXME: Should this point to the return type?
10441 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010442 // FIXME: this note won't trigger for delayed access control
10443 // diagnostics, and it's impossible to get an undelayed error
10444 // here from access control during the original parse because
10445 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010446 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10447 return true;
10448 }
10449 }
Mike Stump1eb44332009-09-09 15:08:12 +000010450
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010451 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010452 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010453 Diag(New->getLocation(),
10454 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010455 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010456 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10457 return true;
10458 };
Mike Stump1eb44332009-09-09 15:08:12 +000010459
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010460
10461 // The new class type must have the same or less qualifiers as the old type.
10462 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10463 Diag(New->getLocation(),
10464 diag::err_covariant_return_type_class_type_more_qualified)
10465 << New->getDeclName() << NewTy << OldTy;
10466 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10467 return true;
10468 };
Mike Stump1eb44332009-09-09 15:08:12 +000010469
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010470 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010471}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010472
Douglas Gregor4ba31362009-12-01 17:24:26 +000010473/// \brief Mark the given method pure.
10474///
10475/// \param Method the method to be marked pure.
10476///
10477/// \param InitRange the source range that covers the "0" initializer.
10478bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010479 SourceLocation EndLoc = InitRange.getEnd();
10480 if (EndLoc.isValid())
10481 Method->setRangeEnd(EndLoc);
10482
Douglas Gregor4ba31362009-12-01 17:24:26 +000010483 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10484 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010485 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010486 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010487
10488 if (!Method->isInvalidDecl())
10489 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10490 << Method->getDeclName() << InitRange;
10491 return true;
10492}
10493
Douglas Gregor552e2992012-02-21 02:22:07 +000010494/// \brief Determine whether the given declaration is a static data member.
10495static bool isStaticDataMember(Decl *D) {
10496 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10497 if (!Var)
10498 return false;
10499
10500 return Var->isStaticDataMember();
10501}
John McCall731ad842009-12-19 09:28:58 +000010502/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10503/// an initializer for the out-of-line declaration 'Dcl'. The scope
10504/// is a fresh scope pushed for just this purpose.
10505///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010506/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10507/// static data member of class X, names should be looked up in the scope of
10508/// class X.
John McCalld226f652010-08-21 09:40:31 +000010509void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010510 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010511 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010512
John McCall731ad842009-12-19 09:28:58 +000010513 // We should only get called for declarations with scope specifiers, like:
10514 // int foo::bar;
10515 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010516 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010517
10518 // If we are parsing the initializer for a static data member, push a
10519 // new expression evaluation context that is associated with this static
10520 // data member.
10521 if (isStaticDataMember(D))
10522 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010523}
10524
10525/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010526/// initializer for the out-of-line declaration 'D'.
10527void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010528 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010529 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010530
Douglas Gregor552e2992012-02-21 02:22:07 +000010531 if (isStaticDataMember(D))
10532 PopExpressionEvaluationContext();
10533
John McCall731ad842009-12-19 09:28:58 +000010534 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010535 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010536}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010537
10538/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10539/// C++ if/switch/while/for statement.
10540/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010541DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010542 // C++ 6.4p2:
10543 // The declarator shall not specify a function or an array.
10544 // The type-specifier-seq shall not contain typedef and shall not declare a
10545 // new class or enumeration.
10546 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10547 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010548
10549 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010550 if (!Dcl)
10551 return true;
10552
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010553 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10554 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010555 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010556 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010557 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010558
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010559 return Dcl;
10560}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010561
Douglas Gregordfe65432011-07-28 19:11:31 +000010562void Sema::LoadExternalVTableUses() {
10563 if (!ExternalSource)
10564 return;
10565
10566 SmallVector<ExternalVTableUse, 4> VTables;
10567 ExternalSource->ReadUsedVTables(VTables);
10568 SmallVector<VTableUse, 4> NewUses;
10569 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10570 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10571 = VTablesUsed.find(VTables[I].Record);
10572 // Even if a definition wasn't required before, it may be required now.
10573 if (Pos != VTablesUsed.end()) {
10574 if (!Pos->second && VTables[I].DefinitionRequired)
10575 Pos->second = true;
10576 continue;
10577 }
10578
10579 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10580 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10581 }
10582
10583 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10584}
10585
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010586void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10587 bool DefinitionRequired) {
10588 // Ignore any vtable uses in unevaluated operands or for classes that do
10589 // not have a vtable.
10590 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10591 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010592 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010593 return;
10594
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010595 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010596 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010597 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10598 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10599 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10600 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010601 // If we already had an entry, check to see if we are promoting this vtable
10602 // to required a definition. If so, we need to reappend to the VTableUses
10603 // list, since we may have already processed the first entry.
10604 if (DefinitionRequired && !Pos.first->second) {
10605 Pos.first->second = true;
10606 } else {
10607 // Otherwise, we can early exit.
10608 return;
10609 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010610 }
10611
10612 // Local classes need to have their virtual members marked
10613 // immediately. For all other classes, we mark their virtual members
10614 // at the end of the translation unit.
10615 if (Class->isLocalClass())
10616 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010617 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010618 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010619}
10620
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010621bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010622 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010623 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010624 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010625
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010626 // Note: The VTableUses vector could grow as a result of marking
10627 // the members of a class as "used", so we check the size each
10628 // time through the loop and prefer indices (with are stable) to
10629 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010630 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010631 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010632 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010633 if (!Class)
10634 continue;
10635
10636 SourceLocation Loc = VTableUses[I].second;
10637
10638 // If this class has a key function, but that key function is
10639 // defined in another translation unit, we don't need to emit the
10640 // vtable even though we're using it.
10641 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010642 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010643 switch (KeyFunction->getTemplateSpecializationKind()) {
10644 case TSK_Undeclared:
10645 case TSK_ExplicitSpecialization:
10646 case TSK_ExplicitInstantiationDeclaration:
10647 // The key function is in another translation unit.
10648 continue;
10649
10650 case TSK_ExplicitInstantiationDefinition:
10651 case TSK_ImplicitInstantiation:
10652 // We will be instantiating the key function.
10653 break;
10654 }
10655 } else if (!KeyFunction) {
10656 // If we have a class with no key function that is the subject
10657 // of an explicit instantiation declaration, suppress the
10658 // vtable; it will live with the explicit instantiation
10659 // definition.
10660 bool IsExplicitInstantiationDeclaration
10661 = Class->getTemplateSpecializationKind()
10662 == TSK_ExplicitInstantiationDeclaration;
10663 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10664 REnd = Class->redecls_end();
10665 R != REnd; ++R) {
10666 TemplateSpecializationKind TSK
10667 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10668 if (TSK == TSK_ExplicitInstantiationDeclaration)
10669 IsExplicitInstantiationDeclaration = true;
10670 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10671 IsExplicitInstantiationDeclaration = false;
10672 break;
10673 }
10674 }
10675
10676 if (IsExplicitInstantiationDeclaration)
10677 continue;
10678 }
10679
10680 // Mark all of the virtual members of this class as referenced, so
10681 // that we can build a vtable. Then, tell the AST consumer that a
10682 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010683 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010684 MarkVirtualMembersReferenced(Loc, Class);
10685 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10686 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10687
10688 // Optionally warn if we're emitting a weak vtable.
10689 if (Class->getLinkage() == ExternalLinkage &&
10690 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010691 const FunctionDecl *KeyFunctionDef = 0;
10692 if (!KeyFunction ||
10693 (KeyFunction->hasBody(KeyFunctionDef) &&
10694 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010695 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10696 TSK_ExplicitInstantiationDefinition
10697 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10698 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010699 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010700 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010701 VTableUses.clear();
10702
Douglas Gregor78844032011-04-22 22:25:37 +000010703 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010704}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010705
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010706void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10707 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010708 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10709 e = RD->method_end(); i != e; ++i) {
10710 CXXMethodDecl *MD = *i;
10711
10712 // C++ [basic.def.odr]p2:
10713 // [...] A virtual member function is used if it is not pure. [...]
10714 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010715 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010716 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010717
10718 // Only classes that have virtual bases need a VTT.
10719 if (RD->getNumVBases() == 0)
10720 return;
10721
10722 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10723 e = RD->bases_end(); i != e; ++i) {
10724 const CXXRecordDecl *Base =
10725 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010726 if (Base->getNumVBases() == 0)
10727 continue;
10728 MarkVirtualMembersReferenced(Loc, Base);
10729 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010730}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010731
10732/// SetIvarInitializers - This routine builds initialization ASTs for the
10733/// Objective-C implementation whose ivars need be initialized.
10734void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10735 if (!getLangOptions().CPlusPlus)
10736 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010737 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010738 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010739 CollectIvarsToConstructOrDestruct(OID, ivars);
10740 if (ivars.empty())
10741 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010742 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010743 for (unsigned i = 0; i < ivars.size(); i++) {
10744 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010745 if (Field->isInvalidDecl())
10746 continue;
10747
Sean Huntcbb67482011-01-08 20:30:50 +000010748 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010749 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10750 InitializationKind InitKind =
10751 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10752
10753 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010754 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010755 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010756 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010757 // Note, MemberInit could actually come back empty if no initialization
10758 // is required (e.g., because it would call a trivial default constructor)
10759 if (!MemberInit.get() || MemberInit.isInvalid())
10760 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010761
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010762 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010763 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10764 SourceLocation(),
10765 MemberInit.takeAs<Expr>(),
10766 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010767 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010768
10769 // Be sure that the destructor is accessible and is marked as referenced.
10770 if (const RecordType *RecordTy
10771 = Context.getBaseElementType(Field->getType())
10772 ->getAs<RecordType>()) {
10773 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010774 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010775 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010776 CheckDestructorAccess(Field->getLocation(), Destructor,
10777 PDiag(diag::err_access_dtor_ivar)
10778 << Context.getBaseElementType(Field->getType()));
10779 }
10780 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010781 }
10782 ObjCImplementation->setIvarInitializers(Context,
10783 AllToInit.data(), AllToInit.size());
10784 }
10785}
Sean Huntfe57eef2011-05-04 05:57:24 +000010786
Sean Huntebcbe1d2011-05-04 23:29:54 +000010787static
10788void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10789 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10790 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10791 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10792 Sema &S) {
10793 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10794 CE = Current.end();
10795 if (Ctor->isInvalidDecl())
10796 return;
10797
10798 const FunctionDecl *FNTarget = 0;
10799 CXXConstructorDecl *Target;
10800
10801 // We ignore the result here since if we don't have a body, Target will be
10802 // null below.
10803 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10804 Target
10805= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10806
10807 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10808 // Avoid dereferencing a null pointer here.
10809 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10810
10811 if (!Current.insert(Canonical))
10812 return;
10813
10814 // We know that beyond here, we aren't chaining into a cycle.
10815 if (!Target || !Target->isDelegatingConstructor() ||
10816 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10817 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10818 Valid.insert(*CI);
10819 Current.clear();
10820 // We've hit a cycle.
10821 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10822 Current.count(TCanonical)) {
10823 // If we haven't diagnosed this cycle yet, do so now.
10824 if (!Invalid.count(TCanonical)) {
10825 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010826 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010827 << Ctor;
10828
10829 // Don't add a note for a function delegating directo to itself.
10830 if (TCanonical != Canonical)
10831 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10832
10833 CXXConstructorDecl *C = Target;
10834 while (C->getCanonicalDecl() != Canonical) {
10835 (void)C->getTargetConstructor()->hasBody(FNTarget);
10836 assert(FNTarget && "Ctor cycle through bodiless function");
10837
10838 C
10839 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10840 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10841 }
10842 }
10843
10844 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10845 Invalid.insert(*CI);
10846 Current.clear();
10847 } else {
10848 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10849 }
10850}
10851
10852
Sean Huntfe57eef2011-05-04 05:57:24 +000010853void Sema::CheckDelegatingCtorCycles() {
10854 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10855
Sean Huntebcbe1d2011-05-04 23:29:54 +000010856 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10857 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010858
Douglas Gregor0129b562011-07-27 21:57:17 +000010859 for (DelegatingCtorDeclsType::iterator
10860 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010861 E = DelegatingCtorDecls.end();
10862 I != E; ++I) {
10863 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010864 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010865
10866 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10867 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010868}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010869
10870/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10871Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10872 // Implicitly declared functions (e.g. copy constructors) are
10873 // __host__ __device__
10874 if (D->isImplicit())
10875 return CFT_HostDevice;
10876
10877 if (D->hasAttr<CUDAGlobalAttr>())
10878 return CFT_Global;
10879
10880 if (D->hasAttr<CUDADeviceAttr>()) {
10881 if (D->hasAttr<CUDAHostAttr>())
10882 return CFT_HostDevice;
10883 else
10884 return CFT_Device;
10885 }
10886
10887 return CFT_Host;
10888}
10889
10890bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10891 CUDAFunctionTarget CalleeTarget) {
10892 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10893 // Callable from the device only."
10894 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10895 return true;
10896
10897 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10898 // Callable from the host only."
10899 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10900 // Callable from the host only."
10901 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10902 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10903 return true;
10904
10905 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10906 return true;
10907
10908 return false;
10909}