blob: 2b7d1bfcd8d81c34fc0a92be0b7da7e054f86717 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000028#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000029#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000030#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000031#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000034#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000035#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000036#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000038#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000039#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000040
41using namespace clang;
42
Chris Lattner8123a952008-04-10 02:22:51 +000043//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
Chris Lattner9e979552008-04-12 23:52:44 +000047namespace {
48 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
49 /// the default argument of a parameter to determine whether it
50 /// contains any ill-formed subexpressions. For example, this will
51 /// diagnose the use of local variables or parameters within the
52 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000053 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000054 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000055 Expr *DefaultArg;
56 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 public:
Mike Stump1eb44332009-09-09 15:08:12 +000059 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000060 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 bool VisitExpr(Expr *Node);
63 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000064 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000065 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000066 };
Chris Lattner8123a952008-04-10 02:22:51 +000067
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitExpr - Visit all of the children of this expression.
69 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
70 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000071 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000072 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000073 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000074 }
75
Chris Lattner9e979552008-04-12 23:52:44 +000076 /// VisitDeclRefExpr - Visit a reference to a declaration, to
77 /// determine whether this declaration can be used in the default
78 /// argument expression.
79 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000081 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
82 // C++ [dcl.fct.default]p9
83 // Default arguments are evaluated each time the function is
84 // called. The order of evaluation of function arguments is
85 // unspecified. Consequently, parameters of a function shall not
86 // be used in default argument expressions, even if they are not
87 // evaluated. Parameters of a function declared before a default
88 // argument expression are in scope and can hide namespace and
89 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000090 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000093 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000094 // C++ [dcl.fct.default]p7
95 // Local variables shall not be used in default argument
96 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000097 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000098 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000100 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102
Douglas Gregor3996f232008-11-04 13:41:56 +0000103 return false;
104 }
Chris Lattner9e979552008-04-12 23:52:44 +0000105
Douglas Gregor796da182008-11-04 14:32:21 +0000106 /// VisitCXXThisExpr - Visit a C++ "this" expression.
107 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
108 // C++ [dcl.fct.default]p8:
109 // The keyword this shall not be used in a default argument of a
110 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000111 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000112 diag::err_param_default_argument_references_this)
113 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000114 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000115
116 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
117 // C++11 [expr.lambda.prim]p13:
118 // A lambda-expression appearing in a default argument shall not
119 // implicitly or explicitly capture any entity.
120 if (Lambda->capture_begin() == Lambda->capture_end())
121 return false;
122
123 return S->Diag(Lambda->getLocStart(),
124 diag::err_lambda_capture_default_arg);
125 }
Chris Lattner8123a952008-04-10 02:22:51 +0000126}
127
Richard Smithe6975e92012-04-17 00:58:00 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
129 CXXMethodDecl *Method) {
Richard Smith7a614d82011-06-11 17:19:42 +0000130 // If we have an MSAny or unknown spec already, don't bother.
131 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000132 return;
133
134 const FunctionProtoType *Proto
135 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000136 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
137 if (!Proto)
138 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000139
140 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
141
142 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000143 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000144 ClearExceptions();
145 ComputedEST = EST;
146 return;
147 }
148
Richard Smith7a614d82011-06-11 17:19:42 +0000149 // FIXME: If the call to this decl is using any of its default arguments, we
150 // need to search them for potentially-throwing calls.
151
Sean Hunt001cad92011-05-10 00:49:42 +0000152 // If this function has a basic noexcept, it doesn't affect the outcome.
153 if (EST == EST_BasicNoexcept)
154 return;
155
156 // If we have a throw-all spec at this point, ignore the function.
157 if (ComputedEST == EST_None)
158 return;
159
160 // If we're still at noexcept(true) and there's a nothrow() callee,
161 // change to that specification.
162 if (EST == EST_DynamicNone) {
163 if (ComputedEST == EST_BasicNoexcept)
164 ComputedEST = EST_DynamicNone;
165 return;
166 }
167
168 // Check out noexcept specs.
169 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000170 FunctionProtoType::NoexceptResult NR =
171 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000172 assert(NR != FunctionProtoType::NR_NoNoexcept &&
173 "Must have noexcept result for EST_ComputedNoexcept.");
174 assert(NR != FunctionProtoType::NR_Dependent &&
175 "Should not generate implicit declarations for dependent cases, "
176 "and don't know how to handle them anyway.");
177
178 // noexcept(false) -> no spec on the new function
179 if (NR == FunctionProtoType::NR_Throw) {
180 ClearExceptions();
181 ComputedEST = EST_None;
182 }
183 // noexcept(true) won't change anything either.
184 return;
185 }
186
187 assert(EST == EST_Dynamic && "EST case not considered earlier.");
188 assert(ComputedEST != EST_None &&
189 "Shouldn't collect exceptions when throw-all is guaranteed.");
190 ComputedEST = EST_Dynamic;
191 // Record the exceptions in this function's exception specification.
192 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
193 EEnd = Proto->exception_end();
194 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000195 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000196 Exceptions.push_back(*E);
197}
198
Richard Smith7a614d82011-06-11 17:19:42 +0000199void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
200 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
201 return;
202
203 // FIXME:
204 //
205 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000206 // [An] implicit exception-specification specifies the type-id T if and
207 // only if T is allowed by the exception-specification of a function directly
208 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000209 // function it directly invokes allows all exceptions, and f shall allow no
210 // exceptions if every function it directly invokes allows no exceptions.
211 //
212 // Note in particular that if an implicit exception-specification is generated
213 // for a function containing a throw-expression, that specification can still
214 // be noexcept(true).
215 //
216 // Note also that 'directly invoked' is not defined in the standard, and there
217 // is no indication that we should only consider potentially-evaluated calls.
218 //
219 // Ultimately we should implement the intent of the standard: the exception
220 // specification should be the set of exceptions which can be thrown by the
221 // implicit definition. For now, we assume that any non-nothrow expression can
222 // throw any exception.
223
Richard Smithe6975e92012-04-17 00:58:00 +0000224 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000225 ComputedEST = EST_None;
226}
227
Anders Carlssoned961f92009-08-25 02:29:20 +0000228bool
John McCall9ae2f072010-08-23 23:25:46 +0000229Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000230 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000231 if (RequireCompleteType(Param->getLocation(), Param->getType(),
232 diag::err_typecheck_decl_incomplete_type)) {
233 Param->setInvalidDecl();
234 return true;
235 }
236
Anders Carlssoned961f92009-08-25 02:29:20 +0000237 // C++ [dcl.fct.default]p5
238 // A default argument expression is implicitly converted (clause
239 // 4) to the parameter type. The default argument expression has
240 // the same semantic constraints as the initializer expression in
241 // a declaration of a variable of the parameter type, using the
242 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000243 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
244 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000245 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
246 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000247 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000248 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000249 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000250 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000251 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000252 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000253
John McCallb4eb64d2010-10-08 02:01:28 +0000254 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000255 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000273}
274
Chris Lattner8123a952008-04-10 02:22:51 +0000275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000278void
John McCalld226f652010-08-21 09:40:31 +0000279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 UnparsedDefaultArgLocs.erase(Param);
286
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000291 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 return;
293 }
294
Douglas Gregor6f526752010-12-16 08:48:57 +0000295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
Anders Carlsson66e30672009-08-25 01:02:06 +0000301 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000304 Param->setInvalidDecl();
305 return;
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCall9ae2f072010-08-23 23:25:46 +0000308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309}
310
Douglas Gregor61366e92008-12-24 00:01:03 +0000311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000318 if (!param)
319 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
John McCalld226f652010-08-21 09:40:31 +0000321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000322 if (Param)
323 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlsson5e300d12009-06-12 16:51:40 +0000325 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000326}
327
Douglas Gregor72b505b2008-12-16 21:30:33 +0000328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000331 if (!param)
332 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCalld226f652010-08-21 09:40:31 +0000334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000339}
340
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000370 }
371 }
372 }
373 }
374}
375
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376// MergeCXXFunctionDecl - Merge two declarations of the same C++
377// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000378// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 bool Invalid = false;
383
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
James Molloy9cda03f2012-03-13 08:55:35 +0000406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000416
Francois Pichet8d051e02011-04-10 03:03:52 +0000417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000423 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000434 Invalid = false;
435 }
436 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000437
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000447 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000461 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000464 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000465 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
John McCall3d6c1782010-05-04 01:53:42 +0000470 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000471 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521 CXXSpecialMember NewSM = getSpecialMember(Ctor),
522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523 if (NewSM != OldSM) {
524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525 << NewParam->getDefaultArgRange() << NewSM;
526 Diag(Old->getLocation(), diag::note_previous_declaration_special)
527 << OldSM;
528 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000529 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000530 }
531 }
532
Richard Smithff234882012-02-20 23:28:05 +0000533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000534 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000535 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000536 if (New->isConstexpr() != Old->isConstexpr()) {
537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538 << New << New->isConstexpr();
539 Diag(Old->getLocation(), diag::note_previous_declaration);
540 Invalid = true;
541 }
542
Douglas Gregore13ad832010-02-12 07:32:17 +0000543 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000544 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545
Douglas Gregorcda9c672009-02-16 17:45:42 +0000546 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000547}
548
Sebastian Redl60618fa2011-03-12 11:50:43 +0000549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000556 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557 return;
558
559 assert(Context.hasSameType(New->getType(), Old->getType()) &&
560 "Should only be called if types are otherwise the same.");
561
562 QualType NewType = New->getType();
563 QualType OldType = Old->getType();
564
565 // We're only interested in pointers and references to functions, as well
566 // as pointers to member functions.
567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568 NewType = R->getPointeeType();
569 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571 NewType = P->getPointeeType();
572 OldType = OldType->getAs<PointerType>()->getPointeeType();
573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574 NewType = M->getPointeeType();
575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576 }
577
578 if (!NewType->isFunctionProtoType())
579 return;
580
581 // There's lots of special cases for functions. For function pointers, system
582 // libraries are hopefully not as broken so that we don't need these
583 // workarounds.
584 if (CheckEquivalentExceptionSpec(
585 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587 New->setInvalidDecl();
588 }
589}
590
Chris Lattner3d1cee32008-04-08 05:04:30 +0000591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595 unsigned NumParams = FD->getNumParams();
596 unsigned p;
597
Douglas Gregorc6889e72012-02-14 22:28:59 +0000598 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599 isa<CXXMethodDecl>(FD) &&
600 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 // Find first parameter with a default argument
603 for (p = 0; p < NumParams; ++p) {
604 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 if (Param->hasDefaultArg()) {
606 // C++11 [expr.prim.lambda]p5:
607 // [...] Default arguments (8.3.6) shall not be specified in the
608 // parameter-declaration-clause of a lambda-declarator.
609 //
610 // FIXME: Core issue 974 strikes this sentence, we only provide an
611 // extension warning.
612 if (IsLambda)
613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000616 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617 }
618
619 // C++ [dcl.fct.default]p4:
620 // In a given function declaration, all parameters
621 // subsequent to a parameter with a default argument shall
622 // have default arguments supplied in this or previous
623 // declarations. A default argument shall not be redefined
624 // by a later declaration (not even to the same value).
625 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000626 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000628 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000629 if (Param->isInvalidDecl())
630 /* We already complained about this parameter. */;
631 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000632 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000633 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000634 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 else
Mike Stump1eb44332009-09-09 15:08:12 +0000636 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000637 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner3d1cee32008-04-08 05:04:30 +0000639 LastMissingDefaultArg = p;
640 }
641 }
642
643 if (LastMissingDefaultArg > 0) {
644 // Some default arguments were missing. Clear out all of the
645 // default arguments up to (and including) the last missing
646 // default argument, so that we leave the function parameters
647 // in a semantically valid state.
648 for (p = 0; p <= LastMissingDefaultArg; ++p) {
649 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000650 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 Param->setDefaultArg(0);
652 }
653 }
654 }
655}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000656
Richard Smith9f569cc2011-10-01 02:31:28 +0000657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000662 unsigned ArgIndex = 0;
663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667 SourceLocation ParamLoc = PD->getLocation();
668 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000669 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000670 diag::err_constexpr_non_literal_param,
671 ArgIndex+1, PD->getSourceRange(),
672 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000673 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 }
675 return true;
676}
677
678// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000679// the requirements of a constexpr function definition or a constexpr
680// constructor definition. If so, return true. If not, produce appropriate
681// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000682//
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
684bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000685 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
686 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000687 // C++11 [dcl.constexpr]p4:
688 // The definition of a constexpr constructor shall satisfy the following
689 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000690 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000691 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
694 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
695 << RD->getNumVBases();
696 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
697 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000698 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000699 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000700 return false;
701 }
Richard Smith35340502012-01-13 04:54:00 +0000702 }
703
704 if (!isa<CXXConstructorDecl>(NewFD)) {
705 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000706 // The definition of a constexpr function shall satisfy the following
707 // constraints:
708 // - it shall not be virtual;
709 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
710 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000711 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000712
Richard Smith86c3ae42012-02-13 03:54:03 +0000713 // If it's not obvious why this function is virtual, find an overridden
714 // function which uses the 'virtual' keyword.
715 const CXXMethodDecl *WrittenVirtual = Method;
716 while (!WrittenVirtual->isVirtualAsWritten())
717 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
718 if (WrittenVirtual != Method)
719 Diag(WrittenVirtual->getLocation(),
720 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return false;
722 }
723
724 // - its return type shall be a literal type;
725 QualType RT = NewFD->getResultType();
726 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000727 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000728 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
731
Richard Smith35340502012-01-13 04:54:00 +0000732 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000734 return false;
735
Richard Smith9f569cc2011-10-01 02:31:28 +0000736 return true;
737}
738
739/// Check the given declaration statement is legal within a constexpr function
740/// body. C++0x [dcl.constexpr]p3,p4.
741///
742/// \return true if the body is OK, false if we have diagnosed a problem.
743static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
744 DeclStmt *DS) {
745 // C++0x [dcl.constexpr]p3 and p4:
746 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
747 // contain only
748 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
749 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
750 switch ((*DclIt)->getKind()) {
751 case Decl::StaticAssert:
752 case Decl::Using:
753 case Decl::UsingShadow:
754 case Decl::UsingDirective:
755 case Decl::UnresolvedUsingTypename:
756 // - static_assert-declarations
757 // - using-declarations,
758 // - using-directives,
759 continue;
760
761 case Decl::Typedef:
762 case Decl::TypeAlias: {
763 // - typedef declarations and alias-declarations that do not define
764 // classes or enumerations,
765 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
766 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
767 // Don't allow variably-modified types in constexpr functions.
768 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
769 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
770 << TL.getSourceRange() << TL.getType()
771 << isa<CXXConstructorDecl>(Dcl);
772 return false;
773 }
774 continue;
775 }
776
777 case Decl::Enum:
778 case Decl::CXXRecord:
779 // As an extension, we allow the declaration (but not the definition) of
780 // classes and enumerations in all declarations, not just in typedef and
781 // alias declarations.
782 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
783 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
784 << isa<CXXConstructorDecl>(Dcl);
785 return false;
786 }
787 continue;
788
789 case Decl::Var:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793
794 default:
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 }
800
801 return true;
802}
803
804/// Check that the given field is initialized within a constexpr constructor.
805///
806/// \param Dcl The constexpr constructor being checked.
807/// \param Field The field being checked. This may be a member of an anonymous
808/// struct or union nested within the class being checked.
809/// \param Inits All declarations, including anonymous struct/union members and
810/// indirect members, for which any initialization was provided.
811/// \param Diagnosed Set to true if an error is produced.
812static void CheckConstexprCtorInitializer(Sema &SemaRef,
813 const FunctionDecl *Dcl,
814 FieldDecl *Field,
815 llvm::SmallSet<Decl*, 16> &Inits,
816 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000817 if (Field->isUnnamedBitfield())
818 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000819
820 if (Field->isAnonymousStructOrUnion() &&
821 Field->getType()->getAsCXXRecordDecl()->isEmpty())
822 return;
823
Richard Smith9f569cc2011-10-01 02:31:28 +0000824 if (!Inits.count(Field)) {
825 if (!Diagnosed) {
826 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
827 Diagnosed = true;
828 }
829 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
830 } else if (Field->isAnonymousStructOrUnion()) {
831 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
832 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
833 I != E; ++I)
834 // If an anonymous union contains an anonymous struct of which any member
835 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000836 if (!RD->isUnion() || Inits.count(*I))
837 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000838 }
839}
840
841/// Check the body for the given constexpr function declaration only contains
842/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
843///
844/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000845bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000847 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 // The definition of a constexpr function shall satisfy the following
849 // constraints: [...]
850 // - its function-body shall be = delete, = default, or a
851 // compound-statement
852 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000853 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 // In the definition of a constexpr constructor, [...]
855 // - its function-body shall not be a function-try-block;
856 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860
861 // - its function-body shall be [...] a compound-statement that contains only
862 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
863
864 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
865 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
866 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
867 switch ((*BodyIt)->getStmtClass()) {
868 case Stmt::NullStmtClass:
869 // - null statements,
870 continue;
871
872 case Stmt::DeclStmtClass:
873 // - static_assert-declarations
874 // - using-declarations,
875 // - using-directives,
876 // - typedef declarations and alias-declarations that do not define
877 // classes or enumerations,
878 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
879 return false;
880 continue;
881
882 case Stmt::ReturnStmtClass:
883 // - and exactly one return statement;
884 if (isa<CXXConstructorDecl>(Dcl))
885 break;
886
887 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 continue;
889
890 default:
891 break;
892 }
893
894 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 if (const CXXConstructorDecl *Constructor
900 = dyn_cast<CXXConstructorDecl>(Dcl)) {
901 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000902 // DR1359:
903 // - every non-variant non-static data member and base class sub-object
904 // shall be initialized;
905 // - if the class is a non-empty union, or for each non-empty anonymous
906 // union member of a non-union class, exactly one non-static data member
907 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000908 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000909 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
911 return false;
912 }
Richard Smith6e433752011-10-10 16:38:04 +0000913 } else if (!Constructor->isDependentContext() &&
914 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000915 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
916
917 // Skip detailed checking if we have enough initializers, and we would
918 // allow at most one initializer per member.
919 bool AnyAnonStructUnionMembers = false;
920 unsigned Fields = 0;
921 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
922 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000923 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000924 AnyAnonStructUnionMembers = true;
925 break;
926 }
927 }
928 if (AnyAnonStructUnionMembers ||
929 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
930 // Check initialization of non-static data members. Base classes are
931 // always initialized so do not need to be checked. Dependent bases
932 // might not have initializers in the member initializer list.
933 llvm::SmallSet<Decl*, 16> Inits;
934 for (CXXConstructorDecl::init_const_iterator
935 I = Constructor->init_begin(), E = Constructor->init_end();
936 I != E; ++I) {
937 if (FieldDecl *FD = (*I)->getMember())
938 Inits.insert(FD);
939 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
940 Inits.insert(ID->chain_begin(), ID->chain_end());
941 }
942
943 bool Diagnosed = false;
944 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
945 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000946 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 if (Diagnosed)
948 return false;
949 }
950 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000951 } else {
952 if (ReturnStmts.empty()) {
953 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
954 return false;
955 }
956 if (ReturnStmts.size() > 1) {
957 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
958 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
959 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
960 return false;
961 }
962 }
963
Richard Smith5ba73e12012-02-04 00:33:54 +0000964 // C++11 [dcl.constexpr]p5:
965 // if no function argument values exist such that the function invocation
966 // substitution would produce a constant expression, the program is
967 // ill-formed; no diagnostic required.
968 // C++11 [dcl.constexpr]p3:
969 // - every constructor call and implicit conversion used in initializing the
970 // return value shall be one of those allowed in a constant expression.
971 // C++11 [dcl.constexpr]p4:
972 // - every constructor involved in initializing non-static data members and
973 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000974 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000975 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000976 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
977 << isa<CXXConstructorDecl>(Dcl);
978 for (size_t I = 0, N = Diags.size(); I != N; ++I)
979 Diag(Diags[I].first, Diags[I].second);
980 return false;
981 }
982
Richard Smith9f569cc2011-10-01 02:31:28 +0000983 return true;
984}
985
Douglas Gregorb48fe382008-10-31 09:07:45 +0000986/// isCurrentClassName - Determine whether the identifier II is the
987/// name of the class type currently being defined. In the case of
988/// nested classes, this will only return true if II is the name of
989/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000990bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
991 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000992 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000993
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000994 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000995 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000996 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000997 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
998 } else
999 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1000
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001001 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001002 return &II == CurDecl->getIdentifier();
1003 else
1004 return false;
1005}
1006
Mike Stump1eb44332009-09-09 15:08:12 +00001007/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001008///
1009/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1010/// and returns NULL otherwise.
1011CXXBaseSpecifier *
1012Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1013 SourceRange SpecifierRange,
1014 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001015 TypeSourceInfo *TInfo,
1016 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001017 QualType BaseType = TInfo->getType();
1018
Douglas Gregor2943aed2009-03-03 04:44:36 +00001019 // C++ [class.union]p1:
1020 // A union shall not have base classes.
1021 if (Class->isUnion()) {
1022 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1023 << SpecifierRange;
1024 return 0;
1025 }
1026
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001027 if (EllipsisLoc.isValid() &&
1028 !TInfo->getType()->containsUnexpandedParameterPack()) {
1029 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1030 << TInfo->getTypeLoc().getSourceRange();
1031 EllipsisLoc = SourceLocation();
1032 }
1033
Douglas Gregor2943aed2009-03-03 04:44:36 +00001034 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001035 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001036 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001037 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001038
1039 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001040
1041 // Base specifiers must be record types.
1042 if (!BaseType->isRecordType()) {
1043 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1044 return 0;
1045 }
1046
1047 // C++ [class.union]p1:
1048 // A union shall not be used as a base class.
1049 if (BaseType->isUnionType()) {
1050 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1051 return 0;
1052 }
1053
1054 // C++ [class.derived]p2:
1055 // The class-name in a base-specifier shall not be an incompletely
1056 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001057 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001058 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001059 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001060 return 0;
John McCall572fc622010-08-17 07:23:57 +00001061 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062
Eli Friedman1d954f62009-08-15 21:55:26 +00001063 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001064 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001065 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001066 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001068 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1069 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001070
Anders Carlsson1d209272011-03-25 14:55:14 +00001071 // C++ [class]p3:
1072 // If a class is marked final and it appears as a base-type-specifier in
1073 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001074 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001075 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1076 << CXXBaseDecl->getDeclName();
1077 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1078 << CXXBaseDecl->getDeclName();
1079 return 0;
1080 }
1081
John McCall572fc622010-08-17 07:23:57 +00001082 if (BaseDecl->isInvalidDecl())
1083 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001084
1085 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001086 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001087 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001088 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001089}
1090
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001091/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1092/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001093/// example:
1094/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001095/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001096BaseResult
John McCalld226f652010-08-21 09:40:31 +00001097Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001098 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001099 ParsedType basetype, SourceLocation BaseLoc,
1100 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001101 if (!classdecl)
1102 return true;
1103
Douglas Gregor40808ce2009-03-09 23:48:35 +00001104 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001105 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001106 if (!Class)
1107 return true;
1108
Nick Lewycky56062202010-07-26 16:56:01 +00001109 TypeSourceInfo *TInfo = 0;
1110 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001111
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001112 if (EllipsisLoc.isInvalid() &&
1113 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001114 UPPC_BaseType))
1115 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001116
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118 Virtual, Access, TInfo,
1119 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001120 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Douglas Gregor2943aed2009-03-03 04:44:36 +00001122 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001123}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001124
Douglas Gregor2943aed2009-03-03 04:44:36 +00001125/// \brief Performs the actual work of attaching the given base class
1126/// specifiers to a C++ class.
1127bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1128 unsigned NumBases) {
1129 if (NumBases == 0)
1130 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001131
1132 // Used to keep track of which base types we have already seen, so
1133 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001134 // that the key is always the unqualified canonical type of the base
1135 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001136 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1137
1138 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001139 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001142 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001144 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001145
1146 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1147 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001148 // C++ [class.mi]p3:
1149 // A class shall not be specified as a direct base class of a
1150 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001151 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001152 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001153 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155
1156 // Delete the duplicate base class specifier; we're going to
1157 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001158 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159
1160 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001161 } else {
1162 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001163 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001164 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001165 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001166 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1167 if (RD->hasAttr<WeakAttr>())
1168 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001169 }
1170 }
1171
1172 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001173 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001174
1175 // Delete the remaining (good) base class specifiers, since their
1176 // data has been copied into the CXXRecordDecl.
1177 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001178 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179
1180 return Invalid;
1181}
1182
1183/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1184/// class, after checking whether there are any duplicate base
1185/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001186void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001187 unsigned NumBases) {
1188 if (!ClassDecl || !Bases || !NumBases)
1189 return;
1190
1191 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001192 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001193 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001194}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001195
John McCall3cb0ebd2010-03-10 03:28:59 +00001196static CXXRecordDecl *GetClassForType(QualType T) {
1197 if (const RecordType *RT = T->getAs<RecordType>())
1198 return cast<CXXRecordDecl>(RT->getDecl());
1199 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1200 return ICT->getDecl();
1201 else
1202 return 0;
1203}
1204
Douglas Gregora8f32e02009-10-06 17:59:45 +00001205/// \brief Determine whether the type \p Derived is a C++ class that is
1206/// derived from the type \p Base.
1207bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001208 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001209 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001210
1211 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1212 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001213 return false;
1214
John McCall3cb0ebd2010-03-10 03:28:59 +00001215 CXXRecordDecl *BaseRD = GetClassForType(Base);
1216 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217 return false;
1218
John McCall86ff3082010-02-04 22:26:26 +00001219 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1220 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221}
1222
1223/// \brief Determine whether the type \p Derived is a C++ class that is
1224/// derived from the type \p Base.
1225bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001226 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001227 return false;
1228
John McCall3cb0ebd2010-03-10 03:28:59 +00001229 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1230 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
John McCall3cb0ebd2010-03-10 03:28:59 +00001233 CXXRecordDecl *BaseRD = GetClassForType(Base);
1234 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001235 return false;
1236
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1238}
1239
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001240void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001241 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242 assert(BasePathArray.empty() && "Base path array must be empty!");
1243 assert(Paths.isRecordingPaths() && "Must record paths!");
1244
1245 const CXXBasePath &Path = Paths.front();
1246
1247 // We first go backward and check if we have a virtual base.
1248 // FIXME: It would be better if CXXBasePath had the base specifier for
1249 // the nearest virtual base.
1250 unsigned Start = 0;
1251 for (unsigned I = Path.size(); I != 0; --I) {
1252 if (Path[I - 1].Base->isVirtual()) {
1253 Start = I - 1;
1254 break;
1255 }
1256 }
1257
1258 // Now add all bases.
1259 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001260 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001261}
1262
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001263/// \brief Determine whether the given base path includes a virtual
1264/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001265bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1266 for (CXXCastPath::const_iterator B = BasePath.begin(),
1267 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001268 B != BEnd; ++B)
1269 if ((*B)->isVirtual())
1270 return true;
1271
1272 return false;
1273}
1274
Douglas Gregora8f32e02009-10-06 17:59:45 +00001275/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1276/// conversion (where Derived and Base are class types) is
1277/// well-formed, meaning that the conversion is unambiguous (and
1278/// that all of the base classes are accessible). Returns true
1279/// and emits a diagnostic if the code is ill-formed, returns false
1280/// otherwise. Loc is the location where this routine should point to
1281/// if there is an error, and Range is the source range to highlight
1282/// if there is an error.
1283bool
1284Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001285 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001286 unsigned AmbigiousBaseConvID,
1287 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001288 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001289 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001290 // First, determine whether the path from Derived to Base is
1291 // ambiguous. This is slightly more expensive than checking whether
1292 // the Derived to Base conversion exists, because here we need to
1293 // explore multiple paths to determine if there is an ambiguity.
1294 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1295 /*DetectVirtual=*/false);
1296 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1297 assert(DerivationOkay &&
1298 "Can only be used with a derived-to-base conversion");
1299 (void)DerivationOkay;
1300
1301 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001302 if (InaccessibleBaseID) {
1303 // Check that the base class can be accessed.
1304 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1305 InaccessibleBaseID)) {
1306 case AR_inaccessible:
1307 return true;
1308 case AR_accessible:
1309 case AR_dependent:
1310 case AR_delayed:
1311 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001312 }
John McCall6b2accb2010-02-10 09:31:12 +00001313 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001314
1315 // Build a base path if necessary.
1316 if (BasePath)
1317 BuildBasePathArray(Paths, *BasePath);
1318 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319 }
1320
1321 // We know that the derived-to-base conversion is ambiguous, and
1322 // we're going to produce a diagnostic. Perform the derived-to-base
1323 // search just one more time to compute all of the possible paths so
1324 // that we can print them out. This is more expensive than any of
1325 // the previous derived-to-base checks we've done, but at this point
1326 // performance isn't as much of an issue.
1327 Paths.clear();
1328 Paths.setRecordingPaths(true);
1329 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1330 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1331 (void)StillOkay;
1332
1333 // Build up a textual representation of the ambiguous paths, e.g.,
1334 // D -> B -> A, that will be used to illustrate the ambiguous
1335 // conversions in the diagnostic. We only print one of the paths
1336 // to each base class subobject.
1337 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1338
1339 Diag(Loc, AmbigiousBaseConvID)
1340 << Derived << Base << PathDisplayStr << Range << Name;
1341 return true;
1342}
1343
1344bool
1345Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001346 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001347 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001348 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001350 IgnoreAccess ? 0
1351 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001353 Loc, Range, DeclarationName(),
1354 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355}
1356
1357
1358/// @brief Builds a string representing ambiguous paths from a
1359/// specific derived class to different subobjects of the same base
1360/// class.
1361///
1362/// This function builds a string that can be used in error messages
1363/// to show the different paths that one can take through the
1364/// inheritance hierarchy to go from the derived class to different
1365/// subobjects of a base class. The result looks something like this:
1366/// @code
1367/// struct D -> struct B -> struct A
1368/// struct D -> struct C -> struct A
1369/// @endcode
1370std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1371 std::string PathDisplayStr;
1372 std::set<unsigned> DisplayedPaths;
1373 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1374 Path != Paths.end(); ++Path) {
1375 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1376 // We haven't displayed a path to this particular base
1377 // class subobject yet.
1378 PathDisplayStr += "\n ";
1379 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1380 for (CXXBasePath::const_iterator Element = Path->begin();
1381 Element != Path->end(); ++Element)
1382 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1383 }
1384 }
1385
1386 return PathDisplayStr;
1387}
1388
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001389//===----------------------------------------------------------------------===//
1390// C++ class member Handling
1391//===----------------------------------------------------------------------===//
1392
Abramo Bagnara6206d532010-06-05 05:09:32 +00001393/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001394bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1395 SourceLocation ASLoc,
1396 SourceLocation ColonLoc,
1397 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001398 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001399 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400 ASLoc, ColonLoc);
1401 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001402 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001403}
1404
Anders Carlsson9e682d92011-01-20 05:57:14 +00001405/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001406void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001407 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001408 if (!MD || !MD->isVirtual())
1409 return;
1410
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001411 if (MD->isDependentContext())
1412 return;
1413
Anders Carlsson9e682d92011-01-20 05:57:14 +00001414 // C++0x [class.virtual]p3:
1415 // If a virtual function is marked with the virt-specifier override and does
1416 // not override a member function of a base class,
1417 // the program is ill-formed.
1418 bool HasOverriddenMethods =
1419 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001420 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001421 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001422 diag::err_function_marked_override_not_overriding)
1423 << MD->getDeclName();
1424 return;
1425 }
1426}
1427
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001428/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1429/// function overrides a virtual member function marked 'final', according to
1430/// C++0x [class.virtual]p3.
1431bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1432 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001433 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001434 return false;
1435
1436 Diag(New->getLocation(), diag::err_final_function_overridden)
1437 << New->getDeclName();
1438 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1439 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001440}
1441
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001442static bool InitializationHasSideEffects(const FieldDecl &FD) {
1443 if (!FD.getType().isNull()) {
1444 if (const CXXRecordDecl *RD = FD.getType()->getAsCXXRecordDecl()) {
1445 return !RD->isCompleteDefinition() ||
1446 !RD->hasTrivialDefaultConstructor() ||
1447 !RD->hasTrivialDestructor();
1448 }
1449 }
1450 return false;
1451}
1452
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001453/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1454/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001455/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1456/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1457/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001458Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001460 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001461 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001462 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001463 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001464 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1465 DeclarationName Name = NameInfo.getName();
1466 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001467
1468 // For anonymous bitfields, the location should point to the type.
1469 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001470 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001471
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001472 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473
John McCall4bde1e12010-06-04 08:34:12 +00001474 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001475 assert(!DS.isFriendSpecified());
1476
Richard Smith1ab0d902011-06-25 02:28:38 +00001477 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001478
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479 // C++ 9.2p6: A member shall not be declared to have automatic storage
1480 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001481 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1482 // data members and cannot be applied to names declared const or static,
1483 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001484 switch (DS.getStorageClassSpec()) {
1485 case DeclSpec::SCS_unspecified:
1486 case DeclSpec::SCS_typedef:
1487 case DeclSpec::SCS_static:
1488 // FALL THROUGH.
1489 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001490 case DeclSpec::SCS_mutable:
1491 if (isFunc) {
1492 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001493 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001494 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001495 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Sebastian Redla11f42f2008-11-17 23:24:37 +00001497 // FIXME: It would be nicer if the keyword was ignored only for this
1498 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001499 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 }
1501 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001502 default:
1503 if (DS.getStorageClassSpecLoc().isValid())
1504 Diag(DS.getStorageClassSpecLoc(),
1505 diag::err_storageclass_invalid_for_member);
1506 else
1507 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1508 D.getMutableDeclSpec().ClearStorageClassSpecs();
1509 }
1510
Sebastian Redl669d5d72008-11-14 23:42:31 +00001511 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1512 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001513 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001514
1515 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001516 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001517 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001518
1519 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001520 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001521 Diag(Loc, diag::err_bad_variable_name)
1522 << Name;
1523 return 0;
1524 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001525
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001526 IdentifierInfo *II = Name.getAsIdentifierInfo();
1527
Douglas Gregorf2503652011-09-21 14:40:46 +00001528 // Member field could not be with "template" keyword.
1529 // So TemplateParameterLists should be empty in this case.
1530 if (TemplateParameterLists.size()) {
1531 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1532 if (TemplateParams->size()) {
1533 // There is no such thing as a member field template.
1534 Diag(D.getIdentifierLoc(), diag::err_template_member)
1535 << II
1536 << SourceRange(TemplateParams->getTemplateLoc(),
1537 TemplateParams->getRAngleLoc());
1538 } else {
1539 // There is an extraneous 'template<>' for this member.
1540 Diag(TemplateParams->getTemplateLoc(),
1541 diag::err_template_member_noparams)
1542 << II
1543 << SourceRange(TemplateParams->getTemplateLoc(),
1544 TemplateParams->getRAngleLoc());
1545 }
1546 return 0;
1547 }
1548
Douglas Gregor922fff22010-10-13 22:19:53 +00001549 if (SS.isSet() && !SS.isInvalid()) {
1550 // The user provided a superfluous scope specifier inside a class
1551 // definition:
1552 //
1553 // class X {
1554 // int X::member;
1555 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001556 if (DeclContext *DC = computeDeclContext(SS, false))
1557 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001558 else
1559 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1560 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001561
Douglas Gregor922fff22010-10-13 22:19:53 +00001562 SS.clear();
1563 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001564
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001565 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001566 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001567 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001568 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001569 assert(!HasDeferredInit);
1570
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001571 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001572 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001573 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001574 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001575
1576 // Non-instance-fields can't have a bitfield.
1577 if (BitWidth) {
1578 if (Member->isInvalidDecl()) {
1579 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001580 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001581 // C++ 9.6p3: A bit-field shall not be a static member.
1582 // "static member 'A' cannot be a bit-field"
1583 Diag(Loc, diag::err_static_not_bitfield)
1584 << Name << BitWidth->getSourceRange();
1585 } else if (isa<TypedefDecl>(Member)) {
1586 // "typedef member 'x' cannot be a bit-field"
1587 Diag(Loc, diag::err_typedef_not_bitfield)
1588 << Name << BitWidth->getSourceRange();
1589 } else {
1590 // A function typedef ("typedef int f(); f a;").
1591 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1592 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001593 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001594 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Chris Lattner8b963ef2009-03-05 23:01:03 +00001597 BitWidth = 0;
1598 Member->setInvalidDecl();
1599 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001600
1601 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregor37b372b2009-08-20 22:52:58 +00001603 // If we have declared a member function template, set the access of the
1604 // templated declaration as well.
1605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1606 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001607 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001608
Anders Carlssonaae5af22011-01-20 04:34:22 +00001609 if (VS.isOverrideSpecified()) {
1610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1611 if (!MD || !MD->isVirtual()) {
1612 Diag(Member->getLocStart(),
1613 diag::override_keyword_only_allowed_on_virtual_member_functions)
1614 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001616 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001617 }
1618 if (VS.isFinalSpecified()) {
1619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1620 if (!MD || !MD->isVirtual()) {
1621 Diag(Member->getLocStart(),
1622 diag::override_keyword_only_allowed_on_virtual_member_functions)
1623 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001624 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001625 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001626 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001627
Douglas Gregorf5251602011-03-08 17:10:18 +00001628 if (VS.getLastLocation().isValid()) {
1629 // Update the end location of a method that has a virt-specifiers.
1630 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1631 MD->setRangeEnd(VS.getLastLocation());
1632 }
1633
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001634 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001635
Douglas Gregor10bd3682008-11-17 22:58:34 +00001636 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001637
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001638 if (isInstField) {
1639 FieldDecl *FD = cast<FieldDecl>(Member);
1640 FieldCollector->Add(FD);
1641
1642 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1643 FD->getLocation())
1644 != DiagnosticsEngine::Ignored) {
1645 // Remember all explicit private FieldDecls that have a name, no side
1646 // effects and are not part of a dependent type declaration.
1647 if (!FD->isImplicit() && FD->getDeclName() &&
1648 FD->getAccess() == AS_private &&
1649 !FD->getParent()->getTypeForDecl()->isDependentType() &&
1650 !InitializationHasSideEffects(*FD))
1651 UnusedPrivateFields.insert(FD);
1652 }
1653 }
1654
John McCalld226f652010-08-21 09:40:31 +00001655 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001656}
1657
Richard Smith7a614d82011-06-11 17:19:42 +00001658/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001659/// in-class initializer for a non-static C++ class member, and after
1660/// instantiating an in-class initializer in a class template. Such actions
1661/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001662void
1663Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1664 Expr *InitExpr) {
1665 FieldDecl *FD = cast<FieldDecl>(D);
1666
1667 if (!InitExpr) {
1668 FD->setInvalidDecl();
1669 FD->removeInClassInitializer();
1670 return;
1671 }
1672
Peter Collingbournefef21892011-10-23 18:59:44 +00001673 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1674 FD->setInvalidDecl();
1675 FD->removeInClassInitializer();
1676 return;
1677 }
1678
Richard Smith7a614d82011-06-11 17:19:42 +00001679 ExprResult Init = InitExpr;
1680 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001681 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001682 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001683 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1684 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001685 Expr **Inits = &InitExpr;
1686 unsigned NumInits = 1;
1687 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1688 InitializationKind Kind = EqualLoc.isInvalid()
1689 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1690 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1691 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1692 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001693 if (Init.isInvalid()) {
1694 FD->setInvalidDecl();
1695 return;
1696 }
1697
1698 CheckImplicitConversions(Init.get(), EqualLoc);
1699 }
1700
1701 // C++0x [class.base.init]p7:
1702 // The initialization of each base and member constitutes a
1703 // full-expression.
1704 Init = MaybeCreateExprWithCleanups(Init);
1705 if (Init.isInvalid()) {
1706 FD->setInvalidDecl();
1707 return;
1708 }
1709
1710 InitExpr = Init.release();
1711
1712 FD->setInClassInitializer(InitExpr);
1713}
1714
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001715/// \brief Find the direct and/or virtual base specifiers that
1716/// correspond to the given base type, for use in base initialization
1717/// within a constructor.
1718static bool FindBaseInitializer(Sema &SemaRef,
1719 CXXRecordDecl *ClassDecl,
1720 QualType BaseType,
1721 const CXXBaseSpecifier *&DirectBaseSpec,
1722 const CXXBaseSpecifier *&VirtualBaseSpec) {
1723 // First, check for a direct base class.
1724 DirectBaseSpec = 0;
1725 for (CXXRecordDecl::base_class_const_iterator Base
1726 = ClassDecl->bases_begin();
1727 Base != ClassDecl->bases_end(); ++Base) {
1728 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1729 // We found a direct base of this type. That's what we're
1730 // initializing.
1731 DirectBaseSpec = &*Base;
1732 break;
1733 }
1734 }
1735
1736 // Check for a virtual base class.
1737 // FIXME: We might be able to short-circuit this if we know in advance that
1738 // there are no virtual bases.
1739 VirtualBaseSpec = 0;
1740 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1741 // We haven't found a base yet; search the class hierarchy for a
1742 // virtual base class.
1743 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1744 /*DetectVirtual=*/false);
1745 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1746 BaseType, Paths)) {
1747 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1748 Path != Paths.end(); ++Path) {
1749 if (Path->back().Base->isVirtual()) {
1750 VirtualBaseSpec = Path->back().Base;
1751 break;
1752 }
1753 }
1754 }
1755 }
1756
1757 return DirectBaseSpec || VirtualBaseSpec;
1758}
1759
Sebastian Redl6df65482011-09-24 17:48:25 +00001760/// \brief Handle a C++ member initializer using braced-init-list syntax.
1761MemInitResult
1762Sema::ActOnMemInitializer(Decl *ConstructorD,
1763 Scope *S,
1764 CXXScopeSpec &SS,
1765 IdentifierInfo *MemberOrBase,
1766 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001767 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001768 SourceLocation IdLoc,
1769 Expr *InitList,
1770 SourceLocation EllipsisLoc) {
1771 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001772 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001773 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001774}
1775
1776/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001777MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001778Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001779 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001780 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001781 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001782 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001783 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001784 SourceLocation IdLoc,
1785 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001786 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001787 SourceLocation RParenLoc,
1788 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001789 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1790 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001791 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001792 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001793}
1794
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001795namespace {
1796
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001797// Callback to only accept typo corrections that can be a valid C++ member
1798// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001799class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1800 public:
1801 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1802 : ClassDecl(ClassDecl) {}
1803
1804 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1805 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1806 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1807 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1808 else
1809 return isa<TypeDecl>(ND);
1810 }
1811 return false;
1812 }
1813
1814 private:
1815 CXXRecordDecl *ClassDecl;
1816};
1817
1818}
1819
Sebastian Redl6df65482011-09-24 17:48:25 +00001820/// \brief Handle a C++ member initializer.
1821MemInitResult
1822Sema::BuildMemInitializer(Decl *ConstructorD,
1823 Scope *S,
1824 CXXScopeSpec &SS,
1825 IdentifierInfo *MemberOrBase,
1826 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001827 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001828 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001829 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001830 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001831 if (!ConstructorD)
1832 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001834 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
1836 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001837 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001838 if (!Constructor) {
1839 // The user wrote a constructor initializer on a function that is
1840 // not a C++ constructor. Ignore the error for now, because we may
1841 // have more member initializers coming; we'll diagnose it just
1842 // once in ActOnMemInitializers.
1843 return true;
1844 }
1845
1846 CXXRecordDecl *ClassDecl = Constructor->getParent();
1847
1848 // C++ [class.base.init]p2:
1849 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001850 // constructor's class and, if not found in that scope, are looked
1851 // up in the scope containing the constructor's definition.
1852 // [Note: if the constructor's class contains a member with the
1853 // same name as a direct or virtual base class of the class, a
1854 // mem-initializer-id naming the member or base class and composed
1855 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001856 // mem-initializer-id for the hidden base class may be specified
1857 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001858 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001859 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001860 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001861 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001862 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001863 ValueDecl *Member;
1864 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1865 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001866 if (EllipsisLoc.isValid())
1867 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001868 << MemberOrBase
1869 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001870
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001871 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001872 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001873 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001874 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001875 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001876 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001877 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001878
1879 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001880 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001881 } else if (DS.getTypeSpecType() == TST_decltype) {
1882 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001883 } else {
1884 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1885 LookupParsedName(R, S, &SS);
1886
1887 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1888 if (!TyD) {
1889 if (R.isAmbiguous()) return true;
1890
John McCallfd225442010-04-09 19:01:14 +00001891 // We don't want access-control diagnostics here.
1892 R.suppressDiagnostics();
1893
Douglas Gregor7a886e12010-01-19 06:46:48 +00001894 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1895 bool NotUnknownSpecialization = false;
1896 DeclContext *DC = computeDeclContext(SS, false);
1897 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1898 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1899
1900 if (!NotUnknownSpecialization) {
1901 // When the scope specifier can refer to a member of an unknown
1902 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001903 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1904 SS.getWithLocInContext(Context),
1905 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001906 if (BaseType.isNull())
1907 return true;
1908
Douglas Gregor7a886e12010-01-19 06:46:48 +00001909 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001910 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001911 }
1912 }
1913
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001914 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001915 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001916 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001917 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001918 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001919 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001920 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1921 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001922 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001923 // We have found a non-static data member with a similar
1924 // name to what was typed; complain and initialize that
1925 // member.
1926 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1927 << MemberOrBase << true << CorrectedQuotedStr
1928 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1929 Diag(Member->getLocation(), diag::note_previous_decl)
1930 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001931
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001932 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001933 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001934 const CXXBaseSpecifier *DirectBaseSpec;
1935 const CXXBaseSpecifier *VirtualBaseSpec;
1936 if (FindBaseInitializer(*this, ClassDecl,
1937 Context.getTypeDeclType(Type),
1938 DirectBaseSpec, VirtualBaseSpec)) {
1939 // We have found a direct or virtual base class with a
1940 // similar name to what was typed; complain and initialize
1941 // that base class.
1942 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001943 << MemberOrBase << false << CorrectedQuotedStr
1944 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001945
1946 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1947 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001948 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001949 diag::note_base_class_specified_here)
1950 << BaseSpec->getType()
1951 << BaseSpec->getSourceRange();
1952
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001953 TyD = Type;
1954 }
1955 }
1956 }
1957
Douglas Gregor7a886e12010-01-19 06:46:48 +00001958 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001959 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001960 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001961 return true;
1962 }
John McCall2b194412009-12-21 10:41:20 +00001963 }
1964
Douglas Gregor7a886e12010-01-19 06:46:48 +00001965 if (BaseType.isNull()) {
1966 BaseType = Context.getTypeDeclType(TyD);
1967 if (SS.isSet()) {
1968 NestedNameSpecifier *Qualifier =
1969 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001970
Douglas Gregor7a886e12010-01-19 06:46:48 +00001971 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001972 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001973 }
John McCall2b194412009-12-21 10:41:20 +00001974 }
1975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
John McCalla93c9342009-12-07 02:54:59 +00001977 if (!TInfo)
1978 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001979
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001980 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001981}
1982
Chandler Carruth81c64772011-09-03 01:14:15 +00001983/// Checks a member initializer expression for cases where reference (or
1984/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001985static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1986 Expr *Init,
1987 SourceLocation IdLoc) {
1988 QualType MemberTy = Member->getType();
1989
1990 // We only handle pointers and references currently.
1991 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1992 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1993 return;
1994
1995 const bool IsPointer = MemberTy->isPointerType();
1996 if (IsPointer) {
1997 if (const UnaryOperator *Op
1998 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1999 // The only case we're worried about with pointers requires taking the
2000 // address.
2001 if (Op->getOpcode() != UO_AddrOf)
2002 return;
2003
2004 Init = Op->getSubExpr();
2005 } else {
2006 // We only handle address-of expression initializers for pointers.
2007 return;
2008 }
2009 }
2010
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002011 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2012 // Taking the address of a temporary will be diagnosed as a hard error.
2013 if (IsPointer)
2014 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002015
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002016 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2017 << Member << Init->getSourceRange();
2018 } else if (const DeclRefExpr *DRE
2019 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2020 // We only warn when referring to a non-reference parameter declaration.
2021 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2022 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002023 return;
2024
2025 S.Diag(Init->getExprLoc(),
2026 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2027 : diag::warn_bind_ref_member_to_parameter)
2028 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002029 } else {
2030 // Other initializers are fine.
2031 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002032 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002033
2034 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2035 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002036}
2037
John McCallb4190042009-11-04 23:02:40 +00002038/// Checks an initializer expression for use of uninitialized fields, such as
2039/// containing the field that is being initialized. Returns true if there is an
2040/// uninitialized field was used an updates the SourceLocation parameter; false
2041/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002042static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002043 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002044 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002045 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2046
Nick Lewycky43ad1822010-06-15 07:32:55 +00002047 if (isa<CallExpr>(S)) {
2048 // Do not descend into function calls or constructors, as the use
2049 // of an uninitialized field may be valid. One would have to inspect
2050 // the contents of the function/ctor to determine if it is safe or not.
2051 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2052 // may be safe, depending on what the function/ctor does.
2053 return false;
2054 }
2055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2056 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002057
2058 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2059 // The member expression points to a static data member.
2060 assert(VD->isStaticDataMember() &&
2061 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002062 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002063 return false;
2064 }
2065
2066 if (isa<EnumConstantDecl>(RhsField)) {
2067 // The member expression points to an enum.
2068 return false;
2069 }
2070
John McCallb4190042009-11-04 23:02:40 +00002071 if (RhsField == LhsField) {
2072 // Initializing a field with itself. Throw a warning.
2073 // But wait; there are exceptions!
2074 // Exception #1: The field may not belong to this record.
2075 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002076 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002077 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2078 // Even though the field matches, it does not belong to this record.
2079 return false;
2080 }
2081 // None of the exceptions triggered; return true to indicate an
2082 // uninitialized field was used.
2083 *L = ME->getMemberLoc();
2084 return true;
2085 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002086 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002087 // sizeof/alignof doesn't reference contents, do not warn.
2088 return false;
2089 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2090 // address-of doesn't reference contents (the pointer may be dereferenced
2091 // in the same expression but it would be rare; and weird).
2092 if (UOE->getOpcode() == UO_AddrOf)
2093 return false;
John McCallb4190042009-11-04 23:02:40 +00002094 }
John McCall7502c1d2011-02-13 04:07:26 +00002095 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002096 if (!*it) {
2097 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002098 continue;
2099 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002100 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2101 return true;
John McCallb4190042009-11-04 23:02:40 +00002102 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002103 return false;
John McCallb4190042009-11-04 23:02:40 +00002104}
2105
John McCallf312b1e2010-08-26 23:41:50 +00002106MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002107Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002109 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2110 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2111 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002112 "Member must be a FieldDecl or IndirectFieldDecl");
2113
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002114 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002115 return true;
2116
Douglas Gregor464b2f02010-11-05 22:21:31 +00002117 if (Member->isInvalidDecl())
2118 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002119
John McCallb4190042009-11-04 23:02:40 +00002120 // Diagnose value-uses of fields to initialize themselves, e.g.
2121 // foo(foo)
2122 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002123 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002124 Expr **Args;
2125 unsigned NumArgs;
2126 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2127 Args = ParenList->getExprs();
2128 NumArgs = ParenList->getNumExprs();
2129 } else {
2130 InitListExpr *InitList = cast<InitListExpr>(Init);
2131 Args = InitList->getInits();
2132 NumArgs = InitList->getNumInits();
2133 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002134
2135 // Mark FieldDecl as being used if it is a non-primitive type and the
2136 // initializer does not call the default constructor (which is trivial
2137 // for all entries in UnusedPrivateFields).
2138 // FIXME: Make this smarter once more side effect-free types can be
2139 // determined.
2140 if (NumArgs > 0) {
2141 if (Member->getType()->isRecordType()) {
2142 UnusedPrivateFields.remove(Member);
2143 } else {
2144 for (unsigned i = 0; i < NumArgs; ++i) {
2145 if (Args[i]->HasSideEffects(Context)) {
2146 UnusedPrivateFields.remove(Member);
2147 break;
2148 }
2149 }
2150 }
2151 }
2152
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002153 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002154 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002155 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002156 // FIXME: Return true in the case when other fields are used before being
2157 // uninitialized. For example, let this field be the i'th field. When
2158 // initializing the i'th field, throw a warning if any of the >= i'th
2159 // fields are used, as they are not yet initialized.
2160 // Right now we are only handling the case where the i'th field uses
2161 // itself in its initializer.
2162 Diag(L, diag::warn_field_is_uninit);
2163 }
2164 }
2165
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002166 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002167
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002168 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002169 // Can't check initialization for a member of dependent type or when
2170 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002171 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002172 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002173 bool InitList = false;
2174 if (isa<InitListExpr>(Init)) {
2175 InitList = true;
2176 Args = &Init;
2177 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002178
2179 if (isStdInitializerList(Member->getType(), 0)) {
2180 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2181 << /*at end of ctor*/1 << InitRange;
2182 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002183 }
2184
Chandler Carruth894aed92010-12-06 09:23:57 +00002185 // Initialize the member.
2186 InitializedEntity MemberEntity =
2187 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2188 : InitializedEntity::InitializeMember(IndirectMember, 0);
2189 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002190 InitList ? InitializationKind::CreateDirectList(IdLoc)
2191 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2192 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002193
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002194 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2195 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2196 MultiExprArg(*this, Args, NumArgs),
2197 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002198 if (MemberInit.isInvalid())
2199 return true;
2200
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002201 CheckImplicitConversions(MemberInit.get(),
2202 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002203
2204 // C++0x [class.base.init]p7:
2205 // The initialization of each base and member constitutes a
2206 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002207 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002208 if (MemberInit.isInvalid())
2209 return true;
2210
2211 // If we are in a dependent context, template instantiation will
2212 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002213 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002214 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2215 // of the information that we have about the member
2216 // initializer. However, deconstructing the ASTs is a dicey process,
2217 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002218 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002219 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002220 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002221 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002222 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2223 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002224 }
2225
Chandler Carruth894aed92010-12-06 09:23:57 +00002226 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2228 InitRange.getBegin(), Init,
2229 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002230 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002231 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2232 InitRange.getBegin(), Init,
2233 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002234 }
Eli Friedman59c04372009-07-29 19:44:27 +00002235}
2236
John McCallf312b1e2010-08-26 23:41:50 +00002237MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002239 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002240 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002241 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002242 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002243 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002244 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002245
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002246 bool InitList = true;
2247 Expr **Args = &Init;
2248 unsigned NumArgs = 1;
2249 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2250 InitList = false;
2251 Args = ParenList->getExprs();
2252 NumArgs = ParenList->getNumExprs();
2253 }
2254
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002255 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002256 // Initialize the object.
2257 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2258 QualType(ClassDecl->getTypeForDecl(), 0));
2259 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002260 InitList ? InitializationKind::CreateDirectList(NameLoc)
2261 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2262 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002263 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2264 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2265 MultiExprArg(*this, Args,NumArgs),
2266 0);
Sean Hunt41717662011-02-26 19:13:13 +00002267 if (DelegationInit.isInvalid())
2268 return true;
2269
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002270 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2271 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002272
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002273 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002274
2275 // C++0x [class.base.init]p7:
2276 // The initialization of each base and member constitutes a
2277 // full-expression.
2278 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2279 if (DelegationInit.isInvalid())
2280 return true;
2281
Eli Friedmand21016f2012-05-19 23:35:23 +00002282 // If we are in a dependent context, template instantiation will
2283 // perform this type-checking again. Just save the arguments that we
2284 // received in a ParenListExpr.
2285 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2286 // of the information that we have about the base
2287 // initializer. However, deconstructing the ASTs is a dicey process,
2288 // and this approach is far more likely to get the corner cases right.
2289 if (CurContext->isDependentContext())
2290 DelegationInit = Owned(Init);
2291
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002292 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002293 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002294 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002295}
2296
2297MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002298Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002299 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002300 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002301 SourceLocation BaseLoc
2302 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002303
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002304 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2305 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2306 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2307
2308 // C++ [class.base.init]p2:
2309 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002310 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002311 // of that class, the mem-initializer is ill-formed. A
2312 // mem-initializer-list can initialize a base class using any
2313 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002314 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002315
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002317 if (EllipsisLoc.isValid()) {
2318 // This is a pack expansion.
2319 if (!BaseType->containsUnexpandedParameterPack()) {
2320 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002321 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002322
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002323 EllipsisLoc = SourceLocation();
2324 }
2325 } else {
2326 // Check for any unexpanded parameter packs.
2327 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2328 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002329
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002330 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002331 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002332 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002333
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002334 // Check for direct and virtual base classes.
2335 const CXXBaseSpecifier *DirectBaseSpec = 0;
2336 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2337 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002338 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2339 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002341
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002342 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2343 VirtualBaseSpec);
2344
2345 // C++ [base.class.init]p2:
2346 // Unless the mem-initializer-id names a nonstatic data member of the
2347 // constructor's class or a direct or virtual base of that class, the
2348 // mem-initializer is ill-formed.
2349 if (!DirectBaseSpec && !VirtualBaseSpec) {
2350 // If the class has any dependent bases, then it's possible that
2351 // one of those types will resolve to the same type as
2352 // BaseType. Therefore, just treat this as a dependent base
2353 // class initialization. FIXME: Should we try to check the
2354 // initialization anyway? It seems odd.
2355 if (ClassDecl->hasAnyDependentBases())
2356 Dependent = true;
2357 else
2358 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2359 << BaseType << Context.getTypeDeclType(ClassDecl)
2360 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2361 }
2362 }
2363
2364 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002365 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Sebastian Redl6df65482011-09-24 17:48:25 +00002367 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2368 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002369 InitRange.getBegin(), Init,
2370 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002371 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002372
2373 // C++ [base.class.init]p2:
2374 // If a mem-initializer-id is ambiguous because it designates both
2375 // a direct non-virtual base class and an inherited virtual base
2376 // class, the mem-initializer is ill-formed.
2377 if (DirectBaseSpec && VirtualBaseSpec)
2378 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002379 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002380
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002381 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002382 if (!BaseSpec)
2383 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2384
2385 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002386 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002387 Expr **Args = &Init;
2388 unsigned NumArgs = 1;
2389 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002390 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002391 Args = ParenList->getExprs();
2392 NumArgs = ParenList->getNumExprs();
2393 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002394
2395 InitializedEntity BaseEntity =
2396 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2397 InitializationKind Kind =
2398 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2399 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2400 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2402 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2403 MultiExprArg(*this, Args, NumArgs),
2404 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002405 if (BaseInit.isInvalid())
2406 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002407
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002408 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002409
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002410 // C++0x [class.base.init]p7:
2411 // The initialization of each base and member constitutes a
2412 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002413 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002414 if (BaseInit.isInvalid())
2415 return true;
2416
2417 // If we are in a dependent context, template instantiation will
2418 // perform this type-checking again. Just save the arguments that we
2419 // received in a ParenListExpr.
2420 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2421 // of the information that we have about the base
2422 // initializer. However, deconstructing the ASTs is a dicey process,
2423 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002424 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002426
Sean Huntcbb67482011-01-08 20:30:50 +00002427 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002428 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002429 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002430 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002431 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002432}
2433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002434// Create a static_cast\<T&&>(expr).
2435static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2436 QualType ExprType = E->getType();
2437 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2438 SourceLocation ExprLoc = E->getLocStart();
2439 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2440 TargetType, ExprLoc);
2441
2442 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2443 SourceRange(ExprLoc, ExprLoc),
2444 E->getSourceRange()).take();
2445}
2446
Anders Carlssone5ef7402010-04-23 03:10:23 +00002447/// ImplicitInitializerKind - How an implicit base or member initializer should
2448/// initialize its base or member.
2449enum ImplicitInitializerKind {
2450 IIK_Default,
2451 IIK_Copy,
2452 IIK_Move
2453};
2454
Anders Carlssondefefd22010-04-23 02:00:02 +00002455static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002456BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002457 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002458 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002459 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002460 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002461 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002462 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2463 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002464
John McCall60d7b3a2010-08-24 06:29:42 +00002465 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002466
2467 switch (ImplicitInitKind) {
2468 case IIK_Default: {
2469 InitializationKind InitKind
2470 = InitializationKind::CreateDefault(Constructor->getLocation());
2471 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2472 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002473 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002474 break;
2475 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002476
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002477 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002478 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002479 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002480 ParmVarDecl *Param = Constructor->getParamDecl(0);
2481 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002482
Anders Carlssone5ef7402010-04-23 03:10:23 +00002483 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002484 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002485 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002486 Constructor->getLocation(), ParamType,
2487 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002488
Eli Friedman5f2987c2012-02-02 03:46:19 +00002489 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2490
Anders Carlssonc7957502010-04-24 22:02:54 +00002491 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002492 QualType ArgTy =
2493 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2494 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002495
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002496 if (Moving) {
2497 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2498 }
2499
John McCallf871d0c2010-08-07 06:22:56 +00002500 CXXCastPath BasePath;
2501 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002502 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2503 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002504 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002505 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002506
Anders Carlssone5ef7402010-04-23 03:10:23 +00002507 InitializationKind InitKind
2508 = InitializationKind::CreateDirect(Constructor->getLocation(),
2509 SourceLocation(), SourceLocation());
2510 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2511 &CopyCtorArg, 1);
2512 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002513 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002514 break;
2515 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002516 }
John McCall9ae2f072010-08-23 23:25:46 +00002517
Douglas Gregor53c374f2010-12-07 00:41:46 +00002518 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002519 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002520 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002521
Anders Carlssondefefd22010-04-23 02:00:02 +00002522 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002523 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002524 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2525 SourceLocation()),
2526 BaseSpec->isVirtual(),
2527 SourceLocation(),
2528 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002529 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002530 SourceLocation());
2531
Anders Carlssondefefd22010-04-23 02:00:02 +00002532 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002533}
2534
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002535static bool RefersToRValueRef(Expr *MemRef) {
2536 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2537 return Referenced->getType()->isRValueReferenceType();
2538}
2539
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002540static bool
2541BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002542 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002543 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002544 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002545 if (Field->isInvalidDecl())
2546 return true;
2547
Chandler Carruthf186b542010-06-29 23:50:44 +00002548 SourceLocation Loc = Constructor->getLocation();
2549
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002550 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2551 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002552 ParmVarDecl *Param = Constructor->getParamDecl(0);
2553 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002554
2555 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002556 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2557 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002558
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002559 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002560 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002561 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002562 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002563
Eli Friedman5f2987c2012-02-02 03:46:19 +00002564 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2565
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002566 if (Moving) {
2567 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2568 }
2569
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002570 // Build a reference to this field within the parameter.
2571 CXXScopeSpec SS;
2572 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2573 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002574 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2575 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002576 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002577 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002578 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002579 ParamType, Loc,
2580 /*IsArrow=*/false,
2581 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002582 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002583 /*FirstQualifierInScope=*/0,
2584 MemberLookup,
2585 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002586 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002587 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002588
2589 // C++11 [class.copy]p15:
2590 // - if a member m has rvalue reference type T&&, it is direct-initialized
2591 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002592 if (RefersToRValueRef(CtorArg.get())) {
2593 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002594 }
2595
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596 // When the field we are copying is an array, create index variables for
2597 // each dimension of the array. We use these index variables to subscript
2598 // the source array, and other clients (e.g., CodeGen) will perform the
2599 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002600 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002601 QualType BaseType = Field->getType();
2602 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002603 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002604 while (const ConstantArrayType *Array
2605 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002606 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 // Create the iteration variable for this array index.
2608 IdentifierInfo *IterationVarName = 0;
2609 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002610 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002611 llvm::raw_svector_ostream OS(Str);
2612 OS << "__i" << IndexVariables.size();
2613 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2614 }
2615 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002616 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002617 IterationVarName, SizeType,
2618 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002619 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002620 IndexVariables.push_back(IterationVar);
2621
2622 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002623 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002624 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002625 assert(!IterationVarRef.isInvalid() &&
2626 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002627 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2628 assert(!IterationVarRef.isInvalid() &&
2629 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002630
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002632 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002633 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002634 Loc);
2635 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002636 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002637
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002638 BaseType = Array->getElementType();
2639 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002640
2641 // The array subscript expression is an lvalue, which is wrong for moving.
2642 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002643 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002644
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002645 // Construct the entity that we will be initializing. For an array, this
2646 // will be first element in the array, which may require several levels
2647 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002648 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002649 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002650 if (Indirect)
2651 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2652 else
2653 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002654 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2655 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2656 0,
2657 Entities.back()));
2658
2659 // Direct-initialize to use the copy constructor.
2660 InitializationKind InitKind =
2661 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2662
Sebastian Redl74e611a2011-09-04 18:14:28 +00002663 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002664 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002665 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002666
John McCall60d7b3a2010-08-24 06:29:42 +00002667 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002668 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002669 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002670 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002671 if (MemberInit.isInvalid())
2672 return true;
2673
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002674 if (Indirect) {
2675 assert(IndexVariables.size() == 0 &&
2676 "Indirect field improperly initialized");
2677 CXXMemberInit
2678 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2679 Loc, Loc,
2680 MemberInit.takeAs<Expr>(),
2681 Loc);
2682 } else
2683 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2684 Loc, MemberInit.takeAs<Expr>(),
2685 Loc,
2686 IndexVariables.data(),
2687 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002688 return false;
2689 }
2690
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002691 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2692
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002693 QualType FieldBaseElementType =
2694 SemaRef.Context.getBaseElementType(Field->getType());
2695
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002696 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002697 InitializedEntity InitEntity
2698 = Indirect? InitializedEntity::InitializeMember(Indirect)
2699 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002700 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002701 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002702
2703 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002704 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002705 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002706
Douglas Gregor53c374f2010-12-07 00:41:46 +00002707 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002708 if (MemberInit.isInvalid())
2709 return true;
2710
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002711 if (Indirect)
2712 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2713 Indirect, Loc,
2714 Loc,
2715 MemberInit.get(),
2716 Loc);
2717 else
2718 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2719 Field, Loc, Loc,
2720 MemberInit.get(),
2721 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002722 return false;
2723 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002724
Sean Hunt1f2f3842011-05-17 00:19:05 +00002725 if (!Field->getParent()->isUnion()) {
2726 if (FieldBaseElementType->isReferenceType()) {
2727 SemaRef.Diag(Constructor->getLocation(),
2728 diag::err_uninitialized_member_in_ctor)
2729 << (int)Constructor->isImplicit()
2730 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2731 << 0 << Field->getDeclName();
2732 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2733 return true;
2734 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002735
Sean Hunt1f2f3842011-05-17 00:19:05 +00002736 if (FieldBaseElementType.isConstQualified()) {
2737 SemaRef.Diag(Constructor->getLocation(),
2738 diag::err_uninitialized_member_in_ctor)
2739 << (int)Constructor->isImplicit()
2740 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2741 << 1 << Field->getDeclName();
2742 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2743 return true;
2744 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002745 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002746
David Blaikie4e4d0842012-03-11 07:00:24 +00002747 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002748 FieldBaseElementType->isObjCRetainableType() &&
2749 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2750 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2751 // Instant objects:
2752 // Default-initialize Objective-C pointers to NULL.
2753 CXXMemberInit
2754 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2755 Loc, Loc,
2756 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2757 Loc);
2758 return false;
2759 }
2760
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002761 // Nothing to initialize.
2762 CXXMemberInit = 0;
2763 return false;
2764}
John McCallf1860e52010-05-20 23:23:51 +00002765
2766namespace {
2767struct BaseAndFieldInfo {
2768 Sema &S;
2769 CXXConstructorDecl *Ctor;
2770 bool AnyErrorsInInits;
2771 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002772 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002773 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002774
2775 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2776 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002777 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2778 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002779 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002780 else if (Generated && Ctor->isMoveConstructor())
2781 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002782 else
2783 IIK = IIK_Default;
2784 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002785
2786 bool isImplicitCopyOrMove() const {
2787 switch (IIK) {
2788 case IIK_Copy:
2789 case IIK_Move:
2790 return true;
2791
2792 case IIK_Default:
2793 return false;
2794 }
David Blaikie30263482012-01-20 21:50:17 +00002795
2796 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002797 }
John McCallf1860e52010-05-20 23:23:51 +00002798};
2799}
2800
Richard Smitha4950662011-09-19 13:34:43 +00002801/// \brief Determine whether the given indirect field declaration is somewhere
2802/// within an anonymous union.
2803static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2804 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2805 CEnd = F->chain_end();
2806 C != CEnd; ++C)
2807 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2808 if (Record->isUnion())
2809 return true;
2810
2811 return false;
2812}
2813
Douglas Gregorddb21472011-11-02 23:04:16 +00002814/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2815/// array type.
2816static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2817 if (T->isIncompleteArrayType())
2818 return true;
2819
2820 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2821 if (!ArrayT->getSize())
2822 return true;
2823
2824 T = ArrayT->getElementType();
2825 }
2826
2827 return false;
2828}
2829
Richard Smith7a614d82011-06-11 17:19:42 +00002830static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002831 FieldDecl *Field,
2832 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002833
Chandler Carruthe861c602010-06-30 02:59:29 +00002834 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002835 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002836 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002837 return false;
2838 }
2839
Richard Smith7a614d82011-06-11 17:19:42 +00002840 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2841 // has a brace-or-equal-initializer, the entity is initialized as specified
2842 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002843 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002844 CXXCtorInitializer *Init;
2845 if (Indirect)
2846 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2847 SourceLocation(),
2848 SourceLocation(), 0,
2849 SourceLocation());
2850 else
2851 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2852 SourceLocation(),
2853 SourceLocation(), 0,
2854 SourceLocation());
2855 Info.AllToInit.push_back(Init);
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002856
2857 // Check whether this initializer makes the field "used".
2858 Expr *InitExpr = Field->getInClassInitializer();
2859 if (Field->getType()->isRecordType() ||
2860 (InitExpr && InitExpr->HasSideEffects(SemaRef.Context)))
2861 SemaRef.UnusedPrivateFields.remove(Field);
2862
Richard Smith7a614d82011-06-11 17:19:42 +00002863 return false;
2864 }
2865
Richard Smithc115f632011-09-18 11:14:50 +00002866 // Don't build an implicit initializer for union members if none was
2867 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002868 if (Field->getParent()->isUnion() ||
2869 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002870 return false;
2871
Douglas Gregorddb21472011-11-02 23:04:16 +00002872 // Don't initialize incomplete or zero-length arrays.
2873 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2874 return false;
2875
John McCallf1860e52010-05-20 23:23:51 +00002876 // Don't try to build an implicit initializer if there were semantic
2877 // errors in any of the initializers (and therefore we might be
2878 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002879 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002880 return false;
2881
Sean Huntcbb67482011-01-08 20:30:50 +00002882 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2884 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002885 return true;
John McCallf1860e52010-05-20 23:23:51 +00002886
Francois Pichet00eb3f92010-12-04 09:14:42 +00002887 if (Init)
2888 Info.AllToInit.push_back(Init);
2889
John McCallf1860e52010-05-20 23:23:51 +00002890 return false;
2891}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002892
2893bool
2894Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2895 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002896 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002897 Constructor->setNumCtorInitializers(1);
2898 CXXCtorInitializer **initializer =
2899 new (Context) CXXCtorInitializer*[1];
2900 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2901 Constructor->setCtorInitializers(initializer);
2902
Sean Huntb76af9c2011-05-03 23:05:34 +00002903 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002904 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002905 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2906 }
2907
Sean Huntc1598702011-05-05 00:05:47 +00002908 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002909
Sean Hunt059ce0d2011-05-01 07:04:31 +00002910 return false;
2911}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002912
John McCallb77115d2011-06-17 00:18:42 +00002913bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2914 CXXCtorInitializer **Initializers,
2915 unsigned NumInitializers,
2916 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002917 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002918 // Just store the initializers as written, they will be checked during
2919 // instantiation.
2920 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002921 Constructor->setNumCtorInitializers(NumInitializers);
2922 CXXCtorInitializer **baseOrMemberInitializers =
2923 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002925 NumInitializers * sizeof(CXXCtorInitializer*));
2926 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002927 }
2928
2929 return false;
2930 }
2931
John McCallf1860e52010-05-20 23:23:51 +00002932 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002933
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002934 // We need to build the initializer AST according to order of construction
2935 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002936 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002937 if (!ClassDecl)
2938 return true;
2939
Eli Friedman80c30da2009-11-09 19:20:36 +00002940 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002942 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002943 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002944
2945 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002946 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002947 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002948 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002949 }
2950
Anders Carlsson711f34a2010-04-21 19:52:01 +00002951 // Keep track of the direct virtual bases.
2952 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2953 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2954 E = ClassDecl->bases_end(); I != E; ++I) {
2955 if (I->isVirtual())
2956 DirectVBases.insert(I);
2957 }
2958
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002959 // Push virtual bases before others.
2960 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2961 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2962
Sean Huntcbb67482011-01-08 20:30:50 +00002963 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002964 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2965 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002966 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002967 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002968 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002969 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002970 VBase, IsInheritedVirtualBase,
2971 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002972 HadError = true;
2973 continue;
2974 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002975
John McCallf1860e52010-05-20 23:23:51 +00002976 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002977 }
2978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCallf1860e52010-05-20 23:23:51 +00002980 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2982 E = ClassDecl->bases_end(); Base != E; ++Base) {
2983 // Virtuals are in the virtual base list and already constructed.
2984 if (Base->isVirtual())
2985 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Sean Huntcbb67482011-01-08 20:30:50 +00002987 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002988 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2989 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002990 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002991 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002992 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002993 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002994 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002995 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002996 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002997 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002998
John McCallf1860e52010-05-20 23:23:51 +00002999 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003000 }
3001 }
Mike Stump1eb44332009-09-09 15:08:12 +00003002
John McCallf1860e52010-05-20 23:23:51 +00003003 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003004 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3005 MemEnd = ClassDecl->decls_end();
3006 Mem != MemEnd; ++Mem) {
3007 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003008 // C++ [class.bit]p2:
3009 // A declaration for a bit-field that omits the identifier declares an
3010 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3011 // initialized.
3012 if (F->isUnnamedBitfield())
3013 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003014
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003015 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003016 // handle anonymous struct/union fields based on their individual
3017 // indirect fields.
3018 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3019 continue;
3020
3021 if (CollectFieldInitializer(*this, Info, F))
3022 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003023 continue;
3024 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003025
3026 // Beyond this point, we only consider default initialization.
3027 if (Info.IIK != IIK_Default)
3028 continue;
3029
3030 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3031 if (F->getType()->isIncompleteArrayType()) {
3032 assert(ClassDecl->hasFlexibleArrayMember() &&
3033 "Incomplete array type is not valid");
3034 continue;
3035 }
3036
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003037 // Initialize each field of an anonymous struct individually.
3038 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3039 HadError = true;
3040
3041 continue;
3042 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003043 }
Mike Stump1eb44332009-09-09 15:08:12 +00003044
John McCallf1860e52010-05-20 23:23:51 +00003045 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003046 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003047 Constructor->setNumCtorInitializers(NumInitializers);
3048 CXXCtorInitializer **baseOrMemberInitializers =
3049 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003050 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003051 NumInitializers * sizeof(CXXCtorInitializer*));
3052 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003053
John McCallef027fe2010-03-16 21:39:52 +00003054 // Constructors implicitly reference the base and member
3055 // destructors.
3056 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3057 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003058 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003059
3060 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003061}
3062
Eli Friedman6347f422009-07-21 19:28:10 +00003063static void *GetKeyForTopLevelField(FieldDecl *Field) {
3064 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003065 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003066 if (RT->getDecl()->isAnonymousStructOrUnion())
3067 return static_cast<void *>(RT->getDecl());
3068 }
3069 return static_cast<void *>(Field);
3070}
3071
Anders Carlssonea356fb2010-04-02 05:42:15 +00003072static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003073 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003074}
3075
Anders Carlssonea356fb2010-04-02 05:42:15 +00003076static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003077 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003078 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003079 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003080
Eli Friedman6347f422009-07-21 19:28:10 +00003081 // For fields injected into the class via declaration of an anonymous union,
3082 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003083 FieldDecl *Field = Member->getAnyMember();
3084
John McCall3c3ccdb2010-04-10 09:28:51 +00003085 // If the field is a member of an anonymous struct or union, our key
3086 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003087 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003088 if (RD->isAnonymousStructOrUnion()) {
3089 while (true) {
3090 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3091 if (Parent->isAnonymousStructOrUnion())
3092 RD = Parent;
3093 else
3094 break;
3095 }
3096
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003097 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003098 }
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003100 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003101}
3102
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003103static void
3104DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003105 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003106 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003107 unsigned NumInits) {
3108 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003109 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003111 // Don't check initializers order unless the warning is enabled at the
3112 // location of at least one initializer.
3113 bool ShouldCheckOrder = false;
3114 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003115 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003116 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3117 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003118 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003119 ShouldCheckOrder = true;
3120 break;
3121 }
3122 }
3123 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003124 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003125
John McCalld6ca8da2010-04-10 07:37:23 +00003126 // Build the list of bases and members in the order that they'll
3127 // actually be initialized. The explicit initializers should be in
3128 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003129 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Anders Carlsson071d6102010-04-02 03:38:04 +00003131 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3132
John McCalld6ca8da2010-04-10 07:37:23 +00003133 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003134 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003135 ClassDecl->vbases_begin(),
3136 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003137 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003138
John McCalld6ca8da2010-04-10 07:37:23 +00003139 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003140 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003141 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003142 if (Base->isVirtual())
3143 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003144 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
John McCalld6ca8da2010-04-10 07:37:23 +00003147 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003148 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003149 E = ClassDecl->field_end(); Field != E; ++Field) {
3150 if (Field->isUnnamedBitfield())
3151 continue;
3152
David Blaikie581deb32012-06-06 20:45:41 +00003153 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003154 }
3155
John McCalld6ca8da2010-04-10 07:37:23 +00003156 unsigned NumIdealInits = IdealInitKeys.size();
3157 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003158
Sean Huntcbb67482011-01-08 20:30:50 +00003159 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003160 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003161 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003162 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003163
3164 // Scan forward to try to find this initializer in the idealized
3165 // initializers list.
3166 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3167 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003168 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003169
3170 // If we didn't find this initializer, it must be because we
3171 // scanned past it on a previous iteration. That can only
3172 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003173 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003174 Sema::SemaDiagnosticBuilder D =
3175 SemaRef.Diag(PrevInit->getSourceLocation(),
3176 diag::warn_initializer_out_of_order);
3177
Francois Pichet00eb3f92010-12-04 09:14:42 +00003178 if (PrevInit->isAnyMemberInitializer())
3179 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003180 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003181 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003182
Francois Pichet00eb3f92010-12-04 09:14:42 +00003183 if (Init->isAnyMemberInitializer())
3184 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003185 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003186 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003187
3188 // Move back to the initializer's location in the ideal list.
3189 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3190 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003191 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003192
3193 assert(IdealIndex != NumIdealInits &&
3194 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003195 }
John McCalld6ca8da2010-04-10 07:37:23 +00003196
3197 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003198 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003199}
3200
John McCall3c3ccdb2010-04-10 09:28:51 +00003201namespace {
3202bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003203 CXXCtorInitializer *Init,
3204 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003205 if (!PrevInit) {
3206 PrevInit = Init;
3207 return false;
3208 }
3209
3210 if (FieldDecl *Field = Init->getMember())
3211 S.Diag(Init->getSourceLocation(),
3212 diag::err_multiple_mem_initialization)
3213 << Field->getDeclName()
3214 << Init->getSourceRange();
3215 else {
John McCallf4c73712011-01-19 06:33:43 +00003216 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003217 assert(BaseClass && "neither field nor base");
3218 S.Diag(Init->getSourceLocation(),
3219 diag::err_multiple_base_initialization)
3220 << QualType(BaseClass, 0)
3221 << Init->getSourceRange();
3222 }
3223 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3224 << 0 << PrevInit->getSourceRange();
3225
3226 return true;
3227}
3228
Sean Huntcbb67482011-01-08 20:30:50 +00003229typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003230typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3231
3232bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003233 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003234 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003235 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003236 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003237 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003238
3239 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003240 if (Parent->isUnion()) {
3241 UnionEntry &En = Unions[Parent];
3242 if (En.first && En.first != Child) {
3243 S.Diag(Init->getSourceLocation(),
3244 diag::err_multiple_mem_union_initialization)
3245 << Field->getDeclName()
3246 << Init->getSourceRange();
3247 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3248 << 0 << En.second->getSourceRange();
3249 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003250 }
3251 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003252 En.first = Child;
3253 En.second = Init;
3254 }
David Blaikie6fe29652011-11-17 06:01:57 +00003255 if (!Parent->isAnonymousStructOrUnion())
3256 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003257 }
3258
3259 Child = Parent;
3260 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003261 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003262
3263 return false;
3264}
3265}
3266
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003267/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003268void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003269 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003270 CXXCtorInitializer **meminits,
3271 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003272 bool AnyErrors) {
3273 if (!ConstructorDecl)
3274 return;
3275
3276 AdjustDeclIfTemplate(ConstructorDecl);
3277
3278 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003279 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003280
3281 if (!Constructor) {
3282 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3283 return;
3284 }
3285
Sean Huntcbb67482011-01-08 20:30:50 +00003286 CXXCtorInitializer **MemInits =
3287 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003288
3289 // Mapping for the duplicate initializers check.
3290 // For member initializers, this is keyed with a FieldDecl*.
3291 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003292 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003293
3294 // Mapping for the inconsistent anonymous-union initializers check.
3295 RedundantUnionMap MemberUnions;
3296
Anders Carlssonea356fb2010-04-02 05:42:15 +00003297 bool HadError = false;
3298 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003299 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003300
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003301 // Set the source order index.
3302 Init->setSourceOrder(i);
3303
Francois Pichet00eb3f92010-12-04 09:14:42 +00003304 if (Init->isAnyMemberInitializer()) {
3305 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003306 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3307 CheckRedundantUnionInit(*this, Init, MemberUnions))
3308 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003309 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003310 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3311 if (CheckRedundantInit(*this, Init, Members[Key]))
3312 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003313 } else {
3314 assert(Init->isDelegatingInitializer());
3315 // This must be the only initializer
3316 if (i != 0 || NumMemInits > 1) {
3317 Diag(MemInits[0]->getSourceLocation(),
3318 diag::err_delegating_initializer_alone)
3319 << MemInits[0]->getSourceRange();
3320 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003321 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003322 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003323 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003324 // Return immediately as the initializer is set.
3325 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003326 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003327 }
3328
Anders Carlssonea356fb2010-04-02 05:42:15 +00003329 if (HadError)
3330 return;
3331
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003332 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003333
Sean Huntcbb67482011-01-08 20:30:50 +00003334 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003335}
3336
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003337void
John McCallef027fe2010-03-16 21:39:52 +00003338Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3339 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003340 // Ignore dependent contexts. Also ignore unions, since their members never
3341 // have destructors implicitly called.
3342 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003343 return;
John McCall58e6f342010-03-16 05:22:47 +00003344
3345 // FIXME: all the access-control diagnostics are positioned on the
3346 // field/base declaration. That's probably good; that said, the
3347 // user might reasonably want to know why the destructor is being
3348 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003349
Anders Carlsson9f853df2009-11-17 04:44:12 +00003350 // Non-static data members.
3351 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3352 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003353 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003354 if (Field->isInvalidDecl())
3355 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003356
3357 // Don't destroy incomplete or zero-length arrays.
3358 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3359 continue;
3360
Anders Carlsson9f853df2009-11-17 04:44:12 +00003361 QualType FieldType = Context.getBaseElementType(Field->getType());
3362
3363 const RecordType* RT = FieldType->getAs<RecordType>();
3364 if (!RT)
3365 continue;
3366
3367 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003368 if (FieldClassDecl->isInvalidDecl())
3369 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003370 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003371 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003372 // The destructor for an implicit anonymous union member is never invoked.
3373 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3374 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003375
Douglas Gregordb89f282010-07-01 22:47:18 +00003376 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003377 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003378 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003379 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003380 << Field->getDeclName()
3381 << FieldType);
3382
Eli Friedman5f2987c2012-02-02 03:46:19 +00003383 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003384 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003385 }
3386
John McCall58e6f342010-03-16 05:22:47 +00003387 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3388
Anders Carlsson9f853df2009-11-17 04:44:12 +00003389 // Bases.
3390 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3391 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003392 // Bases are always records in a well-formed non-dependent class.
3393 const RecordType *RT = Base->getType()->getAs<RecordType>();
3394
3395 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003396 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003397 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003398
John McCall58e6f342010-03-16 05:22:47 +00003399 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003400 // If our base class is invalid, we probably can't get its dtor anyway.
3401 if (BaseClassDecl->isInvalidDecl())
3402 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003403 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003404 continue;
John McCall58e6f342010-03-16 05:22:47 +00003405
Douglas Gregordb89f282010-07-01 22:47:18 +00003406 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003407 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003408
3409 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003410 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003411 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003412 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003413 << Base->getSourceRange(),
3414 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003415
Eli Friedman5f2987c2012-02-02 03:46:19 +00003416 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003417 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003418 }
3419
3420 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003421 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3422 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003423
3424 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003425 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003426
3427 // Ignore direct virtual bases.
3428 if (DirectVirtualBases.count(RT))
3429 continue;
3430
John McCall58e6f342010-03-16 05:22:47 +00003431 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003432 // If our base class is invalid, we probably can't get its dtor anyway.
3433 if (BaseClassDecl->isInvalidDecl())
3434 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003435 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003436 continue;
John McCall58e6f342010-03-16 05:22:47 +00003437
Douglas Gregordb89f282010-07-01 22:47:18 +00003438 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003439 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003440 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003441 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003442 << VBase->getType(),
3443 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003444
Eli Friedman5f2987c2012-02-02 03:46:19 +00003445 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003446 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003447 }
3448}
3449
John McCalld226f652010-08-21 09:40:31 +00003450void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003451 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003452 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Mike Stump1eb44332009-09-09 15:08:12 +00003454 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003455 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003456 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003457}
3458
Mike Stump1eb44332009-09-09 15:08:12 +00003459bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003460 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003461 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3462 unsigned DiagID;
3463 AbstractDiagSelID SelID;
3464
3465 public:
3466 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3467 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3468
3469 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3470 if (SelID == -1)
3471 S.Diag(Loc, DiagID) << T;
3472 else
3473 S.Diag(Loc, DiagID) << SelID << T;
3474 }
3475 } Diagnoser(DiagID, SelID);
3476
3477 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003478}
3479
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003480bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003481 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003482 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003483 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Anders Carlsson11f21a02009-03-23 19:10:31 +00003485 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003486 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003487
Ted Kremenek6217b802009-07-29 21:53:49 +00003488 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003489 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003490 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003491 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003492
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003493 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003494 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Ted Kremenek6217b802009-07-29 21:53:49 +00003497 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003498 if (!RT)
3499 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003500
John McCall86ff3082010-02-04 22:26:26 +00003501 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003502
John McCall94c3b562010-08-18 09:41:07 +00003503 // We can't answer whether something is abstract until it has a
3504 // definition. If it's currently being defined, we'll walk back
3505 // over all the declarations when we have a full definition.
3506 const CXXRecordDecl *Def = RD->getDefinition();
3507 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003508 return false;
3509
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003510 if (!RD->isAbstract())
3511 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003513 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003514 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003515
John McCall94c3b562010-08-18 09:41:07 +00003516 return true;
3517}
3518
3519void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3520 // Check if we've already emitted the list of pure virtual functions
3521 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003522 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003523 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003525 CXXFinalOverriderMap FinalOverriders;
3526 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003528 // Keep a set of seen pure methods so we won't diagnose the same method
3529 // more than once.
3530 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3531
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003532 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3533 MEnd = FinalOverriders.end();
3534 M != MEnd;
3535 ++M) {
3536 for (OverridingMethods::iterator SO = M->second.begin(),
3537 SOEnd = M->second.end();
3538 SO != SOEnd; ++SO) {
3539 // C++ [class.abstract]p4:
3540 // A class is abstract if it contains or inherits at least one
3541 // pure virtual function for which the final overrider is pure
3542 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003544 //
3545 if (SO->second.size() != 1)
3546 continue;
3547
3548 if (!SO->second.front().Method->isPure())
3549 continue;
3550
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003551 if (!SeenPureMethods.insert(SO->second.front().Method))
3552 continue;
3553
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003554 Diag(SO->second.front().Method->getLocation(),
3555 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003556 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003557 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003558 }
3559
3560 if (!PureVirtualClassDiagSet)
3561 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3562 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003563}
3564
Anders Carlsson8211eff2009-03-24 01:19:16 +00003565namespace {
John McCall94c3b562010-08-18 09:41:07 +00003566struct AbstractUsageInfo {
3567 Sema &S;
3568 CXXRecordDecl *Record;
3569 CanQualType AbstractType;
3570 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003571
John McCall94c3b562010-08-18 09:41:07 +00003572 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3573 : S(S), Record(Record),
3574 AbstractType(S.Context.getCanonicalType(
3575 S.Context.getTypeDeclType(Record))),
3576 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003577
John McCall94c3b562010-08-18 09:41:07 +00003578 void DiagnoseAbstractType() {
3579 if (Invalid) return;
3580 S.DiagnoseAbstractType(Record);
3581 Invalid = true;
3582 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003583
John McCall94c3b562010-08-18 09:41:07 +00003584 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3585};
3586
3587struct CheckAbstractUsage {
3588 AbstractUsageInfo &Info;
3589 const NamedDecl *Ctx;
3590
3591 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3592 : Info(Info), Ctx(Ctx) {}
3593
3594 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3595 switch (TL.getTypeLocClass()) {
3596#define ABSTRACT_TYPELOC(CLASS, PARENT)
3597#define TYPELOC(CLASS, PARENT) \
3598 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3599#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003600 }
John McCall94c3b562010-08-18 09:41:07 +00003601 }
Mike Stump1eb44332009-09-09 15:08:12 +00003602
John McCall94c3b562010-08-18 09:41:07 +00003603 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3604 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3605 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003606 if (!TL.getArg(I))
3607 continue;
3608
John McCall94c3b562010-08-18 09:41:07 +00003609 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3610 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003611 }
John McCall94c3b562010-08-18 09:41:07 +00003612 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003613
John McCall94c3b562010-08-18 09:41:07 +00003614 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3615 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3616 }
Mike Stump1eb44332009-09-09 15:08:12 +00003617
John McCall94c3b562010-08-18 09:41:07 +00003618 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3619 // Visit the type parameters from a permissive context.
3620 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3621 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3622 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3623 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3624 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3625 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003626 }
John McCall94c3b562010-08-18 09:41:07 +00003627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
John McCall94c3b562010-08-18 09:41:07 +00003629 // Visit pointee types from a permissive context.
3630#define CheckPolymorphic(Type) \
3631 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3632 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3633 }
3634 CheckPolymorphic(PointerTypeLoc)
3635 CheckPolymorphic(ReferenceTypeLoc)
3636 CheckPolymorphic(MemberPointerTypeLoc)
3637 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003638 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003639
John McCall94c3b562010-08-18 09:41:07 +00003640 /// Handle all the types we haven't given a more specific
3641 /// implementation for above.
3642 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3643 // Every other kind of type that we haven't called out already
3644 // that has an inner type is either (1) sugar or (2) contains that
3645 // inner type in some way as a subobject.
3646 if (TypeLoc Next = TL.getNextTypeLoc())
3647 return Visit(Next, Sel);
3648
3649 // If there's no inner type and we're in a permissive context,
3650 // don't diagnose.
3651 if (Sel == Sema::AbstractNone) return;
3652
3653 // Check whether the type matches the abstract type.
3654 QualType T = TL.getType();
3655 if (T->isArrayType()) {
3656 Sel = Sema::AbstractArrayType;
3657 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003658 }
John McCall94c3b562010-08-18 09:41:07 +00003659 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3660 if (CT != Info.AbstractType) return;
3661
3662 // It matched; do some magic.
3663 if (Sel == Sema::AbstractArrayType) {
3664 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3665 << T << TL.getSourceRange();
3666 } else {
3667 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3668 << Sel << T << TL.getSourceRange();
3669 }
3670 Info.DiagnoseAbstractType();
3671 }
3672};
3673
3674void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3675 Sema::AbstractDiagSelID Sel) {
3676 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3677}
3678
3679}
3680
3681/// Check for invalid uses of an abstract type in a method declaration.
3682static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3683 CXXMethodDecl *MD) {
3684 // No need to do the check on definitions, which require that
3685 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003686 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003687 return;
3688
3689 // For safety's sake, just ignore it if we don't have type source
3690 // information. This should never happen for non-implicit methods,
3691 // but...
3692 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3693 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3694}
3695
3696/// Check for invalid uses of an abstract type within a class definition.
3697static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3698 CXXRecordDecl *RD) {
3699 for (CXXRecordDecl::decl_iterator
3700 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3701 Decl *D = *I;
3702 if (D->isImplicit()) continue;
3703
3704 // Methods and method templates.
3705 if (isa<CXXMethodDecl>(D)) {
3706 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3707 } else if (isa<FunctionTemplateDecl>(D)) {
3708 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3709 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3710
3711 // Fields and static variables.
3712 } else if (isa<FieldDecl>(D)) {
3713 FieldDecl *FD = cast<FieldDecl>(D);
3714 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3715 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3716 } else if (isa<VarDecl>(D)) {
3717 VarDecl *VD = cast<VarDecl>(D);
3718 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3719 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3720
3721 // Nested classes and class templates.
3722 } else if (isa<CXXRecordDecl>(D)) {
3723 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3724 } else if (isa<ClassTemplateDecl>(D)) {
3725 CheckAbstractClassUsage(Info,
3726 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3727 }
3728 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003729}
3730
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003731/// \brief Perform semantic checks on a class definition that has been
3732/// completing, introducing implicitly-declared members, checking for
3733/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003734void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003735 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003736 return;
3737
John McCall94c3b562010-08-18 09:41:07 +00003738 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3739 AbstractUsageInfo Info(*this, Record);
3740 CheckAbstractClassUsage(Info, Record);
3741 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003742
3743 // If this is not an aggregate type and has no user-declared constructor,
3744 // complain about any non-static data members of reference or const scalar
3745 // type, since they will never get initializers.
3746 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003747 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3748 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003749 bool Complained = false;
3750 for (RecordDecl::field_iterator F = Record->field_begin(),
3751 FEnd = Record->field_end();
3752 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003753 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003754 continue;
3755
Douglas Gregor325e5932010-04-15 00:00:53 +00003756 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003757 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003758 if (!Complained) {
3759 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3760 << Record->getTagKind() << Record;
3761 Complained = true;
3762 }
3763
3764 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3765 << F->getType()->isReferenceType()
3766 << F->getDeclName();
3767 }
3768 }
3769 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003770
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003771 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003772 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003773
3774 if (Record->getIdentifier()) {
3775 // C++ [class.mem]p13:
3776 // If T is the name of a class, then each of the following shall have a
3777 // name different from T:
3778 // - every member of every anonymous union that is a member of class T.
3779 //
3780 // C++ [class.mem]p14:
3781 // In addition, if class T has a user-declared constructor (12.1), every
3782 // non-static data member of class T shall have a name different from T.
3783 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003784 R.first != R.second; ++R.first) {
3785 NamedDecl *D = *R.first;
3786 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3787 isa<IndirectFieldDecl>(D)) {
3788 Diag(D->getLocation(), diag::err_member_name_of_class)
3789 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003790 break;
3791 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003792 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003793 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003794
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003795 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003796 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003797 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003798 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003799 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3800 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3801 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003802
3803 // See if a method overloads virtual methods in a base
3804 /// class without overriding any.
3805 if (!Record->isDependentType()) {
3806 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3807 MEnd = Record->method_end();
3808 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003809 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003810 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003811 }
3812 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003813
Richard Smith9f569cc2011-10-01 02:31:28 +00003814 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3815 // function that is not a constructor declares that member function to be
3816 // const. [...] The class of which that function is a member shall be
3817 // a literal type.
3818 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003819 // If the class has virtual bases, any constexpr members will already have
3820 // been diagnosed by the checks performed on the member declaration, so
3821 // suppress this (less useful) diagnostic.
3822 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3823 !Record->isLiteral() && !Record->getNumVBases()) {
3824 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3825 MEnd = Record->method_end();
3826 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003827 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003828 switch (Record->getTemplateSpecializationKind()) {
3829 case TSK_ImplicitInstantiation:
3830 case TSK_ExplicitInstantiationDeclaration:
3831 case TSK_ExplicitInstantiationDefinition:
3832 // If a template instantiates to a non-literal type, but its members
3833 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003834 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003835 continue;
3836
3837 case TSK_Undeclared:
3838 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003839 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003840 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003841 break;
3842 }
3843
3844 // Only produce one error per class.
3845 break;
3846 }
3847 }
3848 }
3849
Sebastian Redlf677ea32011-02-05 19:23:19 +00003850 // Declare inherited constructors. We do this eagerly here because:
3851 // - The standard requires an eager diagnostic for conflicting inherited
3852 // constructors from different classes.
3853 // - The lazy declaration of the other implicit constructors is so as to not
3854 // waste space and performance on classes that are not meant to be
3855 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3856 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003857 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003858
Sean Hunteb88ae52011-05-23 21:07:59 +00003859 if (!Record->isDependentType())
3860 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003861}
3862
3863void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003864 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3865 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003866 MI != ME; ++MI)
3867 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003868 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003869}
3870
Richard Smith3003e1d2012-05-15 04:39:51 +00003871void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
3872 CXXRecordDecl *RD = MD->getParent();
3873 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00003874
Richard Smith3003e1d2012-05-15 04:39:51 +00003875 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
3876 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00003877
3878 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00003879 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00003880 bool First = MD == MD->getCanonicalDecl();
3881
3882 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00003883
3884 // C++11 [dcl.fct.def.default]p1:
3885 // A function that is explicitly defaulted shall
3886 // -- be a special member function (checked elsewhere),
3887 // -- have the same type (except for ref-qualifiers, and except that a
3888 // copy operation can take a non-const reference) as an implicit
3889 // declaration, and
3890 // -- not have default arguments.
3891 unsigned ExpectedParams = 1;
3892 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
3893 ExpectedParams = 0;
3894 if (MD->getNumParams() != ExpectedParams) {
3895 // This also checks for default arguments: a copy or move constructor with a
3896 // default argument is classified as a default constructor, and assignment
3897 // operations and destructors can't have default arguments.
3898 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
3899 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00003900 HadError = true;
3901 }
3902
Richard Smith3003e1d2012-05-15 04:39:51 +00003903 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00003904
Richard Smith3003e1d2012-05-15 04:39:51 +00003905 // Compute implicit exception specification, argument constness, constexpr
3906 // and triviality.
Richard Smithe6975e92012-04-17 00:58:00 +00003907 ImplicitExceptionSpecification Spec(*this);
Richard Smith3003e1d2012-05-15 04:39:51 +00003908 bool Const = false;
3909 bool Constexpr = false;
3910 bool Trivial;
3911 switch (CSM) {
3912 case CXXDefaultConstructor:
3913 Spec = ComputeDefaultedDefaultCtorExceptionSpec(RD);
3914 if (Spec.isDelayed())
3915 // Exception specification depends on some deferred part of the class.
3916 // We'll try again when the class's definition has been fully processed.
3917 return;
3918 Constexpr = RD->defaultedDefaultConstructorIsConstexpr();
3919 Trivial = RD->hasTrivialDefaultConstructor();
3920 break;
3921 case CXXCopyConstructor:
3922 llvm::tie(Spec, Const) =
3923 ComputeDefaultedCopyCtorExceptionSpecAndConst(RD);
3924 Constexpr = RD->defaultedCopyConstructorIsConstexpr();
3925 Trivial = RD->hasTrivialCopyConstructor();
3926 break;
3927 case CXXCopyAssignment:
3928 llvm::tie(Spec, Const) =
3929 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(RD);
3930 Trivial = RD->hasTrivialCopyAssignment();
3931 break;
3932 case CXXMoveConstructor:
3933 Spec = ComputeDefaultedMoveCtorExceptionSpec(RD);
3934 Constexpr = RD->defaultedMoveConstructorIsConstexpr();
3935 Trivial = RD->hasTrivialMoveConstructor();
3936 break;
3937 case CXXMoveAssignment:
3938 Spec = ComputeDefaultedMoveAssignmentExceptionSpec(RD);
3939 Trivial = RD->hasTrivialMoveAssignment();
3940 break;
3941 case CXXDestructor:
3942 Spec = ComputeDefaultedDtorExceptionSpec(RD);
3943 Trivial = RD->hasTrivialDestructor();
3944 break;
3945 case CXXInvalid:
3946 llvm_unreachable("non-special member explicitly defaulted!");
3947 }
Sean Hunt2b188082011-05-14 05:23:28 +00003948
Richard Smith3003e1d2012-05-15 04:39:51 +00003949 QualType ReturnType = Context.VoidTy;
3950 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
3951 // Check for return type matching.
3952 ReturnType = Type->getResultType();
3953 QualType ExpectedReturnType =
3954 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
3955 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
3956 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
3957 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
3958 HadError = true;
3959 }
3960
3961 // A defaulted special member cannot have cv-qualifiers.
3962 if (Type->getTypeQuals()) {
3963 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
3964 << (CSM == CXXMoveAssignment);
3965 HadError = true;
3966 }
3967 }
3968
3969 // Check for parameter type matching.
3970 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
3971 if (ExpectedParams && ArgType->isReferenceType()) {
3972 // Argument must be reference to possibly-const T.
3973 QualType ReferentType = ArgType->getPointeeType();
3974
3975 if (ReferentType.isVolatileQualified()) {
3976 Diag(MD->getLocation(),
3977 diag::err_defaulted_special_member_volatile_param) << CSM;
3978 HadError = true;
3979 }
3980
3981 if (ReferentType.isConstQualified() && !Const) {
3982 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
3983 Diag(MD->getLocation(),
3984 diag::err_defaulted_special_member_copy_const_param)
3985 << (CSM == CXXCopyAssignment);
3986 // FIXME: Explain why this special member can't be const.
3987 } else {
3988 Diag(MD->getLocation(),
3989 diag::err_defaulted_special_member_move_const_param)
3990 << (CSM == CXXMoveAssignment);
3991 }
3992 HadError = true;
3993 }
3994
3995 // If a function is explicitly defaulted on its first declaration, it shall
3996 // have the same parameter type as if it had been implicitly declared.
3997 // (Presumably this is to prevent it from being trivial?)
3998 if (!ReferentType.isConstQualified() && Const && First)
3999 Diag(MD->getLocation(),
4000 diag::err_defaulted_special_member_copy_non_const_param)
4001 << (CSM == CXXCopyAssignment);
4002 } else if (ExpectedParams) {
4003 // A copy assignment operator can take its argument by value, but a
4004 // defaulted one cannot.
4005 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004006 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004007 HadError = true;
4008 }
Sean Huntbe631222011-05-17 20:44:43 +00004009
Richard Smith3003e1d2012-05-15 04:39:51 +00004010 // Rebuild the type with the implicit exception specification added.
4011 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4012 Spec.getEPI(EPI);
4013 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4014 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004015
Richard Smith61802452011-12-22 02:22:31 +00004016 // C++11 [dcl.fct.def.default]p2:
4017 // An explicitly-defaulted function may be declared constexpr only if it
4018 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004019 // Do not apply this rule to members of class templates, since core issue 1358
4020 // makes such functions always instantiate to constexpr functions. For
4021 // non-constructors, this is checked elsewhere.
4022 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4023 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4024 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4025 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004026 }
4027 // and may have an explicit exception-specification only if it is compatible
4028 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004029 if (Type->hasExceptionSpec() &&
4030 CheckEquivalentExceptionSpec(
4031 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4032 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4033 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004034
4035 // If a function is explicitly defaulted on its first declaration,
4036 if (First) {
4037 // -- it is implicitly considered to be constexpr if the implicit
4038 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004039 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004040
Richard Smith3003e1d2012-05-15 04:39:51 +00004041 // -- it is implicitly considered to have the same exception-specification
4042 // as if it had been implicitly declared,
4043 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004044
4045 // Such a function is also trivial if the implicitly-declared function
4046 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004047 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004048 }
4049
Richard Smith3003e1d2012-05-15 04:39:51 +00004050 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004051 if (First) {
4052 MD->setDeletedAsWritten();
4053 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004054 // C++11 [dcl.fct.def.default]p4:
4055 // [For a] user-provided explicitly-defaulted function [...] if such a
4056 // function is implicitly defined as deleted, the program is ill-formed.
4057 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4058 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004059 }
4060 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004061
Richard Smith3003e1d2012-05-15 04:39:51 +00004062 if (HadError)
4063 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004064}
4065
Richard Smith7d5088a2012-02-18 02:02:13 +00004066namespace {
4067struct SpecialMemberDeletionInfo {
4068 Sema &S;
4069 CXXMethodDecl *MD;
4070 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004071 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004072
4073 // Properties of the special member, computed for convenience.
4074 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4075 SourceLocation Loc;
4076
4077 bool AllFieldsAreConst;
4078
4079 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004080 Sema::CXXSpecialMember CSM, bool Diagnose)
4081 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004082 IsConstructor(false), IsAssignment(false), IsMove(false),
4083 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4084 AllFieldsAreConst(true) {
4085 switch (CSM) {
4086 case Sema::CXXDefaultConstructor:
4087 case Sema::CXXCopyConstructor:
4088 IsConstructor = true;
4089 break;
4090 case Sema::CXXMoveConstructor:
4091 IsConstructor = true;
4092 IsMove = true;
4093 break;
4094 case Sema::CXXCopyAssignment:
4095 IsAssignment = true;
4096 break;
4097 case Sema::CXXMoveAssignment:
4098 IsAssignment = true;
4099 IsMove = true;
4100 break;
4101 case Sema::CXXDestructor:
4102 break;
4103 case Sema::CXXInvalid:
4104 llvm_unreachable("invalid special member kind");
4105 }
4106
4107 if (MD->getNumParams()) {
4108 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4109 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4110 }
4111 }
4112
4113 bool inUnion() const { return MD->getParent()->isUnion(); }
4114
4115 /// Look up the corresponding special member in the given class.
4116 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4117 unsigned TQ = MD->getTypeQualifiers();
4118 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4119 MD->getRefQualifier() == RQ_RValue,
4120 TQ & Qualifiers::Const,
4121 TQ & Qualifiers::Volatile);
4122 }
4123
Richard Smith6c4c36c2012-03-30 20:53:28 +00004124 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004125
Richard Smith6c4c36c2012-03-30 20:53:28 +00004126 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004127 bool shouldDeleteForField(FieldDecl *FD);
4128 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004129
4130 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4131 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4132 Sema::SpecialMemberOverloadResult *SMOR,
4133 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004134
4135 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004136};
4137}
4138
John McCall12d8d802012-04-09 20:53:23 +00004139/// Is the given special member inaccessible when used on the given
4140/// sub-object.
4141bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4142 CXXMethodDecl *target) {
4143 /// If we're operating on a base class, the object type is the
4144 /// type of this special member.
4145 QualType objectTy;
4146 AccessSpecifier access = target->getAccess();;
4147 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4148 objectTy = S.Context.getTypeDeclType(MD->getParent());
4149 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4150
4151 // If we're operating on a field, the object type is the type of the field.
4152 } else {
4153 objectTy = S.Context.getTypeDeclType(target->getParent());
4154 }
4155
4156 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4157}
4158
Richard Smith6c4c36c2012-03-30 20:53:28 +00004159/// Check whether we should delete a special member due to the implicit
4160/// definition containing a call to a special member of a subobject.
4161bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4162 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4163 bool IsDtorCallInCtor) {
4164 CXXMethodDecl *Decl = SMOR->getMethod();
4165 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4166
4167 int DiagKind = -1;
4168
4169 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4170 DiagKind = !Decl ? 0 : 1;
4171 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4172 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004173 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004174 DiagKind = 3;
4175 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4176 !Decl->isTrivial()) {
4177 // A member of a union must have a trivial corresponding special member.
4178 // As a weird special case, a destructor call from a union's constructor
4179 // must be accessible and non-deleted, but need not be trivial. Such a
4180 // destructor is never actually called, but is semantically checked as
4181 // if it were.
4182 DiagKind = 4;
4183 }
4184
4185 if (DiagKind == -1)
4186 return false;
4187
4188 if (Diagnose) {
4189 if (Field) {
4190 S.Diag(Field->getLocation(),
4191 diag::note_deleted_special_member_class_subobject)
4192 << CSM << MD->getParent() << /*IsField*/true
4193 << Field << DiagKind << IsDtorCallInCtor;
4194 } else {
4195 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4196 S.Diag(Base->getLocStart(),
4197 diag::note_deleted_special_member_class_subobject)
4198 << CSM << MD->getParent() << /*IsField*/false
4199 << Base->getType() << DiagKind << IsDtorCallInCtor;
4200 }
4201
4202 if (DiagKind == 1)
4203 S.NoteDeletedFunction(Decl);
4204 // FIXME: Explain inaccessibility if DiagKind == 3.
4205 }
4206
4207 return true;
4208}
4209
Richard Smith9a561d52012-02-26 09:11:52 +00004210/// Check whether we should delete a special member function due to having a
4211/// direct or virtual base class or static data member of class type M.
4212bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith6c4c36c2012-03-30 20:53:28 +00004213 CXXRecordDecl *Class, Subobject Subobj) {
4214 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004215
4216 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004217 // -- any direct or virtual base class, or non-static data member with no
4218 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004219 // either M has no default constructor or overload resolution as applied
4220 // to M's default constructor results in an ambiguity or in a function
4221 // that is deleted or inaccessible
4222 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4223 // -- a direct or virtual base class B that cannot be copied/moved because
4224 // overload resolution, as applied to B's corresponding special member,
4225 // results in an ambiguity or a function that is deleted or inaccessible
4226 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004227 // C++11 [class.dtor]p5:
4228 // -- any direct or virtual base class [...] has a type with a destructor
4229 // that is deleted or inaccessible
4230 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004231 Field && Field->hasInClassInitializer()) &&
4232 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4233 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004234
Richard Smith6c4c36c2012-03-30 20:53:28 +00004235 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4236 // -- any direct or virtual base class or non-static data member has a
4237 // type with a destructor that is deleted or inaccessible
4238 if (IsConstructor) {
4239 Sema::SpecialMemberOverloadResult *SMOR =
4240 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4241 false, false, false, false, false);
4242 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4243 return true;
4244 }
4245
Richard Smith9a561d52012-02-26 09:11:52 +00004246 return false;
4247}
4248
4249/// Check whether we should delete a special member function due to the class
4250/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004251bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004252 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4253 return shouldDeleteForClassSubobject(BaseClass, Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004254}
4255
4256/// Check whether we should delete a special member function due to the class
4257/// having a particular non-static data member.
4258bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4259 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4260 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4261
4262 if (CSM == Sema::CXXDefaultConstructor) {
4263 // For a default constructor, all references must be initialized in-class
4264 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004265 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4266 if (Diagnose)
4267 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4268 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004269 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004270 }
Richard Smith79363f52012-02-27 06:07:25 +00004271 // C++11 [class.ctor]p5: any non-variant non-static data member of
4272 // const-qualified type (or array thereof) with no
4273 // brace-or-equal-initializer does not have a user-provided default
4274 // constructor.
4275 if (!inUnion() && FieldType.isConstQualified() &&
4276 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004277 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4278 if (Diagnose)
4279 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004280 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004281 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004282 }
4283
4284 if (inUnion() && !FieldType.isConstQualified())
4285 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004286 } else if (CSM == Sema::CXXCopyConstructor) {
4287 // For a copy constructor, data members must not be of rvalue reference
4288 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004289 if (FieldType->isRValueReferenceType()) {
4290 if (Diagnose)
4291 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4292 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004293 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004294 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004295 } else if (IsAssignment) {
4296 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004297 if (FieldType->isReferenceType()) {
4298 if (Diagnose)
4299 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4300 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004301 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004302 }
4303 if (!FieldRecord && FieldType.isConstQualified()) {
4304 // C++11 [class.copy]p23:
4305 // -- a non-static data member of const non-class type (or array thereof)
4306 if (Diagnose)
4307 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004308 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004309 return true;
4310 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004311 }
4312
4313 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004314 // Some additional restrictions exist on the variant members.
4315 if (!inUnion() && FieldRecord->isUnion() &&
4316 FieldRecord->isAnonymousStructOrUnion()) {
4317 bool AllVariantFieldsAreConst = true;
4318
Richard Smithdf8dc862012-03-29 19:00:10 +00004319 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004320 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4321 UE = FieldRecord->field_end();
4322 UI != UE; ++UI) {
4323 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004324
4325 if (!UnionFieldType.isConstQualified())
4326 AllVariantFieldsAreConst = false;
4327
Richard Smith9a561d52012-02-26 09:11:52 +00004328 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4329 if (UnionFieldRecord &&
David Blaikie581deb32012-06-06 20:45:41 +00004330 shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
Richard Smith9a561d52012-02-26 09:11:52 +00004331 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004332 }
4333
4334 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004335 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004336 FieldRecord->field_begin() != FieldRecord->field_end()) {
4337 if (Diagnose)
4338 S.Diag(FieldRecord->getLocation(),
4339 diag::note_deleted_default_ctor_all_const)
4340 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004341 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004342 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004343
Richard Smithdf8dc862012-03-29 19:00:10 +00004344 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004345 // This is technically non-conformant, but sanity demands it.
4346 return false;
4347 }
4348
Richard Smithdf8dc862012-03-29 19:00:10 +00004349 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4350 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004351 }
4352
4353 return false;
4354}
4355
4356/// C++11 [class.ctor] p5:
4357/// A defaulted default constructor for a class X is defined as deleted if
4358/// X is a union and all of its variant members are of const-qualified type.
4359bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004360 // This is a silly definition, because it gives an empty union a deleted
4361 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004362 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4363 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4364 if (Diagnose)
4365 S.Diag(MD->getParent()->getLocation(),
4366 diag::note_deleted_default_ctor_all_const)
4367 << MD->getParent() << /*not anonymous union*/0;
4368 return true;
4369 }
4370 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004371}
4372
4373/// Determine whether a defaulted special member function should be defined as
4374/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4375/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004376bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4377 bool Diagnose) {
Sean Hunte16da072011-10-10 06:18:57 +00004378 assert(!MD->isInvalidDecl());
4379 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004380 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004381 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004382 return false;
4383
Richard Smith7d5088a2012-02-18 02:02:13 +00004384 // C++11 [expr.lambda.prim]p19:
4385 // The closure type associated with a lambda-expression has a
4386 // deleted (8.4.3) default constructor and a deleted copy
4387 // assignment operator.
4388 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004389 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4390 if (Diagnose)
4391 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004392 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004393 }
4394
Richard Smith5bdaac52012-04-02 20:59:25 +00004395 // For an anonymous struct or union, the copy and assignment special members
4396 // will never be used, so skip the check. For an anonymous union declared at
4397 // namespace scope, the constructor and destructor are used.
4398 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4399 RD->isAnonymousStructOrUnion())
4400 return false;
4401
Richard Smith6c4c36c2012-03-30 20:53:28 +00004402 // C++11 [class.copy]p7, p18:
4403 // If the class definition declares a move constructor or move assignment
4404 // operator, an implicitly declared copy constructor or copy assignment
4405 // operator is defined as deleted.
4406 if (MD->isImplicit() &&
4407 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4408 CXXMethodDecl *UserDeclaredMove = 0;
4409
4410 // In Microsoft mode, a user-declared move only causes the deletion of the
4411 // corresponding copy operation, not both copy operations.
4412 if (RD->hasUserDeclaredMoveConstructor() &&
4413 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4414 if (!Diagnose) return true;
4415 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004416 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004417 } else if (RD->hasUserDeclaredMoveAssignment() &&
4418 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4419 if (!Diagnose) return true;
4420 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004421 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004422 }
4423
4424 if (UserDeclaredMove) {
4425 Diag(UserDeclaredMove->getLocation(),
4426 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004427 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004428 << UserDeclaredMove->isMoveAssignmentOperator();
4429 return true;
4430 }
4431 }
Sean Hunte16da072011-10-10 06:18:57 +00004432
Richard Smith5bdaac52012-04-02 20:59:25 +00004433 // Do access control from the special member function
4434 ContextRAII MethodContext(*this, MD);
4435
Richard Smith9a561d52012-02-26 09:11:52 +00004436 // C++11 [class.dtor]p5:
4437 // -- for a virtual destructor, lookup of the non-array deallocation function
4438 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004439 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004440 FunctionDecl *OperatorDelete = 0;
4441 DeclarationName Name =
4442 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4443 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004444 OperatorDelete, false)) {
4445 if (Diagnose)
4446 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004447 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004448 }
Richard Smith9a561d52012-02-26 09:11:52 +00004449 }
4450
Richard Smith6c4c36c2012-03-30 20:53:28 +00004451 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004452
Sean Huntcdee3fe2011-05-11 22:34:38 +00004453 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004454 BE = RD->bases_end(); BI != BE; ++BI)
4455 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004456 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004457 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004458
4459 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004460 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004461 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004462 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004463
4464 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004465 FE = RD->field_end(); FI != FE; ++FI)
4466 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004467 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004468 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004469
Richard Smith7d5088a2012-02-18 02:02:13 +00004470 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004471 return true;
4472
4473 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004474}
4475
4476/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004477namespace {
4478 struct FindHiddenVirtualMethodData {
4479 Sema *S;
4480 CXXMethodDecl *Method;
4481 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004482 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004483 };
4484}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004485
4486/// \brief Member lookup function that determines whether a given C++
4487/// method overloads virtual methods in a base class without overriding any,
4488/// to be used with CXXRecordDecl::lookupInBases().
4489static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4490 CXXBasePath &Path,
4491 void *UserData) {
4492 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4493
4494 FindHiddenVirtualMethodData &Data
4495 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4496
4497 DeclarationName Name = Data.Method->getDeclName();
4498 assert(Name.getNameKind() == DeclarationName::Identifier);
4499
4500 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004501 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004502 for (Path.Decls = BaseRecord->lookup(Name);
4503 Path.Decls.first != Path.Decls.second;
4504 ++Path.Decls.first) {
4505 NamedDecl *D = *Path.Decls.first;
4506 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004507 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004508 foundSameNameMethod = true;
4509 // Interested only in hidden virtual methods.
4510 if (!MD->isVirtual())
4511 continue;
4512 // If the method we are checking overrides a method from its base
4513 // don't warn about the other overloaded methods.
4514 if (!Data.S->IsOverload(Data.Method, MD, false))
4515 return true;
4516 // Collect the overload only if its hidden.
4517 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4518 overloadedMethods.push_back(MD);
4519 }
4520 }
4521
4522 if (foundSameNameMethod)
4523 Data.OverloadedMethods.append(overloadedMethods.begin(),
4524 overloadedMethods.end());
4525 return foundSameNameMethod;
4526}
4527
4528/// \brief See if a method overloads virtual methods in a base class without
4529/// overriding any.
4530void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4531 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004532 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004533 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004534 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004535 return;
4536
4537 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4538 /*bool RecordPaths=*/false,
4539 /*bool DetectVirtual=*/false);
4540 FindHiddenVirtualMethodData Data;
4541 Data.Method = MD;
4542 Data.S = this;
4543
4544 // Keep the base methods that were overriden or introduced in the subclass
4545 // by 'using' in a set. A base method not in this set is hidden.
4546 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4547 res.first != res.second; ++res.first) {
4548 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4549 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4550 E = MD->end_overridden_methods();
4551 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004552 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004553 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4554 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004555 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004556 }
4557
4558 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4559 !Data.OverloadedMethods.empty()) {
4560 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4561 << MD << (Data.OverloadedMethods.size() > 1);
4562
4563 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4564 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4565 Diag(overloadedMD->getLocation(),
4566 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4567 }
4568 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004569}
4570
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004571void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004572 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004573 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004574 SourceLocation RBrac,
4575 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004576 if (!TagDecl)
4577 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004578
Douglas Gregor42af25f2009-05-11 19:58:34 +00004579 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004580
David Blaikie77b6de02011-09-22 02:58:26 +00004581 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004582 // strict aliasing violation!
4583 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004584 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004585
Douglas Gregor23c94db2010-07-02 17:43:08 +00004586 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004587 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004588}
4589
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004590/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4591/// special functions, such as the default constructor, copy
4592/// constructor, or destructor, to the given C++ class (C++
4593/// [special]p1). This routine can only be executed just before the
4594/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004595void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004596 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004597 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004598
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004599 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004600 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004601
David Blaikie4e4d0842012-03-11 07:00:24 +00004602 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004603 ++ASTContext::NumImplicitMoveConstructors;
4604
Douglas Gregora376d102010-07-02 21:50:04 +00004605 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4606 ++ASTContext::NumImplicitCopyAssignmentOperators;
4607
4608 // If we have a dynamic class, then the copy assignment operator may be
4609 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4610 // it shows up in the right place in the vtable and that we diagnose
4611 // problems with the implicit exception specification.
4612 if (ClassDecl->isDynamicClass())
4613 DeclareImplicitCopyAssignment(ClassDecl);
4614 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004615
Richard Smith1c931be2012-04-02 18:40:40 +00004616 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004617 ++ASTContext::NumImplicitMoveAssignmentOperators;
4618
4619 // Likewise for the move assignment operator.
4620 if (ClassDecl->isDynamicClass())
4621 DeclareImplicitMoveAssignment(ClassDecl);
4622 }
4623
Douglas Gregor4923aa22010-07-02 20:37:36 +00004624 if (!ClassDecl->hasUserDeclaredDestructor()) {
4625 ++ASTContext::NumImplicitDestructors;
4626
4627 // If we have a dynamic class, then the destructor may be virtual, so we
4628 // have to declare the destructor immediately. This ensures that, e.g., it
4629 // shows up in the right place in the vtable and that we diagnose problems
4630 // with the implicit exception specification.
4631 if (ClassDecl->isDynamicClass())
4632 DeclareImplicitDestructor(ClassDecl);
4633 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004634}
4635
Francois Pichet8387e2a2011-04-22 22:18:13 +00004636void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4637 if (!D)
4638 return;
4639
4640 int NumParamList = D->getNumTemplateParameterLists();
4641 for (int i = 0; i < NumParamList; i++) {
4642 TemplateParameterList* Params = D->getTemplateParameterList(i);
4643 for (TemplateParameterList::iterator Param = Params->begin(),
4644 ParamEnd = Params->end();
4645 Param != ParamEnd; ++Param) {
4646 NamedDecl *Named = cast<NamedDecl>(*Param);
4647 if (Named->getDeclName()) {
4648 S->AddDecl(Named);
4649 IdResolver.AddDecl(Named);
4650 }
4651 }
4652 }
4653}
4654
John McCalld226f652010-08-21 09:40:31 +00004655void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004656 if (!D)
4657 return;
4658
4659 TemplateParameterList *Params = 0;
4660 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4661 Params = Template->getTemplateParameters();
4662 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4663 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4664 Params = PartialSpec->getTemplateParameters();
4665 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004666 return;
4667
Douglas Gregor6569d682009-05-27 23:11:45 +00004668 for (TemplateParameterList::iterator Param = Params->begin(),
4669 ParamEnd = Params->end();
4670 Param != ParamEnd; ++Param) {
4671 NamedDecl *Named = cast<NamedDecl>(*Param);
4672 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004673 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004674 IdResolver.AddDecl(Named);
4675 }
4676 }
4677}
4678
John McCalld226f652010-08-21 09:40:31 +00004679void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004680 if (!RecordD) return;
4681 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004682 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004683 PushDeclContext(S, Record);
4684}
4685
John McCalld226f652010-08-21 09:40:31 +00004686void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004687 if (!RecordD) return;
4688 PopDeclContext();
4689}
4690
Douglas Gregor72b505b2008-12-16 21:30:33 +00004691/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4692/// parsing a top-level (non-nested) C++ class, and we are now
4693/// parsing those parts of the given Method declaration that could
4694/// not be parsed earlier (C++ [class.mem]p2), such as default
4695/// arguments. This action should enter the scope of the given
4696/// Method declaration as if we had just parsed the qualified method
4697/// name. However, it should not bring the parameters into scope;
4698/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004699void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004700}
4701
4702/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4703/// C++ method declaration. We're (re-)introducing the given
4704/// function parameter into scope for use in parsing later parts of
4705/// the method declaration. For example, we could see an
4706/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004707void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004708 if (!ParamD)
4709 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004710
John McCalld226f652010-08-21 09:40:31 +00004711 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004712
4713 // If this parameter has an unparsed default argument, clear it out
4714 // to make way for the parsed default argument.
4715 if (Param->hasUnparsedDefaultArg())
4716 Param->setDefaultArg(0);
4717
John McCalld226f652010-08-21 09:40:31 +00004718 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004719 if (Param->getDeclName())
4720 IdResolver.AddDecl(Param);
4721}
4722
4723/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4724/// processing the delayed method declaration for Method. The method
4725/// declaration is now considered finished. There may be a separate
4726/// ActOnStartOfFunctionDef action later (not necessarily
4727/// immediately!) for this method, if it was also defined inside the
4728/// class body.
John McCalld226f652010-08-21 09:40:31 +00004729void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004730 if (!MethodD)
4731 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004733 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004734
John McCalld226f652010-08-21 09:40:31 +00004735 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004736
4737 // Now that we have our default arguments, check the constructor
4738 // again. It could produce additional diagnostics or affect whether
4739 // the class has implicitly-declared destructors, among other
4740 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4742 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004743
4744 // Check the default arguments, which we may have added.
4745 if (!Method->isInvalidDecl())
4746 CheckCXXDefaultArguments(Method);
4747}
4748
Douglas Gregor42a552f2008-11-05 20:51:48 +00004749/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004750/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004751/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004752/// emit diagnostics and set the invalid bit to true. In any case, the type
4753/// will be updated to reflect a well-formed type for the constructor and
4754/// returned.
4755QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004756 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004757 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004758
4759 // C++ [class.ctor]p3:
4760 // A constructor shall not be virtual (10.3) or static (9.4). A
4761 // constructor can be invoked for a const, volatile or const
4762 // volatile object. A constructor shall not be declared const,
4763 // volatile, or const volatile (9.3.2).
4764 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004765 if (!D.isInvalidType())
4766 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4767 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4768 << SourceRange(D.getIdentifierLoc());
4769 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004770 }
John McCalld931b082010-08-26 03:08:43 +00004771 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004772 if (!D.isInvalidType())
4773 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4774 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4775 << SourceRange(D.getIdentifierLoc());
4776 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004777 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004778 }
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004780 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004781 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004782 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4784 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004785 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004786 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4787 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004788 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004789 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4790 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004791 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004792 }
Mike Stump1eb44332009-09-09 15:08:12 +00004793
Douglas Gregorc938c162011-01-26 05:01:58 +00004794 // C++0x [class.ctor]p4:
4795 // A constructor shall not be declared with a ref-qualifier.
4796 if (FTI.hasRefQualifier()) {
4797 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4798 << FTI.RefQualifierIsLValueRef
4799 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4800 D.setInvalidType();
4801 }
4802
Douglas Gregor42a552f2008-11-05 20:51:48 +00004803 // Rebuild the function type "R" without any type qualifiers (in
4804 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004805 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004806 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004807 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4808 return R;
4809
4810 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4811 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004812 EPI.RefQualifier = RQ_None;
4813
Chris Lattner65401802009-04-25 08:28:21 +00004814 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004815 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004816}
4817
Douglas Gregor72b505b2008-12-16 21:30:33 +00004818/// CheckConstructor - Checks a fully-formed constructor for
4819/// well-formedness, issuing any diagnostics required. Returns true if
4820/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004821void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004822 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004823 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4824 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004825 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004826
4827 // C++ [class.copy]p3:
4828 // A declaration of a constructor for a class X is ill-formed if
4829 // its first parameter is of type (optionally cv-qualified) X and
4830 // either there are no other parameters or else all other
4831 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004832 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004833 ((Constructor->getNumParams() == 1) ||
4834 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004835 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4836 Constructor->getTemplateSpecializationKind()
4837 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004838 QualType ParamType = Constructor->getParamDecl(0)->getType();
4839 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4840 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004841 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004842 const char *ConstRef
4843 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4844 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004845 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004846 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004847
4848 // FIXME: Rather that making the constructor invalid, we should endeavor
4849 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004850 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004851 }
4852 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004853}
4854
John McCall15442822010-08-04 01:04:25 +00004855/// CheckDestructor - Checks a fully-formed destructor definition for
4856/// well-formedness, issuing any diagnostics required. Returns true
4857/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004858bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004859 CXXRecordDecl *RD = Destructor->getParent();
4860
4861 if (Destructor->isVirtual()) {
4862 SourceLocation Loc;
4863
4864 if (!Destructor->isImplicit())
4865 Loc = Destructor->getLocation();
4866 else
4867 Loc = RD->getLocation();
4868
4869 // If we have a virtual destructor, look up the deallocation function
4870 FunctionDecl *OperatorDelete = 0;
4871 DeclarationName Name =
4872 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004873 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004874 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004875
Eli Friedman5f2987c2012-02-02 03:46:19 +00004876 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004877
4878 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004879 }
Anders Carlsson37909802009-11-30 21:24:50 +00004880
4881 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004882}
4883
Mike Stump1eb44332009-09-09 15:08:12 +00004884static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004885FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4886 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4887 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004888 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004889}
4890
Douglas Gregor42a552f2008-11-05 20:51:48 +00004891/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4892/// the well-formednes of the destructor declarator @p D with type @p
4893/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004894/// emit diagnostics and set the declarator to invalid. Even if this happens,
4895/// will be updated to reflect a well-formed type for the destructor and
4896/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004897QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004898 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004899 // C++ [class.dtor]p1:
4900 // [...] A typedef-name that names a class is a class-name
4901 // (7.1.3); however, a typedef-name that names a class shall not
4902 // be used as the identifier in the declarator for a destructor
4903 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004904 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004905 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004906 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004907 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004908 else if (const TemplateSpecializationType *TST =
4909 DeclaratorType->getAs<TemplateSpecializationType>())
4910 if (TST->isTypeAlias())
4911 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4912 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004913
4914 // C++ [class.dtor]p2:
4915 // A destructor is used to destroy objects of its class type. A
4916 // destructor takes no parameters, and no return type can be
4917 // specified for it (not even void). The address of a destructor
4918 // shall not be taken. A destructor shall not be static. A
4919 // destructor can be invoked for a const, volatile or const
4920 // volatile object. A destructor shall not be declared const,
4921 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004922 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004923 if (!D.isInvalidType())
4924 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4925 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004926 << SourceRange(D.getIdentifierLoc())
4927 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4928
John McCalld931b082010-08-26 03:08:43 +00004929 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004930 }
Chris Lattner65401802009-04-25 08:28:21 +00004931 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004932 // Destructors don't have return types, but the parser will
4933 // happily parse something like:
4934 //
4935 // class X {
4936 // float ~X();
4937 // };
4938 //
4939 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004940 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4941 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4942 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004943 }
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004946 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004947 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004948 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4949 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004950 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004951 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4952 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004953 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004954 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4955 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004956 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004957 }
4958
Douglas Gregorc938c162011-01-26 05:01:58 +00004959 // C++0x [class.dtor]p2:
4960 // A destructor shall not be declared with a ref-qualifier.
4961 if (FTI.hasRefQualifier()) {
4962 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4963 << FTI.RefQualifierIsLValueRef
4964 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4965 D.setInvalidType();
4966 }
4967
Douglas Gregor42a552f2008-11-05 20:51:48 +00004968 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004969 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004970 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4971
4972 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004973 FTI.freeArgs();
4974 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004975 }
4976
Mike Stump1eb44332009-09-09 15:08:12 +00004977 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004978 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004979 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004980 D.setInvalidType();
4981 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004982
4983 // Rebuild the function type "R" without any type qualifiers or
4984 // parameters (in case any of the errors above fired) and with
4985 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004986 // types.
John McCalle23cf432010-12-14 08:05:40 +00004987 if (!D.isInvalidType())
4988 return R;
4989
Douglas Gregord92ec472010-07-01 05:10:53 +00004990 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004991 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4992 EPI.Variadic = false;
4993 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004994 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004995 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004996}
4997
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004998/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4999/// well-formednes of the conversion function declarator @p D with
5000/// type @p R. If there are any errors in the declarator, this routine
5001/// will emit diagnostics and return true. Otherwise, it will return
5002/// false. Either way, the type @p R will be updated to reflect a
5003/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005004void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005005 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005006 // C++ [class.conv.fct]p1:
5007 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005008 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005009 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005010 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005011 if (!D.isInvalidType())
5012 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5013 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5014 << SourceRange(D.getIdentifierLoc());
5015 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005016 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005017 }
John McCalla3f81372010-04-13 00:04:31 +00005018
5019 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5020
Chris Lattner6e475012009-04-25 08:35:12 +00005021 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005022 // Conversion functions don't have return types, but the parser will
5023 // happily parse something like:
5024 //
5025 // class X {
5026 // float operator bool();
5027 // };
5028 //
5029 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005030 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5031 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5032 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005033 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005034 }
5035
John McCalla3f81372010-04-13 00:04:31 +00005036 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5037
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005038 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005039 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005040 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5041
5042 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005043 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005044 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005045 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005046 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005047 D.setInvalidType();
5048 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005049
John McCalla3f81372010-04-13 00:04:31 +00005050 // Diagnose "&operator bool()" and other such nonsense. This
5051 // is actually a gcc extension which we don't support.
5052 if (Proto->getResultType() != ConvType) {
5053 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5054 << Proto->getResultType();
5055 D.setInvalidType();
5056 ConvType = Proto->getResultType();
5057 }
5058
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005059 // C++ [class.conv.fct]p4:
5060 // The conversion-type-id shall not represent a function type nor
5061 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005062 if (ConvType->isArrayType()) {
5063 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5064 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005065 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005066 } else if (ConvType->isFunctionType()) {
5067 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5068 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005069 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005070 }
5071
5072 // Rebuild the function type "R" without any parameters (in case any
5073 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005074 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005075 if (D.isInvalidType())
5076 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005077
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005078 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005079 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005080 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005081 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005082 diag::warn_cxx98_compat_explicit_conversion_functions :
5083 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005084 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005085}
5086
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005087/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5088/// the declaration of the given C++ conversion function. This routine
5089/// is responsible for recording the conversion function in the C++
5090/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005091Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005092 assert(Conversion && "Expected to receive a conversion function declaration");
5093
Douglas Gregor9d350972008-12-12 08:25:50 +00005094 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005095
5096 // Make sure we aren't redeclaring the conversion function.
5097 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005098
5099 // C++ [class.conv.fct]p1:
5100 // [...] A conversion function is never used to convert a
5101 // (possibly cv-qualified) object to the (possibly cv-qualified)
5102 // same object type (or a reference to it), to a (possibly
5103 // cv-qualified) base class of that type (or a reference to it),
5104 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005105 // FIXME: Suppress this warning if the conversion function ends up being a
5106 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005107 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005108 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005109 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005110 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005111 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5112 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005113 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005114 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005115 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5116 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005117 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005118 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005119 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005120 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005121 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005122 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005123 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005124 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005125 }
5126
Douglas Gregore80622f2010-09-29 04:25:11 +00005127 if (FunctionTemplateDecl *ConversionTemplate
5128 = Conversion->getDescribedFunctionTemplate())
5129 return ConversionTemplate;
5130
John McCalld226f652010-08-21 09:40:31 +00005131 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005132}
5133
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005134//===----------------------------------------------------------------------===//
5135// Namespace Handling
5136//===----------------------------------------------------------------------===//
5137
John McCallea318642010-08-26 09:15:37 +00005138
5139
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005140/// ActOnStartNamespaceDef - This is called at the start of a namespace
5141/// definition.
John McCalld226f652010-08-21 09:40:31 +00005142Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005143 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005144 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005145 SourceLocation IdentLoc,
5146 IdentifierInfo *II,
5147 SourceLocation LBrace,
5148 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005149 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5150 // For anonymous namespace, take the location of the left brace.
5151 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005152 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005153 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005154 bool IsStd = false;
5155 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005156 Scope *DeclRegionScope = NamespcScope->getParent();
5157
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005158 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005159 if (II) {
5160 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005161 // The identifier in an original-namespace-definition shall not
5162 // have been previously defined in the declarative region in
5163 // which the original-namespace-definition appears. The
5164 // identifier in an original-namespace-definition is the name of
5165 // the namespace. Subsequently in that declarative region, it is
5166 // treated as an original-namespace-name.
5167 //
5168 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005169 // look through using directives, just look for any ordinary names.
5170
5171 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005172 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5173 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005174 NamedDecl *PrevDecl = 0;
5175 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005176 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005177 R.first != R.second; ++R.first) {
5178 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5179 PrevDecl = *R.first;
5180 break;
5181 }
5182 }
5183
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005184 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5185
5186 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005187 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005188 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005189 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005190 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005191 // The user probably just forgot the 'inline', so suggest that it
5192 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005193 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005194 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5195 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005196 Diag(Loc, diag::err_inline_namespace_mismatch)
5197 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005198 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005199 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5200
5201 IsInline = PrevNS->isInline();
5202 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005203 } else if (PrevDecl) {
5204 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005205 Diag(Loc, diag::err_redefinition_different_kind)
5206 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005207 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005208 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005209 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005210 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005211 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005212 // This is the first "real" definition of the namespace "std", so update
5213 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005214 PrevNS = getStdNamespace();
5215 IsStd = true;
5216 AddToKnown = !IsInline;
5217 } else {
5218 // We've seen this namespace for the first time.
5219 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005220 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005221 } else {
John McCall9aeed322009-10-01 00:25:31 +00005222 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005223
5224 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005225 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005226 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005227 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005228 } else {
5229 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005230 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005231 }
5232
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005233 if (PrevNS && IsInline != PrevNS->isInline()) {
5234 // inline-ness must match
5235 Diag(Loc, diag::err_inline_namespace_mismatch)
5236 << IsInline;
5237 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005238
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005239 // Recover by ignoring the new namespace's inline status.
5240 IsInline = PrevNS->isInline();
5241 }
5242 }
5243
5244 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5245 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005246 if (IsInvalid)
5247 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005248
5249 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005250
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005251 // FIXME: Should we be merging attributes?
5252 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005253 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005254
5255 if (IsStd)
5256 StdNamespace = Namespc;
5257 if (AddToKnown)
5258 KnownNamespaces[Namespc] = false;
5259
5260 if (II) {
5261 PushOnScopeChains(Namespc, DeclRegionScope);
5262 } else {
5263 // Link the anonymous namespace into its parent.
5264 DeclContext *Parent = CurContext->getRedeclContext();
5265 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5266 TU->setAnonymousNamespace(Namespc);
5267 } else {
5268 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005269 }
John McCall9aeed322009-10-01 00:25:31 +00005270
Douglas Gregora4181472010-03-24 00:46:35 +00005271 CurContext->addDecl(Namespc);
5272
John McCall9aeed322009-10-01 00:25:31 +00005273 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5274 // behaves as if it were replaced by
5275 // namespace unique { /* empty body */ }
5276 // using namespace unique;
5277 // namespace unique { namespace-body }
5278 // where all occurrences of 'unique' in a translation unit are
5279 // replaced by the same identifier and this identifier differs
5280 // from all other identifiers in the entire program.
5281
5282 // We just create the namespace with an empty name and then add an
5283 // implicit using declaration, just like the standard suggests.
5284 //
5285 // CodeGen enforces the "universally unique" aspect by giving all
5286 // declarations semantically contained within an anonymous
5287 // namespace internal linkage.
5288
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005289 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005290 UsingDirectiveDecl* UD
5291 = UsingDirectiveDecl::Create(Context, CurContext,
5292 /* 'using' */ LBrace,
5293 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005294 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005295 /* identifier */ SourceLocation(),
5296 Namespc,
5297 /* Ancestor */ CurContext);
5298 UD->setImplicit();
5299 CurContext->addDecl(UD);
5300 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005301 }
5302
5303 // Although we could have an invalid decl (i.e. the namespace name is a
5304 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005305 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5306 // for the namespace has the declarations that showed up in that particular
5307 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005308 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005309 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005310}
5311
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005312/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5313/// is a namespace alias, returns the namespace it points to.
5314static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5315 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5316 return AD->getNamespace();
5317 return dyn_cast_or_null<NamespaceDecl>(D);
5318}
5319
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005320/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5321/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005322void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005323 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5324 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005325 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005326 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005327 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005328 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005329}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005330
John McCall384aff82010-08-25 07:42:41 +00005331CXXRecordDecl *Sema::getStdBadAlloc() const {
5332 return cast_or_null<CXXRecordDecl>(
5333 StdBadAlloc.get(Context.getExternalSource()));
5334}
5335
5336NamespaceDecl *Sema::getStdNamespace() const {
5337 return cast_or_null<NamespaceDecl>(
5338 StdNamespace.get(Context.getExternalSource()));
5339}
5340
Douglas Gregor66992202010-06-29 17:53:46 +00005341/// \brief Retrieve the special "std" namespace, which may require us to
5342/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005343NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005344 if (!StdNamespace) {
5345 // The "std" namespace has not yet been defined, so build one implicitly.
5346 StdNamespace = NamespaceDecl::Create(Context,
5347 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005348 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005349 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005350 &PP.getIdentifierTable().get("std"),
5351 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005352 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005353 }
5354
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005355 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005356}
5357
Sebastian Redl395e04d2012-01-17 22:49:33 +00005358bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005359 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005360 "Looking for std::initializer_list outside of C++.");
5361
5362 // We're looking for implicit instantiations of
5363 // template <typename E> class std::initializer_list.
5364
5365 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5366 return false;
5367
Sebastian Redl84760e32012-01-17 22:49:58 +00005368 ClassTemplateDecl *Template = 0;
5369 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005370
Sebastian Redl84760e32012-01-17 22:49:58 +00005371 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005372
Sebastian Redl84760e32012-01-17 22:49:58 +00005373 ClassTemplateSpecializationDecl *Specialization =
5374 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5375 if (!Specialization)
5376 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005377
Sebastian Redl84760e32012-01-17 22:49:58 +00005378 Template = Specialization->getSpecializedTemplate();
5379 Arguments = Specialization->getTemplateArgs().data();
5380 } else if (const TemplateSpecializationType *TST =
5381 Ty->getAs<TemplateSpecializationType>()) {
5382 Template = dyn_cast_or_null<ClassTemplateDecl>(
5383 TST->getTemplateName().getAsTemplateDecl());
5384 Arguments = TST->getArgs();
5385 }
5386 if (!Template)
5387 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005388
5389 if (!StdInitializerList) {
5390 // Haven't recognized std::initializer_list yet, maybe this is it.
5391 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5392 if (TemplateClass->getIdentifier() !=
5393 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005394 !getStdNamespace()->InEnclosingNamespaceSetOf(
5395 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005396 return false;
5397 // This is a template called std::initializer_list, but is it the right
5398 // template?
5399 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005400 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005401 return false;
5402 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5403 return false;
5404
5405 // It's the right template.
5406 StdInitializerList = Template;
5407 }
5408
5409 if (Template != StdInitializerList)
5410 return false;
5411
5412 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005413 if (Element)
5414 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005415 return true;
5416}
5417
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005418static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5419 NamespaceDecl *Std = S.getStdNamespace();
5420 if (!Std) {
5421 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5422 return 0;
5423 }
5424
5425 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5426 Loc, Sema::LookupOrdinaryName);
5427 if (!S.LookupQualifiedName(Result, Std)) {
5428 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5429 return 0;
5430 }
5431 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5432 if (!Template) {
5433 Result.suppressDiagnostics();
5434 // We found something weird. Complain about the first thing we found.
5435 NamedDecl *Found = *Result.begin();
5436 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5437 return 0;
5438 }
5439
5440 // We found some template called std::initializer_list. Now verify that it's
5441 // correct.
5442 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005443 if (Params->getMinRequiredArguments() != 1 ||
5444 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005445 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5446 return 0;
5447 }
5448
5449 return Template;
5450}
5451
5452QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5453 if (!StdInitializerList) {
5454 StdInitializerList = LookupStdInitializerList(*this, Loc);
5455 if (!StdInitializerList)
5456 return QualType();
5457 }
5458
5459 TemplateArgumentListInfo Args(Loc, Loc);
5460 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5461 Context.getTrivialTypeSourceInfo(Element,
5462 Loc)));
5463 return Context.getCanonicalType(
5464 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5465}
5466
Sebastian Redl98d36062012-01-17 22:50:14 +00005467bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5468 // C++ [dcl.init.list]p2:
5469 // A constructor is an initializer-list constructor if its first parameter
5470 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5471 // std::initializer_list<E> for some type E, and either there are no other
5472 // parameters or else all other parameters have default arguments.
5473 if (Ctor->getNumParams() < 1 ||
5474 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5475 return false;
5476
5477 QualType ArgType = Ctor->getParamDecl(0)->getType();
5478 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5479 ArgType = RT->getPointeeType().getUnqualifiedType();
5480
5481 return isStdInitializerList(ArgType, 0);
5482}
5483
Douglas Gregor9172aa62011-03-26 22:25:30 +00005484/// \brief Determine whether a using statement is in a context where it will be
5485/// apply in all contexts.
5486static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5487 switch (CurContext->getDeclKind()) {
5488 case Decl::TranslationUnit:
5489 return true;
5490 case Decl::LinkageSpec:
5491 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5492 default:
5493 return false;
5494 }
5495}
5496
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005497namespace {
5498
5499// Callback to only accept typo corrections that are namespaces.
5500class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5501 public:
5502 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5503 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5504 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5505 }
5506 return false;
5507 }
5508};
5509
5510}
5511
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005512static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5513 CXXScopeSpec &SS,
5514 SourceLocation IdentLoc,
5515 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005516 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005517 R.clear();
5518 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005519 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005520 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005521 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5522 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005523 if (DeclContext *DC = S.computeDeclContext(SS, false))
5524 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5525 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5526 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5527 else
5528 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5529 << Ident << CorrectedQuotedStr
5530 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005531
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005532 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5533 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005534
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005535 R.addDecl(Corrected.getCorrectionDecl());
5536 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005537 }
5538 return false;
5539}
5540
John McCalld226f652010-08-21 09:40:31 +00005541Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005542 SourceLocation UsingLoc,
5543 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005544 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005545 SourceLocation IdentLoc,
5546 IdentifierInfo *NamespcName,
5547 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005548 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5549 assert(NamespcName && "Invalid NamespcName.");
5550 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005551
5552 // This can only happen along a recovery path.
5553 while (S->getFlags() & Scope::TemplateParamScope)
5554 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005555 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005556
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005557 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005558 NestedNameSpecifier *Qualifier = 0;
5559 if (SS.isSet())
5560 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5561
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005562 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005563 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5564 LookupParsedName(R, S, &SS);
5565 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005566 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005567
Douglas Gregor66992202010-06-29 17:53:46 +00005568 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005569 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005570 // Allow "using namespace std;" or "using namespace ::std;" even if
5571 // "std" hasn't been defined yet, for GCC compatibility.
5572 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5573 NamespcName->isStr("std")) {
5574 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005575 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005576 R.resolveKind();
5577 }
5578 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005579 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005580 }
5581
John McCallf36e02d2009-10-09 21:13:30 +00005582 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005583 NamedDecl *Named = R.getFoundDecl();
5584 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5585 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005586 // C++ [namespace.udir]p1:
5587 // A using-directive specifies that the names in the nominated
5588 // namespace can be used in the scope in which the
5589 // using-directive appears after the using-directive. During
5590 // unqualified name lookup (3.4.1), the names appear as if they
5591 // were declared in the nearest enclosing namespace which
5592 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005593 // namespace. [Note: in this context, "contains" means "contains
5594 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005595
5596 // Find enclosing context containing both using-directive and
5597 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005598 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005599 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5600 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5601 CommonAncestor = CommonAncestor->getParent();
5602
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005603 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005604 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005605 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005606
Douglas Gregor9172aa62011-03-26 22:25:30 +00005607 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005608 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005609 Diag(IdentLoc, diag::warn_using_directive_in_header);
5610 }
5611
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005612 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005613 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005614 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005615 }
5616
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005617 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005618 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005619}
5620
5621void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005622 // If the scope has an associated entity and the using directive is at
5623 // namespace or translation unit scope, add the UsingDirectiveDecl into
5624 // its lookup structure so qualified name lookup can find it.
5625 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5626 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005627 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005628 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005629 // Otherwise, it is at block sope. The using-directives will affect lookup
5630 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005631 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005632}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005633
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005634
John McCalld226f652010-08-21 09:40:31 +00005635Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005636 AccessSpecifier AS,
5637 bool HasUsingKeyword,
5638 SourceLocation UsingLoc,
5639 CXXScopeSpec &SS,
5640 UnqualifiedId &Name,
5641 AttributeList *AttrList,
5642 bool IsTypeName,
5643 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005644 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005645
Douglas Gregor12c118a2009-11-04 16:30:06 +00005646 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005647 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005648 case UnqualifiedId::IK_Identifier:
5649 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005650 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005651 case UnqualifiedId::IK_ConversionFunctionId:
5652 break;
5653
5654 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005655 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005656 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005657 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005658 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005659 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5660 // instead once inheriting constructors work.
5661 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005662 diag::err_using_decl_constructor)
5663 << SS.getRange();
5664
David Blaikie4e4d0842012-03-11 07:00:24 +00005665 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005666
John McCalld226f652010-08-21 09:40:31 +00005667 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005668
5669 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005670 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005671 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005672 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005673
5674 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005675 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005676 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005677 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005678 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005679
5680 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5681 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005682 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005683 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005684
John McCall60fa3cf2009-12-11 02:10:03 +00005685 // Warn about using declarations.
5686 // TODO: store that the declaration was written without 'using' and
5687 // talk about access decls instead of using decls in the
5688 // diagnostics.
5689 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005690 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005691
5692 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005693 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005694 }
5695
Douglas Gregor56c04582010-12-16 00:46:58 +00005696 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5697 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5698 return 0;
5699
John McCall9488ea12009-11-17 05:59:44 +00005700 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005701 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005702 /* IsInstantiation */ false,
5703 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005704 if (UD)
5705 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005706
John McCalld226f652010-08-21 09:40:31 +00005707 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005708}
5709
Douglas Gregor09acc982010-07-07 23:08:52 +00005710/// \brief Determine whether a using declaration considers the given
5711/// declarations as "equivalent", e.g., if they are redeclarations of
5712/// the same entity or are both typedefs of the same type.
5713static bool
5714IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5715 bool &SuppressRedeclaration) {
5716 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5717 SuppressRedeclaration = false;
5718 return true;
5719 }
5720
Richard Smith162e1c12011-04-15 14:24:37 +00005721 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5722 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005723 SuppressRedeclaration = true;
5724 return Context.hasSameType(TD1->getUnderlyingType(),
5725 TD2->getUnderlyingType());
5726 }
5727
5728 return false;
5729}
5730
5731
John McCall9f54ad42009-12-10 09:41:52 +00005732/// Determines whether to create a using shadow decl for a particular
5733/// decl, given the set of decls existing prior to this using lookup.
5734bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5735 const LookupResult &Previous) {
5736 // Diagnose finding a decl which is not from a base class of the
5737 // current class. We do this now because there are cases where this
5738 // function will silently decide not to build a shadow decl, which
5739 // will pre-empt further diagnostics.
5740 //
5741 // We don't need to do this in C++0x because we do the check once on
5742 // the qualifier.
5743 //
5744 // FIXME: diagnose the following if we care enough:
5745 // struct A { int foo; };
5746 // struct B : A { using A::foo; };
5747 // template <class T> struct C : A {};
5748 // template <class T> struct D : C<T> { using B::foo; } // <---
5749 // This is invalid (during instantiation) in C++03 because B::foo
5750 // resolves to the using decl in B, which is not a base class of D<T>.
5751 // We can't diagnose it immediately because C<T> is an unknown
5752 // specialization. The UsingShadowDecl in D<T> then points directly
5753 // to A::foo, which will look well-formed when we instantiate.
5754 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005755 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005756 DeclContext *OrigDC = Orig->getDeclContext();
5757
5758 // Handle enums and anonymous structs.
5759 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5760 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5761 while (OrigRec->isAnonymousStructOrUnion())
5762 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5763
5764 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5765 if (OrigDC == CurContext) {
5766 Diag(Using->getLocation(),
5767 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005768 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005769 Diag(Orig->getLocation(), diag::note_using_decl_target);
5770 return true;
5771 }
5772
Douglas Gregordc355712011-02-25 00:36:19 +00005773 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005774 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005775 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005776 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005777 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005778 Diag(Orig->getLocation(), diag::note_using_decl_target);
5779 return true;
5780 }
5781 }
5782
5783 if (Previous.empty()) return false;
5784
5785 NamedDecl *Target = Orig;
5786 if (isa<UsingShadowDecl>(Target))
5787 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5788
John McCalld7533ec2009-12-11 02:33:26 +00005789 // If the target happens to be one of the previous declarations, we
5790 // don't have a conflict.
5791 //
5792 // FIXME: but we might be increasing its access, in which case we
5793 // should redeclare it.
5794 NamedDecl *NonTag = 0, *Tag = 0;
5795 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5796 I != E; ++I) {
5797 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005798 bool Result;
5799 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5800 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005801
5802 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5803 }
5804
John McCall9f54ad42009-12-10 09:41:52 +00005805 if (Target->isFunctionOrFunctionTemplate()) {
5806 FunctionDecl *FD;
5807 if (isa<FunctionTemplateDecl>(Target))
5808 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5809 else
5810 FD = cast<FunctionDecl>(Target);
5811
5812 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005813 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005814 case Ovl_Overload:
5815 return false;
5816
5817 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005818 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005819 break;
5820
5821 // We found a decl with the exact signature.
5822 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005823 // If we're in a record, we want to hide the target, so we
5824 // return true (without a diagnostic) to tell the caller not to
5825 // build a shadow decl.
5826 if (CurContext->isRecord())
5827 return true;
5828
5829 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005830 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005831 break;
5832 }
5833
5834 Diag(Target->getLocation(), diag::note_using_decl_target);
5835 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5836 return true;
5837 }
5838
5839 // Target is not a function.
5840
John McCall9f54ad42009-12-10 09:41:52 +00005841 if (isa<TagDecl>(Target)) {
5842 // No conflict between a tag and a non-tag.
5843 if (!Tag) return false;
5844
John McCall41ce66f2009-12-10 19:51:03 +00005845 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005846 Diag(Target->getLocation(), diag::note_using_decl_target);
5847 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5848 return true;
5849 }
5850
5851 // No conflict between a tag and a non-tag.
5852 if (!NonTag) return false;
5853
John McCall41ce66f2009-12-10 19:51:03 +00005854 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005855 Diag(Target->getLocation(), diag::note_using_decl_target);
5856 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5857 return true;
5858}
5859
John McCall9488ea12009-11-17 05:59:44 +00005860/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005861UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005862 UsingDecl *UD,
5863 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005864
5865 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005866 NamedDecl *Target = Orig;
5867 if (isa<UsingShadowDecl>(Target)) {
5868 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5869 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005870 }
5871
5872 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005873 = UsingShadowDecl::Create(Context, CurContext,
5874 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005875 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005876
5877 Shadow->setAccess(UD->getAccess());
5878 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5879 Shadow->setInvalidDecl();
5880
John McCall9488ea12009-11-17 05:59:44 +00005881 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005882 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005883 else
John McCall604e7f12009-12-08 07:46:18 +00005884 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005885
John McCall604e7f12009-12-08 07:46:18 +00005886
John McCall9f54ad42009-12-10 09:41:52 +00005887 return Shadow;
5888}
John McCall604e7f12009-12-08 07:46:18 +00005889
John McCall9f54ad42009-12-10 09:41:52 +00005890/// Hides a using shadow declaration. This is required by the current
5891/// using-decl implementation when a resolvable using declaration in a
5892/// class is followed by a declaration which would hide or override
5893/// one or more of the using decl's targets; for example:
5894///
5895/// struct Base { void foo(int); };
5896/// struct Derived : Base {
5897/// using Base::foo;
5898/// void foo(int);
5899/// };
5900///
5901/// The governing language is C++03 [namespace.udecl]p12:
5902///
5903/// When a using-declaration brings names from a base class into a
5904/// derived class scope, member functions in the derived class
5905/// override and/or hide member functions with the same name and
5906/// parameter types in a base class (rather than conflicting).
5907///
5908/// There are two ways to implement this:
5909/// (1) optimistically create shadow decls when they're not hidden
5910/// by existing declarations, or
5911/// (2) don't create any shadow decls (or at least don't make them
5912/// visible) until we've fully parsed/instantiated the class.
5913/// The problem with (1) is that we might have to retroactively remove
5914/// a shadow decl, which requires several O(n) operations because the
5915/// decl structures are (very reasonably) not designed for removal.
5916/// (2) avoids this but is very fiddly and phase-dependent.
5917void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005918 if (Shadow->getDeclName().getNameKind() ==
5919 DeclarationName::CXXConversionFunctionName)
5920 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5921
John McCall9f54ad42009-12-10 09:41:52 +00005922 // Remove it from the DeclContext...
5923 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005924
John McCall9f54ad42009-12-10 09:41:52 +00005925 // ...and the scope, if applicable...
5926 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005927 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005928 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005929 }
5930
John McCall9f54ad42009-12-10 09:41:52 +00005931 // ...and the using decl.
5932 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5933
5934 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005935 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005936}
5937
John McCall7ba107a2009-11-18 02:36:19 +00005938/// Builds a using declaration.
5939///
5940/// \param IsInstantiation - Whether this call arises from an
5941/// instantiation of an unresolved using declaration. We treat
5942/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005943NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5944 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005945 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005946 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005947 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005948 bool IsInstantiation,
5949 bool IsTypeName,
5950 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005951 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005952 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005953 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005954
Anders Carlsson550b14b2009-08-28 05:49:21 +00005955 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005956
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005957 if (SS.isEmpty()) {
5958 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005959 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005960 }
Mike Stump1eb44332009-09-09 15:08:12 +00005961
John McCall9f54ad42009-12-10 09:41:52 +00005962 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005963 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005964 ForRedeclaration);
5965 Previous.setHideTags(false);
5966 if (S) {
5967 LookupName(Previous, S);
5968
5969 // It is really dumb that we have to do this.
5970 LookupResult::Filter F = Previous.makeFilter();
5971 while (F.hasNext()) {
5972 NamedDecl *D = F.next();
5973 if (!isDeclInScope(D, CurContext, S))
5974 F.erase();
5975 }
5976 F.done();
5977 } else {
5978 assert(IsInstantiation && "no scope in non-instantiation");
5979 assert(CurContext->isRecord() && "scope not record in instantiation");
5980 LookupQualifiedName(Previous, CurContext);
5981 }
5982
John McCall9f54ad42009-12-10 09:41:52 +00005983 // Check for invalid redeclarations.
5984 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5985 return 0;
5986
5987 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005988 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5989 return 0;
5990
John McCallaf8e6ed2009-11-12 03:15:40 +00005991 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005992 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005993 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005994 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005995 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005996 // FIXME: not all declaration name kinds are legal here
5997 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5998 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005999 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006000 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006001 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006002 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6003 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006004 }
John McCalled976492009-12-04 22:46:56 +00006005 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006006 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6007 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006008 }
John McCalled976492009-12-04 22:46:56 +00006009 D->setAccess(AS);
6010 CurContext->addDecl(D);
6011
6012 if (!LookupContext) return D;
6013 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006014
John McCall77bb1aa2010-05-01 00:40:08 +00006015 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006016 UD->setInvalidDecl();
6017 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006018 }
6019
Richard Smithc5a89a12012-04-02 01:30:27 +00006020 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006021 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006022 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006023 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006024 return UD;
6025 }
6026
6027 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006028
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006029 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006030
John McCall604e7f12009-12-08 07:46:18 +00006031 // Unlike most lookups, we don't always want to hide tag
6032 // declarations: tag names are visible through the using declaration
6033 // even if hidden by ordinary names, *except* in a dependent context
6034 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006035 if (!IsInstantiation)
6036 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006037
John McCallb9abd8722012-04-07 03:04:20 +00006038 // For the purposes of this lookup, we have a base object type
6039 // equal to that of the current context.
6040 if (CurContext->isRecord()) {
6041 R.setBaseObjectType(
6042 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6043 }
6044
John McCalla24dc2e2009-11-17 02:14:36 +00006045 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006046
John McCallf36e02d2009-10-09 21:13:30 +00006047 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006048 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006049 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006050 UD->setInvalidDecl();
6051 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006052 }
6053
John McCalled976492009-12-04 22:46:56 +00006054 if (R.isAmbiguous()) {
6055 UD->setInvalidDecl();
6056 return UD;
6057 }
Mike Stump1eb44332009-09-09 15:08:12 +00006058
John McCall7ba107a2009-11-18 02:36:19 +00006059 if (IsTypeName) {
6060 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006061 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006062 Diag(IdentLoc, diag::err_using_typename_non_type);
6063 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6064 Diag((*I)->getUnderlyingDecl()->getLocation(),
6065 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006066 UD->setInvalidDecl();
6067 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006068 }
6069 } else {
6070 // If we asked for a non-typename and we got a type, error out,
6071 // but only if this is an instantiation of an unresolved using
6072 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006073 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006074 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6075 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006076 UD->setInvalidDecl();
6077 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006078 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006079 }
6080
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006081 // C++0x N2914 [namespace.udecl]p6:
6082 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006083 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006084 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6085 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006086 UD->setInvalidDecl();
6087 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006088 }
Mike Stump1eb44332009-09-09 15:08:12 +00006089
John McCall9f54ad42009-12-10 09:41:52 +00006090 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6091 if (!CheckUsingShadowDecl(UD, *I, Previous))
6092 BuildUsingShadowDecl(S, UD, *I);
6093 }
John McCall9488ea12009-11-17 05:59:44 +00006094
6095 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006096}
6097
Sebastian Redlf677ea32011-02-05 19:23:19 +00006098/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006099bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6100 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006101
Douglas Gregordc355712011-02-25 00:36:19 +00006102 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006103 assert(SourceType &&
6104 "Using decl naming constructor doesn't have type in scope spec.");
6105 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6106
6107 // Check whether the named type is a direct base class.
6108 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6109 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6110 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6111 BaseIt != BaseE; ++BaseIt) {
6112 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6113 if (CanonicalSourceType == BaseType)
6114 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006115 if (BaseIt->getType()->isDependentType())
6116 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006117 }
6118
6119 if (BaseIt == BaseE) {
6120 // Did not find SourceType in the bases.
6121 Diag(UD->getUsingLocation(),
6122 diag::err_using_decl_constructor_not_in_direct_base)
6123 << UD->getNameInfo().getSourceRange()
6124 << QualType(SourceType, 0) << TargetClass;
6125 return true;
6126 }
6127
Richard Smithc5a89a12012-04-02 01:30:27 +00006128 if (!CurContext->isDependentContext())
6129 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006130
6131 return false;
6132}
6133
John McCall9f54ad42009-12-10 09:41:52 +00006134/// Checks that the given using declaration is not an invalid
6135/// redeclaration. Note that this is checking only for the using decl
6136/// itself, not for any ill-formedness among the UsingShadowDecls.
6137bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6138 bool isTypeName,
6139 const CXXScopeSpec &SS,
6140 SourceLocation NameLoc,
6141 const LookupResult &Prev) {
6142 // C++03 [namespace.udecl]p8:
6143 // C++0x [namespace.udecl]p10:
6144 // A using-declaration is a declaration and can therefore be used
6145 // repeatedly where (and only where) multiple declarations are
6146 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006147 //
John McCall8a726212010-11-29 18:01:58 +00006148 // That's in non-member contexts.
6149 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006150 return false;
6151
6152 NestedNameSpecifier *Qual
6153 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6154
6155 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6156 NamedDecl *D = *I;
6157
6158 bool DTypename;
6159 NestedNameSpecifier *DQual;
6160 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6161 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006162 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006163 } else if (UnresolvedUsingValueDecl *UD
6164 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6165 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006166 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006167 } else if (UnresolvedUsingTypenameDecl *UD
6168 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6169 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006170 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006171 } else continue;
6172
6173 // using decls differ if one says 'typename' and the other doesn't.
6174 // FIXME: non-dependent using decls?
6175 if (isTypeName != DTypename) continue;
6176
6177 // using decls differ if they name different scopes (but note that
6178 // template instantiation can cause this check to trigger when it
6179 // didn't before instantiation).
6180 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6181 Context.getCanonicalNestedNameSpecifier(DQual))
6182 continue;
6183
6184 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006185 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006186 return true;
6187 }
6188
6189 return false;
6190}
6191
John McCall604e7f12009-12-08 07:46:18 +00006192
John McCalled976492009-12-04 22:46:56 +00006193/// Checks that the given nested-name qualifier used in a using decl
6194/// in the current context is appropriately related to the current
6195/// scope. If an error is found, diagnoses it and returns true.
6196bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6197 const CXXScopeSpec &SS,
6198 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006199 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006200
John McCall604e7f12009-12-08 07:46:18 +00006201 if (!CurContext->isRecord()) {
6202 // C++03 [namespace.udecl]p3:
6203 // C++0x [namespace.udecl]p8:
6204 // A using-declaration for a class member shall be a member-declaration.
6205
6206 // If we weren't able to compute a valid scope, it must be a
6207 // dependent class scope.
6208 if (!NamedContext || NamedContext->isRecord()) {
6209 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6210 << SS.getRange();
6211 return true;
6212 }
6213
6214 // Otherwise, everything is known to be fine.
6215 return false;
6216 }
6217
6218 // The current scope is a record.
6219
6220 // If the named context is dependent, we can't decide much.
6221 if (!NamedContext) {
6222 // FIXME: in C++0x, we can diagnose if we can prove that the
6223 // nested-name-specifier does not refer to a base class, which is
6224 // still possible in some cases.
6225
6226 // Otherwise we have to conservatively report that things might be
6227 // okay.
6228 return false;
6229 }
6230
6231 if (!NamedContext->isRecord()) {
6232 // Ideally this would point at the last name in the specifier,
6233 // but we don't have that level of source info.
6234 Diag(SS.getRange().getBegin(),
6235 diag::err_using_decl_nested_name_specifier_is_not_class)
6236 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6237 return true;
6238 }
6239
Douglas Gregor6fb07292010-12-21 07:41:49 +00006240 if (!NamedContext->isDependentContext() &&
6241 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6242 return true;
6243
David Blaikie4e4d0842012-03-11 07:00:24 +00006244 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006245 // C++0x [namespace.udecl]p3:
6246 // In a using-declaration used as a member-declaration, the
6247 // nested-name-specifier shall name a base class of the class
6248 // being defined.
6249
6250 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6251 cast<CXXRecordDecl>(NamedContext))) {
6252 if (CurContext == NamedContext) {
6253 Diag(NameLoc,
6254 diag::err_using_decl_nested_name_specifier_is_current_class)
6255 << SS.getRange();
6256 return true;
6257 }
6258
6259 Diag(SS.getRange().getBegin(),
6260 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6261 << (NestedNameSpecifier*) SS.getScopeRep()
6262 << cast<CXXRecordDecl>(CurContext)
6263 << SS.getRange();
6264 return true;
6265 }
6266
6267 return false;
6268 }
6269
6270 // C++03 [namespace.udecl]p4:
6271 // A using-declaration used as a member-declaration shall refer
6272 // to a member of a base class of the class being defined [etc.].
6273
6274 // Salient point: SS doesn't have to name a base class as long as
6275 // lookup only finds members from base classes. Therefore we can
6276 // diagnose here only if we can prove that that can't happen,
6277 // i.e. if the class hierarchies provably don't intersect.
6278
6279 // TODO: it would be nice if "definitely valid" results were cached
6280 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6281 // need to be repeated.
6282
6283 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006284 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006285
6286 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6287 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6288 Data->Bases.insert(Base);
6289 return true;
6290 }
6291
6292 bool hasDependentBases(const CXXRecordDecl *Class) {
6293 return !Class->forallBases(collect, this);
6294 }
6295
6296 /// Returns true if the base is dependent or is one of the
6297 /// accumulated base classes.
6298 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6299 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6300 return !Data->Bases.count(Base);
6301 }
6302
6303 bool mightShareBases(const CXXRecordDecl *Class) {
6304 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6305 }
6306 };
6307
6308 UserData Data;
6309
6310 // Returns false if we find a dependent base.
6311 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6312 return false;
6313
6314 // Returns false if the class has a dependent base or if it or one
6315 // of its bases is present in the base set of the current context.
6316 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6317 return false;
6318
6319 Diag(SS.getRange().getBegin(),
6320 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6321 << (NestedNameSpecifier*) SS.getScopeRep()
6322 << cast<CXXRecordDecl>(CurContext)
6323 << SS.getRange();
6324
6325 return true;
John McCalled976492009-12-04 22:46:56 +00006326}
6327
Richard Smith162e1c12011-04-15 14:24:37 +00006328Decl *Sema::ActOnAliasDeclaration(Scope *S,
6329 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006330 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006331 SourceLocation UsingLoc,
6332 UnqualifiedId &Name,
6333 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006334 // Skip up to the relevant declaration scope.
6335 while (S->getFlags() & Scope::TemplateParamScope)
6336 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006337 assert((S->getFlags() & Scope::DeclScope) &&
6338 "got alias-declaration outside of declaration scope");
6339
6340 if (Type.isInvalid())
6341 return 0;
6342
6343 bool Invalid = false;
6344 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6345 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006346 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006347
6348 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6349 return 0;
6350
6351 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006352 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006353 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006354 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6355 TInfo->getTypeLoc().getBeginLoc());
6356 }
Richard Smith162e1c12011-04-15 14:24:37 +00006357
6358 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6359 LookupName(Previous, S);
6360
6361 // Warn about shadowing the name of a template parameter.
6362 if (Previous.isSingleResult() &&
6363 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006364 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006365 Previous.clear();
6366 }
6367
6368 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6369 "name in alias declaration must be an identifier");
6370 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6371 Name.StartLocation,
6372 Name.Identifier, TInfo);
6373
6374 NewTD->setAccess(AS);
6375
6376 if (Invalid)
6377 NewTD->setInvalidDecl();
6378
Richard Smith3e4c6c42011-05-05 21:57:07 +00006379 CheckTypedefForVariablyModifiedType(S, NewTD);
6380 Invalid |= NewTD->isInvalidDecl();
6381
Richard Smith162e1c12011-04-15 14:24:37 +00006382 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006383
6384 NamedDecl *NewND;
6385 if (TemplateParamLists.size()) {
6386 TypeAliasTemplateDecl *OldDecl = 0;
6387 TemplateParameterList *OldTemplateParams = 0;
6388
6389 if (TemplateParamLists.size() != 1) {
6390 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6391 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6392 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6393 }
6394 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6395
6396 // Only consider previous declarations in the same scope.
6397 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6398 /*ExplicitInstantiationOrSpecialization*/false);
6399 if (!Previous.empty()) {
6400 Redeclaration = true;
6401
6402 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6403 if (!OldDecl && !Invalid) {
6404 Diag(UsingLoc, diag::err_redefinition_different_kind)
6405 << Name.Identifier;
6406
6407 NamedDecl *OldD = Previous.getRepresentativeDecl();
6408 if (OldD->getLocation().isValid())
6409 Diag(OldD->getLocation(), diag::note_previous_definition);
6410
6411 Invalid = true;
6412 }
6413
6414 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6415 if (TemplateParameterListsAreEqual(TemplateParams,
6416 OldDecl->getTemplateParameters(),
6417 /*Complain=*/true,
6418 TPL_TemplateMatch))
6419 OldTemplateParams = OldDecl->getTemplateParameters();
6420 else
6421 Invalid = true;
6422
6423 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6424 if (!Invalid &&
6425 !Context.hasSameType(OldTD->getUnderlyingType(),
6426 NewTD->getUnderlyingType())) {
6427 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6428 // but we can't reasonably accept it.
6429 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6430 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6431 if (OldTD->getLocation().isValid())
6432 Diag(OldTD->getLocation(), diag::note_previous_definition);
6433 Invalid = true;
6434 }
6435 }
6436 }
6437
6438 // Merge any previous default template arguments into our parameters,
6439 // and check the parameter list.
6440 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6441 TPC_TypeAliasTemplate))
6442 return 0;
6443
6444 TypeAliasTemplateDecl *NewDecl =
6445 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6446 Name.Identifier, TemplateParams,
6447 NewTD);
6448
6449 NewDecl->setAccess(AS);
6450
6451 if (Invalid)
6452 NewDecl->setInvalidDecl();
6453 else if (OldDecl)
6454 NewDecl->setPreviousDeclaration(OldDecl);
6455
6456 NewND = NewDecl;
6457 } else {
6458 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6459 NewND = NewTD;
6460 }
Richard Smith162e1c12011-04-15 14:24:37 +00006461
6462 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006463 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006464
Richard Smith3e4c6c42011-05-05 21:57:07 +00006465 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006466}
6467
John McCalld226f652010-08-21 09:40:31 +00006468Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006469 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006470 SourceLocation AliasLoc,
6471 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006472 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006473 SourceLocation IdentLoc,
6474 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006475
Anders Carlsson81c85c42009-03-28 23:53:49 +00006476 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006477 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6478 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006479
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006480 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006481 NamedDecl *PrevDecl
6482 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6483 ForRedeclaration);
6484 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6485 PrevDecl = 0;
6486
6487 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006488 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006489 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006490 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006491 // FIXME: At some point, we'll want to create the (redundant)
6492 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006493 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006494 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006495 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006496 }
Mike Stump1eb44332009-09-09 15:08:12 +00006497
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006498 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6499 diag::err_redefinition_different_kind;
6500 Diag(AliasLoc, DiagID) << Alias;
6501 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006502 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006503 }
6504
John McCalla24dc2e2009-11-17 02:14:36 +00006505 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006506 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006507
John McCallf36e02d2009-10-09 21:13:30 +00006508 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006509 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006510 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006511 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006512 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006513 }
Mike Stump1eb44332009-09-09 15:08:12 +00006514
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006515 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006516 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006517 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006518 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006519
John McCall3dbd3d52010-02-16 06:53:13 +00006520 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006521 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006522}
6523
Douglas Gregor39957dc2010-05-01 15:04:51 +00006524namespace {
6525 /// \brief Scoped object used to handle the state changes required in Sema
6526 /// to implicitly define the body of a C++ member function;
6527 class ImplicitlyDefinedFunctionScope {
6528 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006529 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006530
6531 public:
6532 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006533 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006534 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006535 S.PushFunctionScope();
6536 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6537 }
6538
6539 ~ImplicitlyDefinedFunctionScope() {
6540 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006541 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006542 }
6543 };
6544}
6545
Sean Hunt001cad92011-05-10 00:49:42 +00006546Sema::ImplicitExceptionSpecification
6547Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006548 // C++ [except.spec]p14:
6549 // An implicitly declared special member function (Clause 12) shall have an
6550 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006551 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006552 if (ClassDecl->isInvalidDecl())
6553 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006554
Sebastian Redl60618fa2011-03-12 11:50:43 +00006555 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006556 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6557 BEnd = ClassDecl->bases_end();
6558 B != BEnd; ++B) {
6559 if (B->isVirtual()) // Handled below.
6560 continue;
6561
Douglas Gregor18274032010-07-03 00:47:00 +00006562 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6563 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006564 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6565 // If this is a deleted function, add it anyway. This might be conformant
6566 // with the standard. This might not. I'm not sure. It might not matter.
6567 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006568 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006569 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006570 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006571
6572 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006573 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6574 BEnd = ClassDecl->vbases_end();
6575 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006576 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6577 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006578 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6579 // If this is a deleted function, add it anyway. This might be conformant
6580 // with the standard. This might not. I'm not sure. It might not matter.
6581 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006582 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006583 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006584 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006585
6586 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006587 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6588 FEnd = ClassDecl->field_end();
6589 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006590 if (F->hasInClassInitializer()) {
6591 if (Expr *E = F->getInClassInitializer())
6592 ExceptSpec.CalledExpr(E);
6593 else if (!F->isInvalidDecl())
6594 ExceptSpec.SetDelayed();
6595 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006596 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006597 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6598 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6599 // If this is a deleted function, add it anyway. This might be conformant
6600 // with the standard. This might not. I'm not sure. It might not matter.
6601 // In particular, the problem is that this function never gets called. It
6602 // might just be ill-formed because this function attempts to refer to
6603 // a deleted function here.
6604 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006605 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006606 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006607 }
John McCalle23cf432010-12-14 08:05:40 +00006608
Sean Hunt001cad92011-05-10 00:49:42 +00006609 return ExceptSpec;
6610}
6611
6612CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6613 CXXRecordDecl *ClassDecl) {
6614 // C++ [class.ctor]p5:
6615 // A default constructor for a class X is a constructor of class X
6616 // that can be called without an argument. If there is no
6617 // user-declared constructor for class X, a default constructor is
6618 // implicitly declared. An implicitly-declared default constructor
6619 // is an inline public member of its class.
6620 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6621 "Should not build implicit default constructor!");
6622
6623 ImplicitExceptionSpecification Spec =
6624 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6625 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006626
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006627 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006628 CanQualType ClassType
6629 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006630 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006631 DeclarationName Name
6632 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006633 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006634 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6635 Context, ClassDecl, ClassLoc, NameInfo,
6636 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6637 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6638 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006639 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006640 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006641 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006642 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006643 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006644
6645 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006646 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6647
Douglas Gregor23c94db2010-07-02 17:43:08 +00006648 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006649 PushOnScopeChains(DefaultCon, S, false);
6650 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006651
Sean Hunte16da072011-10-10 06:18:57 +00006652 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006653 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006654
Douglas Gregor32df23e2010-07-01 22:02:46 +00006655 return DefaultCon;
6656}
6657
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006658void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6659 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006660 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006661 !Constructor->doesThisDeclarationHaveABody() &&
6662 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006663 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006664
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006665 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006666 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006667
Douglas Gregor39957dc2010-05-01 15:04:51 +00006668 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006669 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006670 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006671 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006672 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006673 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006674 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006675 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006676 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006677
6678 SourceLocation Loc = Constructor->getLocation();
6679 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6680
6681 Constructor->setUsed();
6682 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006683
6684 if (ASTMutationListener *L = getASTMutationListener()) {
6685 L->CompletedImplicitDefinition(Constructor);
6686 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006687}
6688
Richard Smith7a614d82011-06-11 17:19:42 +00006689/// Get any existing defaulted default constructor for the given class. Do not
6690/// implicitly define one if it does not exist.
6691static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6692 CXXRecordDecl *D) {
6693 ASTContext &Context = Self.Context;
6694 QualType ClassType = Context.getTypeDeclType(D);
6695 DeclarationName ConstructorName
6696 = Context.DeclarationNames.getCXXConstructorName(
6697 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6698
6699 DeclContext::lookup_const_iterator Con, ConEnd;
6700 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6701 Con != ConEnd; ++Con) {
6702 // A function template cannot be defaulted.
6703 if (isa<FunctionTemplateDecl>(*Con))
6704 continue;
6705
6706 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6707 if (Constructor->isDefaultConstructor())
6708 return Constructor->isDefaulted() ? Constructor : 0;
6709 }
6710 return 0;
6711}
6712
6713void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6714 if (!D) return;
6715 AdjustDeclIfTemplate(D);
6716
6717 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6718 CXXConstructorDecl *CtorDecl
6719 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6720
6721 if (!CtorDecl) return;
6722
6723 // Compute the exception specification for the default constructor.
6724 const FunctionProtoType *CtorTy =
6725 CtorDecl->getType()->castAs<FunctionProtoType>();
6726 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
Richard Smithe6975e92012-04-17 00:58:00 +00006727 // FIXME: Don't do this unless the exception spec is needed.
Richard Smith7a614d82011-06-11 17:19:42 +00006728 ImplicitExceptionSpecification Spec =
6729 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6730 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6731 assert(EPI.ExceptionSpecType != EST_Delayed);
6732
6733 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6734 }
6735
6736 // If the default constructor is explicitly defaulted, checking the exception
6737 // specification is deferred until now.
6738 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6739 !ClassDecl->isDependentType())
Richard Smith3003e1d2012-05-15 04:39:51 +00006740 CheckExplicitlyDefaultedSpecialMember(CtorDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006741}
6742
Sebastian Redlf677ea32011-02-05 19:23:19 +00006743void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6744 // We start with an initial pass over the base classes to collect those that
6745 // inherit constructors from. If there are none, we can forgo all further
6746 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006747 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006748 BasesVector BasesToInheritFrom;
6749 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6750 BaseE = ClassDecl->bases_end();
6751 BaseIt != BaseE; ++BaseIt) {
6752 if (BaseIt->getInheritConstructors()) {
6753 QualType Base = BaseIt->getType();
6754 if (Base->isDependentType()) {
6755 // If we inherit constructors from anything that is dependent, just
6756 // abort processing altogether. We'll get another chance for the
6757 // instantiations.
6758 return;
6759 }
6760 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6761 }
6762 }
6763 if (BasesToInheritFrom.empty())
6764 return;
6765
6766 // Now collect the constructors that we already have in the current class.
6767 // Those take precedence over inherited constructors.
6768 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6769 // unless there is a user-declared constructor with the same signature in
6770 // the class where the using-declaration appears.
6771 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6772 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6773 CtorE = ClassDecl->ctor_end();
6774 CtorIt != CtorE; ++CtorIt) {
6775 ExistingConstructors.insert(
6776 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6777 }
6778
Sebastian Redlf677ea32011-02-05 19:23:19 +00006779 DeclarationName CreatedCtorName =
6780 Context.DeclarationNames.getCXXConstructorName(
6781 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6782
6783 // Now comes the true work.
6784 // First, we keep a map from constructor types to the base that introduced
6785 // them. Needed for finding conflicting constructors. We also keep the
6786 // actually inserted declarations in there, for pretty diagnostics.
6787 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6788 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6789 ConstructorToSourceMap InheritedConstructors;
6790 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6791 BaseE = BasesToInheritFrom.end();
6792 BaseIt != BaseE; ++BaseIt) {
6793 const RecordType *Base = *BaseIt;
6794 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6795 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6796 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6797 CtorE = BaseDecl->ctor_end();
6798 CtorIt != CtorE; ++CtorIt) {
6799 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006800 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006801 DeclarationName Name =
6802 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006803 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6804 LookupQualifiedName(Result, CurContext);
6805 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006806 SourceLocation UsingLoc = UD ? UD->getLocation() :
6807 ClassDecl->getLocation();
6808
6809 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6810 // from the class X named in the using-declaration consists of actual
6811 // constructors and notional constructors that result from the
6812 // transformation of defaulted parameters as follows:
6813 // - all non-template default constructors of X, and
6814 // - for each non-template constructor of X that has at least one
6815 // parameter with a default argument, the set of constructors that
6816 // results from omitting any ellipsis parameter specification and
6817 // successively omitting parameters with a default argument from the
6818 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006819 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006820 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6821 const FunctionProtoType *BaseCtorType =
6822 BaseCtor->getType()->getAs<FunctionProtoType>();
6823
6824 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6825 maxParams = BaseCtor->getNumParams();
6826 params <= maxParams; ++params) {
6827 // Skip default constructors. They're never inherited.
6828 if (params == 0)
6829 continue;
6830 // Skip copy and move constructors for the same reason.
6831 if (CanBeCopyOrMove && params == 1)
6832 continue;
6833
6834 // Build up a function type for this particular constructor.
6835 // FIXME: The working paper does not consider that the exception spec
6836 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006837 // source. This code doesn't yet, either. When it does, this code will
6838 // need to be delayed until after exception specifications and in-class
6839 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006840 const Type *NewCtorType;
6841 if (params == maxParams)
6842 NewCtorType = BaseCtorType;
6843 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006844 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006845 for (unsigned i = 0; i < params; ++i) {
6846 Args.push_back(BaseCtorType->getArgType(i));
6847 }
6848 FunctionProtoType::ExtProtoInfo ExtInfo =
6849 BaseCtorType->getExtProtoInfo();
6850 ExtInfo.Variadic = false;
6851 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6852 Args.data(), params, ExtInfo)
6853 .getTypePtr();
6854 }
6855 const Type *CanonicalNewCtorType =
6856 Context.getCanonicalType(NewCtorType);
6857
6858 // Now that we have the type, first check if the class already has a
6859 // constructor with this signature.
6860 if (ExistingConstructors.count(CanonicalNewCtorType))
6861 continue;
6862
6863 // Then we check if we have already declared an inherited constructor
6864 // with this signature.
6865 std::pair<ConstructorToSourceMap::iterator, bool> result =
6866 InheritedConstructors.insert(std::make_pair(
6867 CanonicalNewCtorType,
6868 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6869 if (!result.second) {
6870 // Already in the map. If it came from a different class, that's an
6871 // error. Not if it's from the same.
6872 CanQualType PreviousBase = result.first->second.first;
6873 if (CanonicalBase != PreviousBase) {
6874 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6875 const CXXConstructorDecl *PrevBaseCtor =
6876 PrevCtor->getInheritedConstructor();
6877 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6878
6879 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6880 Diag(BaseCtor->getLocation(),
6881 diag::note_using_decl_constructor_conflict_current_ctor);
6882 Diag(PrevBaseCtor->getLocation(),
6883 diag::note_using_decl_constructor_conflict_previous_ctor);
6884 Diag(PrevCtor->getLocation(),
6885 diag::note_using_decl_constructor_conflict_previous_using);
6886 }
6887 continue;
6888 }
6889
6890 // OK, we're there, now add the constructor.
6891 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006892 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006893 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6894 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006895 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6896 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006897 /*ImplicitlyDeclared=*/true,
6898 // FIXME: Due to a defect in the standard, we treat inherited
6899 // constructors as constexpr even if that makes them ill-formed.
6900 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006901 NewCtor->setAccess(BaseCtor->getAccess());
6902
6903 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006904 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006905 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006906 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6907 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006908 /*IdentifierInfo=*/0,
6909 BaseCtorType->getArgType(i),
6910 /*TInfo=*/0, SC_None,
6911 SC_None, /*DefaultArg=*/0));
6912 }
David Blaikie4278c652011-09-21 18:16:56 +00006913 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006914 NewCtor->setInheritedConstructor(BaseCtor);
6915
Sebastian Redlf677ea32011-02-05 19:23:19 +00006916 ClassDecl->addDecl(NewCtor);
6917 result.first->second.second = NewCtor;
6918 }
6919 }
6920 }
6921}
6922
Sean Huntcb45a0f2011-05-12 22:46:25 +00006923Sema::ImplicitExceptionSpecification
6924Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006925 // C++ [except.spec]p14:
6926 // An implicitly declared special member function (Clause 12) shall have
6927 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00006928 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006929 if (ClassDecl->isInvalidDecl())
6930 return ExceptSpec;
6931
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006932 // Direct base-class destructors.
6933 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6934 BEnd = ClassDecl->bases_end();
6935 B != BEnd; ++B) {
6936 if (B->isVirtual()) // Handled below.
6937 continue;
6938
6939 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006940 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006941 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006942 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006943
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006944 // Virtual base-class destructors.
6945 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6946 BEnd = ClassDecl->vbases_end();
6947 B != BEnd; ++B) {
6948 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006949 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006950 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006951 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006952
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006953 // Field destructors.
6954 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6955 FEnd = ClassDecl->field_end();
6956 F != FEnd; ++F) {
6957 if (const RecordType *RecordTy
6958 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006959 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006960 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006961 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006962
Sean Huntcb45a0f2011-05-12 22:46:25 +00006963 return ExceptSpec;
6964}
6965
6966CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6967 // C++ [class.dtor]p2:
6968 // If a class has no user-declared destructor, a destructor is
6969 // declared implicitly. An implicitly-declared destructor is an
6970 // inline public member of its class.
6971
6972 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006973 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006974 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6975
Douglas Gregor4923aa22010-07-02 20:37:36 +00006976 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006977 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006978
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006979 CanQualType ClassType
6980 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006981 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006982 DeclarationName Name
6983 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006984 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006985 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006986 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6987 /*isInline=*/true,
6988 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006989 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006990 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006991 Destructor->setImplicit();
6992 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006993
6994 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006995 ++ASTContext::NumImplicitDestructorsDeclared;
6996
6997 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006998 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006999 PushOnScopeChains(Destructor, S, false);
7000 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007001
7002 // This could be uniqued if it ever proves significant.
7003 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007004
Richard Smith9a561d52012-02-26 09:11:52 +00007005 AddOverriddenMethods(ClassDecl, Destructor);
7006
Richard Smith7d5088a2012-02-18 02:02:13 +00007007 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007008 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007009
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007010 return Destructor;
7011}
7012
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007013void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007014 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007015 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007016 !Destructor->doesThisDeclarationHaveABody() &&
7017 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007018 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007019 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007020 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007021
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007022 if (Destructor->isInvalidDecl())
7023 return;
7024
Douglas Gregor39957dc2010-05-01 15:04:51 +00007025 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007026
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007027 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007028 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7029 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007030
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007031 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007032 Diag(CurrentLocation, diag::note_member_synthesized_at)
7033 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7034
7035 Destructor->setInvalidDecl();
7036 return;
7037 }
7038
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007039 SourceLocation Loc = Destructor->getLocation();
7040 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007041 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007042 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007043 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007044
7045 if (ASTMutationListener *L = getASTMutationListener()) {
7046 L->CompletedImplicitDefinition(Destructor);
7047 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007048}
7049
Richard Smitha4156b82012-04-21 18:42:51 +00007050/// \brief Perform any semantic analysis which needs to be delayed until all
7051/// pending class member declarations have been parsed.
7052void Sema::ActOnFinishCXXMemberDecls() {
7053 // Now we have parsed all exception specifications, determine the implicit
7054 // exception specifications for destructors.
7055 for (unsigned i = 0, e = DelayedDestructorExceptionSpecs.size();
7056 i != e; ++i) {
7057 CXXDestructorDecl *Dtor = DelayedDestructorExceptionSpecs[i];
7058 AdjustDestructorExceptionSpec(Dtor->getParent(), Dtor, true);
7059 }
7060 DelayedDestructorExceptionSpecs.clear();
7061
7062 // Perform any deferred checking of exception specifications for virtual
7063 // destructors.
7064 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7065 i != e; ++i) {
7066 const CXXDestructorDecl *Dtor =
7067 DelayedDestructorExceptionSpecChecks[i].first;
7068 assert(!Dtor->getParent()->isDependentType() &&
7069 "Should not ever add destructors of templates into the list.");
7070 CheckOverridingFunctionExceptionSpec(Dtor,
7071 DelayedDestructorExceptionSpecChecks[i].second);
7072 }
7073 DelayedDestructorExceptionSpecChecks.clear();
7074}
7075
Sebastian Redl0ee33912011-05-19 05:13:44 +00007076void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
Richard Smitha4156b82012-04-21 18:42:51 +00007077 CXXDestructorDecl *destructor,
7078 bool WasDelayed) {
Sebastian Redl0ee33912011-05-19 05:13:44 +00007079 // C++11 [class.dtor]p3:
7080 // A declaration of a destructor that does not have an exception-
7081 // specification is implicitly considered to have the same exception-
7082 // specification as an implicit declaration.
7083 const FunctionProtoType *dtorType = destructor->getType()->
7084 getAs<FunctionProtoType>();
Richard Smitha4156b82012-04-21 18:42:51 +00007085 if (!WasDelayed && dtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007086 return;
7087
7088 ImplicitExceptionSpecification exceptSpec =
7089 ComputeDefaultedDtorExceptionSpec(classDecl);
7090
Chandler Carruth3f224b22011-09-20 04:55:26 +00007091 // Replace the destructor's type, building off the existing one. Fortunately,
7092 // the only thing of interest in the destructor type is its extended info.
7093 // The return and arguments are fixed.
7094 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007095 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7096 epi.NumExceptions = exceptSpec.size();
7097 epi.Exceptions = exceptSpec.data();
7098 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7099
7100 destructor->setType(ty);
7101
Richard Smitha4156b82012-04-21 18:42:51 +00007102 // If we can't compute the exception specification for this destructor yet
7103 // (because it depends on an exception specification which we have not parsed
7104 // yet), make a note that we need to try again when the class is complete.
7105 if (epi.ExceptionSpecType == EST_Delayed) {
7106 assert(!WasDelayed && "couldn't compute destructor exception spec");
7107 DelayedDestructorExceptionSpecs.push_back(destructor);
7108 }
7109
Sebastian Redl0ee33912011-05-19 05:13:44 +00007110 // FIXME: If the destructor has a body that could throw, and the newly created
7111 // spec doesn't allow exceptions, we should emit a warning, because this
7112 // change in behavior can break conforming C++03 programs at runtime.
7113 // However, we don't have a body yet, so it needs to be done somewhere else.
7114}
7115
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007116/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007117/// \c To.
7118///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007119/// This routine is used to copy/move the members of a class with an
7120/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007121/// copied are arrays, this routine builds for loops to copy them.
7122///
7123/// \param S The Sema object used for type-checking.
7124///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007125/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007126///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007127/// \param T The type of the expressions being copied/moved. Both expressions
7128/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007129///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007130/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007131///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007132/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007133///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007134/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007135/// Otherwise, it's a non-static member subobject.
7136///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007137/// \param Copying Whether we're copying or moving.
7138///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007139/// \param Depth Internal parameter recording the depth of the recursion.
7140///
7141/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007142static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007143BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007144 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007145 bool CopyingBaseSubobject, bool Copying,
7146 unsigned Depth = 0) {
7147 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007148 // Each subobject is assigned in the manner appropriate to its type:
7149 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007150 // - if the subobject is of class type, as if by a call to operator= with
7151 // the subobject as the object expression and the corresponding
7152 // subobject of x as a single function argument (as if by explicit
7153 // qualification; that is, ignoring any possible virtual overriding
7154 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007155 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7156 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7157
7158 // Look for operator=.
7159 DeclarationName Name
7160 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7161 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7162 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7163
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007164 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007165 LookupResult::Filter F = OpLookup.makeFilter();
7166 while (F.hasNext()) {
7167 NamedDecl *D = F.next();
7168 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007169 if (Method->isCopyAssignmentOperator() ||
7170 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007171 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007172
Douglas Gregor06a9f362010-05-01 20:49:11 +00007173 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007174 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007175 F.done();
7176
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007177 // Suppress the protected check (C++ [class.protected]) for each of the
7178 // assignment operators we found. This strange dance is required when
7179 // we're assigning via a base classes's copy-assignment operator. To
7180 // ensure that we're getting the right base class subobject (without
7181 // ambiguities), we need to cast "this" to that subobject type; to
7182 // ensure that we don't go through the virtual call mechanism, we need
7183 // to qualify the operator= name with the base class (see below). However,
7184 // this means that if the base class has a protected copy assignment
7185 // operator, the protected member access check will fail. So, we
7186 // rewrite "protected" access to "public" access in this case, since we
7187 // know by construction that we're calling from a derived class.
7188 if (CopyingBaseSubobject) {
7189 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7190 L != LEnd; ++L) {
7191 if (L.getAccess() == AS_protected)
7192 L.setAccess(AS_public);
7193 }
7194 }
7195
Douglas Gregor06a9f362010-05-01 20:49:11 +00007196 // Create the nested-name-specifier that will be used to qualify the
7197 // reference to operator=; this is required to suppress the virtual
7198 // call mechanism.
7199 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007200 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007201 SS.MakeTrivial(S.Context,
7202 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007203 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007204 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007205
7206 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007207 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007208 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007209 /*TemplateKWLoc=*/SourceLocation(),
7210 /*FirstQualifierInScope=*/0,
7211 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007212 /*TemplateArgs=*/0,
7213 /*SuppressQualifierCheck=*/true);
7214 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007215 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007216
7217 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007218
John McCall60d7b3a2010-08-24 06:29:42 +00007219 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007220 OpEqualRef.takeAs<Expr>(),
7221 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007222 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007223 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007224
7225 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007226 }
John McCallb0207482010-03-16 06:11:48 +00007227
Douglas Gregor06a9f362010-05-01 20:49:11 +00007228 // - if the subobject is of scalar type, the built-in assignment
7229 // operator is used.
7230 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7231 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007232 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007233 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007234 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007235
7236 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007237 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007238
7239 // - if the subobject is an array, each element is assigned, in the
7240 // manner appropriate to the element type;
7241
7242 // Construct a loop over the array bounds, e.g.,
7243 //
7244 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7245 //
7246 // that will copy each of the array elements.
7247 QualType SizeType = S.Context.getSizeType();
7248
7249 // Create the iteration variable.
7250 IdentifierInfo *IterationVarName = 0;
7251 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007252 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007253 llvm::raw_svector_ostream OS(Str);
7254 OS << "__i" << Depth;
7255 IterationVarName = &S.Context.Idents.get(OS.str());
7256 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007257 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007258 IterationVarName, SizeType,
7259 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007260 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007261
7262 // Initialize the iteration variable to zero.
7263 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007264 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007265
7266 // Create a reference to the iteration variable; we'll use this several
7267 // times throughout.
7268 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007269 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007270 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007271 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7272 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7273
Douglas Gregor06a9f362010-05-01 20:49:11 +00007274 // Create the DeclStmt that holds the iteration variable.
7275 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7276
7277 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007278 llvm::APInt Upper
7279 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007280 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007281 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007282 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7283 BO_NE, S.Context.BoolTy,
7284 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007285
7286 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007287 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007288 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7289 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007290
7291 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007292 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007293 IterationVarRefRVal,
7294 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007295 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007296 IterationVarRefRVal,
7297 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007298 if (!Copying) // Cast to rvalue
7299 From = CastForMoving(S, From);
7300
7301 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007302 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7303 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007304 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007305 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007306 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007307
7308 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007309 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007310 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007311 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007312 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007313}
7314
Sean Hunt30de05c2011-05-14 05:23:20 +00007315std::pair<Sema::ImplicitExceptionSpecification, bool>
7316Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7317 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007318 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00007319 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007320
Douglas Gregord3c35902010-07-01 16:36:15 +00007321 // C++ [class.copy]p10:
7322 // If the class definition does not explicitly declare a copy
7323 // assignment operator, one is declared implicitly.
7324 // The implicitly-defined copy assignment operator for a class X
7325 // will have the form
7326 //
7327 // X& X::operator=(const X&)
7328 //
7329 // if
7330 bool HasConstCopyAssignment = true;
7331
7332 // -- each direct base class B of X has a copy assignment operator
7333 // whose parameter is of type const B&, const volatile B& or B,
7334 // and
7335 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7336 BaseEnd = ClassDecl->bases_end();
7337 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007338 // We'll handle this below
7339 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7340 continue;
7341
Douglas Gregord3c35902010-07-01 16:36:15 +00007342 assert(!Base->getType()->isDependentType() &&
7343 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007344 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007345 HasConstCopyAssignment &=
7346 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7347 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007348 }
7349
Richard Smithebaf0e62011-10-18 20:49:44 +00007350 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007351 if (LangOpts.CPlusPlus0x) {
7352 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7353 BaseEnd = ClassDecl->vbases_end();
7354 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7355 assert(!Base->getType()->isDependentType() &&
7356 "Cannot generate implicit members for class with dependent bases.");
7357 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007358 HasConstCopyAssignment &=
7359 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7360 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007361 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007362 }
7363
7364 // -- for all the nonstatic data members of X that are of a class
7365 // type M (or array thereof), each such class type has a copy
7366 // assignment operator whose parameter is of type const M&,
7367 // const volatile M& or M.
7368 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7369 FieldEnd = ClassDecl->field_end();
7370 HasConstCopyAssignment && Field != FieldEnd;
7371 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007372 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007373 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00007374 HasConstCopyAssignment &=
7375 (bool)LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7376 false, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007377 }
7378 }
7379
7380 // Otherwise, the implicitly declared copy assignment operator will
7381 // have the form
7382 //
7383 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007384
Douglas Gregorb87786f2010-07-01 17:48:08 +00007385 // C++ [except.spec]p14:
7386 // An implicitly declared special member function (Clause 12) shall have an
7387 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007388
7389 // It is unspecified whether or not an implicit copy assignment operator
7390 // attempts to deduplicate calls to assignment operators of virtual bases are
7391 // made. As such, this exception specification is effectively unspecified.
7392 // Based on a similar decision made for constness in C++0x, we're erring on
7393 // the side of assuming such calls to be made regardless of whether they
7394 // actually happen.
Richard Smithe6975e92012-04-17 00:58:00 +00007395 ImplicitExceptionSpecification ExceptSpec(*this);
Sean Hunt661c67a2011-06-21 23:42:56 +00007396 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007397 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7398 BaseEnd = ClassDecl->bases_end();
7399 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007400 if (Base->isVirtual())
7401 continue;
7402
Douglas Gregora376d102010-07-02 21:50:04 +00007403 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007404 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007405 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7406 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007407 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007408 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007409
7410 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7411 BaseEnd = ClassDecl->vbases_end();
7412 Base != BaseEnd; ++Base) {
7413 CXXRecordDecl *BaseClassDecl
7414 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7415 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7416 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007417 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007418 }
7419
Douglas Gregorb87786f2010-07-01 17:48:08 +00007420 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7421 FieldEnd = ClassDecl->field_end();
7422 Field != FieldEnd;
7423 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007424 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007425 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7426 if (CXXMethodDecl *CopyAssign =
7427 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007428 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007429 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007430 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007431
Sean Hunt30de05c2011-05-14 05:23:20 +00007432 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7433}
7434
7435CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7436 // Note: The following rules are largely analoguous to the copy
7437 // constructor rules. Note that virtual bases are not taken into account
7438 // for determining the argument type of the operator. Note also that
7439 // operators taking an object instead of a reference are allowed.
7440
Richard Smithe6975e92012-04-17 00:58:00 +00007441 ImplicitExceptionSpecification Spec(*this);
Sean Hunt30de05c2011-05-14 05:23:20 +00007442 bool Const;
7443 llvm::tie(Spec, Const) =
7444 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7445
7446 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7447 QualType RetType = Context.getLValueReferenceType(ArgType);
7448 if (Const)
7449 ArgType = ArgType.withConst();
7450 ArgType = Context.getLValueReferenceType(ArgType);
7451
Douglas Gregord3c35902010-07-01 16:36:15 +00007452 // An implicitly-declared copy assignment operator is an inline public
7453 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007454 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007455 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007456 SourceLocation ClassLoc = ClassDecl->getLocation();
7457 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007458 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007459 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007460 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007461 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007462 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007463 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007464 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007465 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007466 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007467 CopyAssignment->setImplicit();
7468 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007469
7470 // Add the parameter to the operator.
7471 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007472 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007473 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007474 SC_None,
7475 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007476 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007477
Douglas Gregora376d102010-07-02 21:50:04 +00007478 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007479 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007480
Douglas Gregor23c94db2010-07-02 17:43:08 +00007481 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007482 PushOnScopeChains(CopyAssignment, S, false);
7483 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007484
Nico Weberafcc96a2012-01-23 03:19:29 +00007485 // C++0x [class.copy]p19:
7486 // .... If the class definition does not explicitly declare a copy
7487 // assignment operator, there is no user-declared move constructor, and
7488 // there is no user-declared move assignment operator, a copy assignment
7489 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007490 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007491 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007492
Douglas Gregord3c35902010-07-01 16:36:15 +00007493 AddOverriddenMethods(ClassDecl, CopyAssignment);
7494 return CopyAssignment;
7495}
7496
Douglas Gregor06a9f362010-05-01 20:49:11 +00007497void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7498 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007499 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007500 CopyAssignOperator->isOverloadedOperator() &&
7501 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007502 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7503 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007504 "DefineImplicitCopyAssignment called for wrong function");
7505
7506 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7507
7508 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7509 CopyAssignOperator->setInvalidDecl();
7510 return;
7511 }
7512
7513 CopyAssignOperator->setUsed();
7514
7515 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007516 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007517
7518 // C++0x [class.copy]p30:
7519 // The implicitly-defined or explicitly-defaulted copy assignment operator
7520 // for a non-union class X performs memberwise copy assignment of its
7521 // subobjects. The direct base classes of X are assigned first, in the
7522 // order of their declaration in the base-specifier-list, and then the
7523 // immediate non-static data members of X are assigned, in the order in
7524 // which they were declared in the class definition.
7525
7526 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007527 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007528
7529 // The parameter for the "other" object, which we are copying from.
7530 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7531 Qualifiers OtherQuals = Other->getType().getQualifiers();
7532 QualType OtherRefType = Other->getType();
7533 if (const LValueReferenceType *OtherRef
7534 = OtherRefType->getAs<LValueReferenceType>()) {
7535 OtherRefType = OtherRef->getPointeeType();
7536 OtherQuals = OtherRefType.getQualifiers();
7537 }
7538
7539 // Our location for everything implicitly-generated.
7540 SourceLocation Loc = CopyAssignOperator->getLocation();
7541
7542 // Construct a reference to the "other" object. We'll be using this
7543 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007544 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007545 assert(OtherRef && "Reference to parameter cannot fail!");
7546
7547 // Construct the "this" pointer. We'll be using this throughout the generated
7548 // ASTs.
7549 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7550 assert(This && "Reference to this cannot fail!");
7551
7552 // Assign base classes.
7553 bool Invalid = false;
7554 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7555 E = ClassDecl->bases_end(); Base != E; ++Base) {
7556 // Form the assignment:
7557 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7558 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007559 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007560 Invalid = true;
7561 continue;
7562 }
7563
John McCallf871d0c2010-08-07 06:22:56 +00007564 CXXCastPath BasePath;
7565 BasePath.push_back(Base);
7566
Douglas Gregor06a9f362010-05-01 20:49:11 +00007567 // Construct the "from" expression, which is an implicit cast to the
7568 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007569 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007570 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7571 CK_UncheckedDerivedToBase,
7572 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007573
7574 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007575 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007576
7577 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007578 To = ImpCastExprToType(To.take(),
7579 Context.getCVRQualifiedType(BaseType,
7580 CopyAssignOperator->getTypeQualifiers()),
7581 CK_UncheckedDerivedToBase,
7582 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007583
7584 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007585 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007586 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007587 /*CopyingBaseSubobject=*/true,
7588 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007589 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007590 Diag(CurrentLocation, diag::note_member_synthesized_at)
7591 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7592 CopyAssignOperator->setInvalidDecl();
7593 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007594 }
7595
7596 // Success! Record the copy.
7597 Statements.push_back(Copy.takeAs<Expr>());
7598 }
7599
7600 // \brief Reference to the __builtin_memcpy function.
7601 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007602 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007603 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007604
7605 // Assign non-static members.
7606 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7607 FieldEnd = ClassDecl->field_end();
7608 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007609 if (Field->isUnnamedBitfield())
7610 continue;
7611
Douglas Gregor06a9f362010-05-01 20:49:11 +00007612 // Check for members of reference type; we can't copy those.
7613 if (Field->getType()->isReferenceType()) {
7614 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7615 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7616 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007617 Diag(CurrentLocation, diag::note_member_synthesized_at)
7618 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619 Invalid = true;
7620 continue;
7621 }
7622
7623 // Check for members of const-qualified, non-class type.
7624 QualType BaseType = Context.getBaseElementType(Field->getType());
7625 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7626 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7627 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7628 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007629 Diag(CurrentLocation, diag::note_member_synthesized_at)
7630 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007631 Invalid = true;
7632 continue;
7633 }
John McCallb77115d2011-06-17 00:18:42 +00007634
7635 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007636 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7637 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007638
7639 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007640 if (FieldType->isIncompleteArrayType()) {
7641 assert(ClassDecl->hasFlexibleArrayMember() &&
7642 "Incomplete array type is not valid");
7643 continue;
7644 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007645
7646 // Build references to the field in the object we're copying from and to.
7647 CXXScopeSpec SS; // Intentionally empty
7648 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7649 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007650 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007651 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007652 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007653 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007654 SS, SourceLocation(), 0,
7655 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007656 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007657 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007658 SS, SourceLocation(), 0,
7659 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7661 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7662
7663 // If the field should be copied with __builtin_memcpy rather than via
7664 // explicit assignments, do so. This optimization only applies for arrays
7665 // of scalars and arrays of class type with trivial copy-assignment
7666 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007667 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007668 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669 // Compute the size of the memory buffer to be copied.
7670 QualType SizeType = Context.getSizeType();
7671 llvm::APInt Size(Context.getTypeSize(SizeType),
7672 Context.getTypeSizeInChars(BaseType).getQuantity());
7673 for (const ConstantArrayType *Array
7674 = Context.getAsConstantArrayType(FieldType);
7675 Array;
7676 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007677 llvm::APInt ArraySize
7678 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679 Size *= ArraySize;
7680 }
7681
7682 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007683 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7684 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007685
7686 bool NeedsCollectableMemCpy =
7687 (BaseType->isRecordType() &&
7688 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7689
7690 if (NeedsCollectableMemCpy) {
7691 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007692 // Create a reference to the __builtin_objc_memmove_collectable function.
7693 LookupResult R(*this,
7694 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007695 Loc, LookupOrdinaryName);
7696 LookupName(R, TUScope, true);
7697
7698 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7699 if (!CollectableMemCpy) {
7700 // Something went horribly wrong earlier, and we will have
7701 // complained about it.
7702 Invalid = true;
7703 continue;
7704 }
7705
7706 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7707 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007708 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007709 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7710 }
7711 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007712 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007713 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007714 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7715 LookupOrdinaryName);
7716 LookupName(R, TUScope, true);
7717
7718 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7719 if (!BuiltinMemCpy) {
7720 // Something went horribly wrong earlier, and we will have complained
7721 // about it.
7722 Invalid = true;
7723 continue;
7724 }
7725
7726 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7727 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007728 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007729 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7730 }
7731
John McCallca0408f2010-08-23 06:44:23 +00007732 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007733 CallArgs.push_back(To.takeAs<Expr>());
7734 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007735 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007736 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007737 if (NeedsCollectableMemCpy)
7738 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007739 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007740 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007741 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007742 else
7743 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007744 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007745 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007746 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007747
Douglas Gregor06a9f362010-05-01 20:49:11 +00007748 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7749 Statements.push_back(Call.takeAs<Expr>());
7750 continue;
7751 }
7752
7753 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007754 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007755 To.get(), From.get(),
7756 /*CopyingBaseSubobject=*/false,
7757 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007758 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007759 Diag(CurrentLocation, diag::note_member_synthesized_at)
7760 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7761 CopyAssignOperator->setInvalidDecl();
7762 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007763 }
7764
7765 // Success! Record the copy.
7766 Statements.push_back(Copy.takeAs<Stmt>());
7767 }
7768
7769 if (!Invalid) {
7770 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007771 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007772
John McCall60d7b3a2010-08-24 06:29:42 +00007773 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007774 if (Return.isInvalid())
7775 Invalid = true;
7776 else {
7777 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007778
7779 if (Trap.hasErrorOccurred()) {
7780 Diag(CurrentLocation, diag::note_member_synthesized_at)
7781 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7782 Invalid = true;
7783 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007784 }
7785 }
7786
7787 if (Invalid) {
7788 CopyAssignOperator->setInvalidDecl();
7789 return;
7790 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007791
7792 StmtResult Body;
7793 {
7794 CompoundScopeRAII CompoundScope(*this);
7795 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7796 /*isStmtExpr=*/false);
7797 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7798 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007799 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007800
7801 if (ASTMutationListener *L = getASTMutationListener()) {
7802 L->CompletedImplicitDefinition(CopyAssignOperator);
7803 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007804}
7805
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007806Sema::ImplicitExceptionSpecification
7807Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
Richard Smithe6975e92012-04-17 00:58:00 +00007808 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007809
7810 if (ClassDecl->isInvalidDecl())
7811 return ExceptSpec;
7812
7813 // C++0x [except.spec]p14:
7814 // An implicitly declared special member function (Clause 12) shall have an
7815 // exception-specification. [...]
7816
7817 // It is unspecified whether or not an implicit move assignment operator
7818 // attempts to deduplicate calls to assignment operators of virtual bases are
7819 // made. As such, this exception specification is effectively unspecified.
7820 // Based on a similar decision made for constness in C++0x, we're erring on
7821 // the side of assuming such calls to be made regardless of whether they
7822 // actually happen.
7823 // Note that a move constructor is not implicitly declared when there are
7824 // virtual bases, but it can still be user-declared and explicitly defaulted.
7825 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7826 BaseEnd = ClassDecl->bases_end();
7827 Base != BaseEnd; ++Base) {
7828 if (Base->isVirtual())
7829 continue;
7830
7831 CXXRecordDecl *BaseClassDecl
7832 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7833 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7834 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007835 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007836 }
7837
7838 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7839 BaseEnd = ClassDecl->vbases_end();
7840 Base != BaseEnd; ++Base) {
7841 CXXRecordDecl *BaseClassDecl
7842 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7843 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7844 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007845 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007846 }
7847
7848 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7849 FieldEnd = ClassDecl->field_end();
7850 Field != FieldEnd;
7851 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007852 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007853 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7854 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7855 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007856 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007857 }
7858 }
7859
7860 return ExceptSpec;
7861}
7862
Richard Smith1c931be2012-04-02 18:40:40 +00007863/// Determine whether the class type has any direct or indirect virtual base
7864/// classes which have a non-trivial move assignment operator.
7865static bool
7866hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
7867 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7868 BaseEnd = ClassDecl->vbases_end();
7869 Base != BaseEnd; ++Base) {
7870 CXXRecordDecl *BaseClass =
7871 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7872
7873 // Try to declare the move assignment. If it would be deleted, then the
7874 // class does not have a non-trivial move assignment.
7875 if (BaseClass->needsImplicitMoveAssignment())
7876 S.DeclareImplicitMoveAssignment(BaseClass);
7877
7878 // If the class has both a trivial move assignment and a non-trivial move
7879 // assignment, hasTrivialMoveAssignment() is false.
7880 if (BaseClass->hasDeclaredMoveAssignment() &&
7881 !BaseClass->hasTrivialMoveAssignment())
7882 return true;
7883 }
7884
7885 return false;
7886}
7887
7888/// Determine whether the given type either has a move constructor or is
7889/// trivially copyable.
7890static bool
7891hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
7892 Type = S.Context.getBaseElementType(Type);
7893
7894 // FIXME: Technically, non-trivially-copyable non-class types, such as
7895 // reference types, are supposed to return false here, but that appears
7896 // to be a standard defect.
7897 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00007898 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00007899 return true;
7900
7901 if (Type.isTriviallyCopyableType(S.Context))
7902 return true;
7903
7904 if (IsConstructor) {
7905 if (ClassDecl->needsImplicitMoveConstructor())
7906 S.DeclareImplicitMoveConstructor(ClassDecl);
7907 return ClassDecl->hasDeclaredMoveConstructor();
7908 }
7909
7910 if (ClassDecl->needsImplicitMoveAssignment())
7911 S.DeclareImplicitMoveAssignment(ClassDecl);
7912 return ClassDecl->hasDeclaredMoveAssignment();
7913}
7914
7915/// Determine whether all non-static data members and direct or virtual bases
7916/// of class \p ClassDecl have either a move operation, or are trivially
7917/// copyable.
7918static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
7919 bool IsConstructor) {
7920 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7921 BaseEnd = ClassDecl->bases_end();
7922 Base != BaseEnd; ++Base) {
7923 if (Base->isVirtual())
7924 continue;
7925
7926 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
7927 return false;
7928 }
7929
7930 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7931 BaseEnd = ClassDecl->vbases_end();
7932 Base != BaseEnd; ++Base) {
7933 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
7934 return false;
7935 }
7936
7937 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7938 FieldEnd = ClassDecl->field_end();
7939 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007940 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00007941 return false;
7942 }
7943
7944 return true;
7945}
7946
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007947CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00007948 // C++11 [class.copy]p20:
7949 // If the definition of a class X does not explicitly declare a move
7950 // assignment operator, one will be implicitly declared as defaulted
7951 // if and only if:
7952 //
7953 // - [first 4 bullets]
7954 assert(ClassDecl->needsImplicitMoveAssignment());
7955
7956 // [Checked after we build the declaration]
7957 // - the move assignment operator would not be implicitly defined as
7958 // deleted,
7959
7960 // [DR1402]:
7961 // - X has no direct or indirect virtual base class with a non-trivial
7962 // move assignment operator, and
7963 // - each of X's non-static data members and direct or virtual base classes
7964 // has a type that either has a move assignment operator or is trivially
7965 // copyable.
7966 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
7967 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
7968 ClassDecl->setFailedImplicitMoveAssignment();
7969 return 0;
7970 }
7971
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007972 // Note: The following rules are largely analoguous to the move
7973 // constructor rules.
7974
7975 ImplicitExceptionSpecification Spec(
7976 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7977
7978 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7979 QualType RetType = Context.getLValueReferenceType(ArgType);
7980 ArgType = Context.getRValueReferenceType(ArgType);
7981
7982 // An implicitly-declared move assignment operator is an inline public
7983 // member of its class.
7984 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7985 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7986 SourceLocation ClassLoc = ClassDecl->getLocation();
7987 DeclarationNameInfo NameInfo(Name, ClassLoc);
7988 CXXMethodDecl *MoveAssignment
7989 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7990 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7991 /*TInfo=*/0, /*isStatic=*/false,
7992 /*StorageClassAsWritten=*/SC_None,
7993 /*isInline=*/true,
7994 /*isConstexpr=*/false,
7995 SourceLocation());
7996 MoveAssignment->setAccess(AS_public);
7997 MoveAssignment->setDefaulted();
7998 MoveAssignment->setImplicit();
7999 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8000
8001 // Add the parameter to the operator.
8002 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8003 ClassLoc, ClassLoc, /*Id=*/0,
8004 ArgType, /*TInfo=*/0,
8005 SC_None,
8006 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008007 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008008
8009 // Note that we have added this copy-assignment operator.
8010 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8011
8012 // C++0x [class.copy]p9:
8013 // If the definition of a class X does not explicitly declare a move
8014 // assignment operator, one will be implicitly declared as defaulted if and
8015 // only if:
8016 // [...]
8017 // - the move assignment operator would not be implicitly defined as
8018 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008019 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008020 // Cache this result so that we don't try to generate this over and over
8021 // on every lookup, leaking memory and wasting time.
8022 ClassDecl->setFailedImplicitMoveAssignment();
8023 return 0;
8024 }
8025
8026 if (Scope *S = getScopeForContext(ClassDecl))
8027 PushOnScopeChains(MoveAssignment, S, false);
8028 ClassDecl->addDecl(MoveAssignment);
8029
8030 AddOverriddenMethods(ClassDecl, MoveAssignment);
8031 return MoveAssignment;
8032}
8033
8034void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8035 CXXMethodDecl *MoveAssignOperator) {
8036 assert((MoveAssignOperator->isDefaulted() &&
8037 MoveAssignOperator->isOverloadedOperator() &&
8038 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008039 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8040 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008041 "DefineImplicitMoveAssignment called for wrong function");
8042
8043 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8044
8045 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8046 MoveAssignOperator->setInvalidDecl();
8047 return;
8048 }
8049
8050 MoveAssignOperator->setUsed();
8051
8052 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8053 DiagnosticErrorTrap Trap(Diags);
8054
8055 // C++0x [class.copy]p28:
8056 // The implicitly-defined or move assignment operator for a non-union class
8057 // X performs memberwise move assignment of its subobjects. The direct base
8058 // classes of X are assigned first, in the order of their declaration in the
8059 // base-specifier-list, and then the immediate non-static data members of X
8060 // are assigned, in the order in which they were declared in the class
8061 // definition.
8062
8063 // The statements that form the synthesized function body.
8064 ASTOwningVector<Stmt*> Statements(*this);
8065
8066 // The parameter for the "other" object, which we are move from.
8067 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8068 QualType OtherRefType = Other->getType()->
8069 getAs<RValueReferenceType>()->getPointeeType();
8070 assert(OtherRefType.getQualifiers() == 0 &&
8071 "Bad argument type of defaulted move assignment");
8072
8073 // Our location for everything implicitly-generated.
8074 SourceLocation Loc = MoveAssignOperator->getLocation();
8075
8076 // Construct a reference to the "other" object. We'll be using this
8077 // throughout the generated ASTs.
8078 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8079 assert(OtherRef && "Reference to parameter cannot fail!");
8080 // Cast to rvalue.
8081 OtherRef = CastForMoving(*this, OtherRef);
8082
8083 // Construct the "this" pointer. We'll be using this throughout the generated
8084 // ASTs.
8085 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8086 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008087
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008088 // Assign base classes.
8089 bool Invalid = false;
8090 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8091 E = ClassDecl->bases_end(); Base != E; ++Base) {
8092 // Form the assignment:
8093 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8094 QualType BaseType = Base->getType().getUnqualifiedType();
8095 if (!BaseType->isRecordType()) {
8096 Invalid = true;
8097 continue;
8098 }
8099
8100 CXXCastPath BasePath;
8101 BasePath.push_back(Base);
8102
8103 // Construct the "from" expression, which is an implicit cast to the
8104 // appropriately-qualified base type.
8105 Expr *From = OtherRef;
8106 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008107 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008108
8109 // Dereference "this".
8110 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8111
8112 // Implicitly cast "this" to the appropriately-qualified base type.
8113 To = ImpCastExprToType(To.take(),
8114 Context.getCVRQualifiedType(BaseType,
8115 MoveAssignOperator->getTypeQualifiers()),
8116 CK_UncheckedDerivedToBase,
8117 VK_LValue, &BasePath);
8118
8119 // Build the move.
8120 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8121 To.get(), From,
8122 /*CopyingBaseSubobject=*/true,
8123 /*Copying=*/false);
8124 if (Move.isInvalid()) {
8125 Diag(CurrentLocation, diag::note_member_synthesized_at)
8126 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8127 MoveAssignOperator->setInvalidDecl();
8128 return;
8129 }
8130
8131 // Success! Record the move.
8132 Statements.push_back(Move.takeAs<Expr>());
8133 }
8134
8135 // \brief Reference to the __builtin_memcpy function.
8136 Expr *BuiltinMemCpyRef = 0;
8137 // \brief Reference to the __builtin_objc_memmove_collectable function.
8138 Expr *CollectableMemCpyRef = 0;
8139
8140 // Assign non-static members.
8141 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8142 FieldEnd = ClassDecl->field_end();
8143 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008144 if (Field->isUnnamedBitfield())
8145 continue;
8146
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008147 // Check for members of reference type; we can't move those.
8148 if (Field->getType()->isReferenceType()) {
8149 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8150 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8151 Diag(Field->getLocation(), diag::note_declared_at);
8152 Diag(CurrentLocation, diag::note_member_synthesized_at)
8153 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8154 Invalid = true;
8155 continue;
8156 }
8157
8158 // Check for members of const-qualified, non-class type.
8159 QualType BaseType = Context.getBaseElementType(Field->getType());
8160 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8161 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8162 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8163 Diag(Field->getLocation(), diag::note_declared_at);
8164 Diag(CurrentLocation, diag::note_member_synthesized_at)
8165 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8166 Invalid = true;
8167 continue;
8168 }
8169
8170 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008171 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8172 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008173
8174 QualType FieldType = Field->getType().getNonReferenceType();
8175 if (FieldType->isIncompleteArrayType()) {
8176 assert(ClassDecl->hasFlexibleArrayMember() &&
8177 "Incomplete array type is not valid");
8178 continue;
8179 }
8180
8181 // Build references to the field in the object we're copying from and to.
8182 CXXScopeSpec SS; // Intentionally empty
8183 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8184 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008185 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008186 MemberLookup.resolveKind();
8187 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8188 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008189 SS, SourceLocation(), 0,
8190 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008191 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8192 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008193 SS, SourceLocation(), 0,
8194 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008195 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8196 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8197
8198 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8199 "Member reference with rvalue base must be rvalue except for reference "
8200 "members, which aren't allowed for move assignment.");
8201
8202 // If the field should be copied with __builtin_memcpy rather than via
8203 // explicit assignments, do so. This optimization only applies for arrays
8204 // of scalars and arrays of class type with trivial move-assignment
8205 // operators.
8206 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8207 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8208 // Compute the size of the memory buffer to be copied.
8209 QualType SizeType = Context.getSizeType();
8210 llvm::APInt Size(Context.getTypeSize(SizeType),
8211 Context.getTypeSizeInChars(BaseType).getQuantity());
8212 for (const ConstantArrayType *Array
8213 = Context.getAsConstantArrayType(FieldType);
8214 Array;
8215 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8216 llvm::APInt ArraySize
8217 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8218 Size *= ArraySize;
8219 }
8220
Douglas Gregor45d3d712011-09-01 02:09:07 +00008221 // Take the address of the field references for "from" and "to". We
8222 // directly construct UnaryOperators here because semantic analysis
8223 // does not permit us to take the address of an xvalue.
8224 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8225 Context.getPointerType(From.get()->getType()),
8226 VK_RValue, OK_Ordinary, Loc);
8227 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8228 Context.getPointerType(To.get()->getType()),
8229 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008230
8231 bool NeedsCollectableMemCpy =
8232 (BaseType->isRecordType() &&
8233 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8234
8235 if (NeedsCollectableMemCpy) {
8236 if (!CollectableMemCpyRef) {
8237 // Create a reference to the __builtin_objc_memmove_collectable function.
8238 LookupResult R(*this,
8239 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8240 Loc, LookupOrdinaryName);
8241 LookupName(R, TUScope, true);
8242
8243 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8244 if (!CollectableMemCpy) {
8245 // Something went horribly wrong earlier, and we will have
8246 // complained about it.
8247 Invalid = true;
8248 continue;
8249 }
8250
8251 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8252 CollectableMemCpy->getType(),
8253 VK_LValue, Loc, 0).take();
8254 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8255 }
8256 }
8257 // Create a reference to the __builtin_memcpy builtin function.
8258 else if (!BuiltinMemCpyRef) {
8259 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8260 LookupOrdinaryName);
8261 LookupName(R, TUScope, true);
8262
8263 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8264 if (!BuiltinMemCpy) {
8265 // Something went horribly wrong earlier, and we will have complained
8266 // about it.
8267 Invalid = true;
8268 continue;
8269 }
8270
8271 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8272 BuiltinMemCpy->getType(),
8273 VK_LValue, Loc, 0).take();
8274 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8275 }
8276
8277 ASTOwningVector<Expr*> CallArgs(*this);
8278 CallArgs.push_back(To.takeAs<Expr>());
8279 CallArgs.push_back(From.takeAs<Expr>());
8280 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8281 ExprResult Call = ExprError();
8282 if (NeedsCollectableMemCpy)
8283 Call = ActOnCallExpr(/*Scope=*/0,
8284 CollectableMemCpyRef,
8285 Loc, move_arg(CallArgs),
8286 Loc);
8287 else
8288 Call = ActOnCallExpr(/*Scope=*/0,
8289 BuiltinMemCpyRef,
8290 Loc, move_arg(CallArgs),
8291 Loc);
8292
8293 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8294 Statements.push_back(Call.takeAs<Expr>());
8295 continue;
8296 }
8297
8298 // Build the move of this field.
8299 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8300 To.get(), From.get(),
8301 /*CopyingBaseSubobject=*/false,
8302 /*Copying=*/false);
8303 if (Move.isInvalid()) {
8304 Diag(CurrentLocation, diag::note_member_synthesized_at)
8305 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8306 MoveAssignOperator->setInvalidDecl();
8307 return;
8308 }
8309
8310 // Success! Record the copy.
8311 Statements.push_back(Move.takeAs<Stmt>());
8312 }
8313
8314 if (!Invalid) {
8315 // Add a "return *this;"
8316 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8317
8318 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8319 if (Return.isInvalid())
8320 Invalid = true;
8321 else {
8322 Statements.push_back(Return.takeAs<Stmt>());
8323
8324 if (Trap.hasErrorOccurred()) {
8325 Diag(CurrentLocation, diag::note_member_synthesized_at)
8326 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8327 Invalid = true;
8328 }
8329 }
8330 }
8331
8332 if (Invalid) {
8333 MoveAssignOperator->setInvalidDecl();
8334 return;
8335 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008336
8337 StmtResult Body;
8338 {
8339 CompoundScopeRAII CompoundScope(*this);
8340 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8341 /*isStmtExpr=*/false);
8342 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8343 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008344 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8345
8346 if (ASTMutationListener *L = getASTMutationListener()) {
8347 L->CompletedImplicitDefinition(MoveAssignOperator);
8348 }
8349}
8350
Sean Hunt49634cf2011-05-13 06:10:58 +00008351std::pair<Sema::ImplicitExceptionSpecification, bool>
8352Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008353 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00008354 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008355
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008356 // C++ [class.copy]p5:
8357 // The implicitly-declared copy constructor for a class X will
8358 // have the form
8359 //
8360 // X::X(const X&)
8361 //
8362 // if
Sean Huntc530d172011-06-10 04:44:37 +00008363 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008364 bool HasConstCopyConstructor = true;
8365
8366 // -- each direct or virtual base class B of X has a copy
8367 // constructor whose first parameter is of type const B& or
8368 // const volatile B&, and
8369 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8370 BaseEnd = ClassDecl->bases_end();
8371 HasConstCopyConstructor && Base != BaseEnd;
8372 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008373 // Virtual bases are handled below.
8374 if (Base->isVirtual())
8375 continue;
8376
Douglas Gregor22584312010-07-02 23:41:54 +00008377 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008378 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008379 HasConstCopyConstructor &=
8380 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor598a8542010-07-01 18:27:03 +00008381 }
8382
8383 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8384 BaseEnd = ClassDecl->vbases_end();
8385 HasConstCopyConstructor && Base != BaseEnd;
8386 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008387 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008389 HasConstCopyConstructor &=
8390 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008391 }
8392
8393 // -- for all the nonstatic data members of X that are of a
8394 // class type M (or array thereof), each such class type
8395 // has a copy constructor whose first parameter is of type
8396 // const M& or const volatile M&.
8397 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8398 FieldEnd = ClassDecl->field_end();
8399 HasConstCopyConstructor && Field != FieldEnd;
8400 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008401 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008402 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00008403 HasConstCopyConstructor &=
8404 (bool)LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008405 }
8406 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008407 // Otherwise, the implicitly declared copy constructor will have
8408 // the form
8409 //
8410 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008411
Douglas Gregor0d405db2010-07-01 20:59:04 +00008412 // C++ [except.spec]p14:
8413 // An implicitly declared special member function (Clause 12) shall have an
8414 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008415 ImplicitExceptionSpecification ExceptSpec(*this);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008416 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8417 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8418 BaseEnd = ClassDecl->bases_end();
8419 Base != BaseEnd;
8420 ++Base) {
8421 // Virtual bases are handled below.
8422 if (Base->isVirtual())
8423 continue;
8424
Douglas Gregor22584312010-07-02 23:41:54 +00008425 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008426 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008427 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008428 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008429 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008430 }
8431 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8432 BaseEnd = ClassDecl->vbases_end();
8433 Base != BaseEnd;
8434 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008435 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008436 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008437 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008438 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008439 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008440 }
8441 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8442 FieldEnd = ClassDecl->field_end();
8443 Field != FieldEnd;
8444 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008445 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008446 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8447 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008448 LookupCopyingConstructor(FieldClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008449 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008450 }
8451 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008452
Sean Hunt49634cf2011-05-13 06:10:58 +00008453 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8454}
8455
8456CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8457 CXXRecordDecl *ClassDecl) {
8458 // C++ [class.copy]p4:
8459 // If the class definition does not explicitly declare a copy
8460 // constructor, one is declared implicitly.
8461
Richard Smithe6975e92012-04-17 00:58:00 +00008462 ImplicitExceptionSpecification Spec(*this);
Sean Hunt49634cf2011-05-13 06:10:58 +00008463 bool Const;
8464 llvm::tie(Spec, Const) =
8465 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8466
8467 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8468 QualType ArgType = ClassType;
8469 if (Const)
8470 ArgType = ArgType.withConst();
8471 ArgType = Context.getLValueReferenceType(ArgType);
8472
8473 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8474
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008475 DeclarationName Name
8476 = Context.DeclarationNames.getCXXConstructorName(
8477 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008478 SourceLocation ClassLoc = ClassDecl->getLocation();
8479 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008480
8481 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008482 // member of its class.
8483 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8484 Context, ClassDecl, ClassLoc, NameInfo,
8485 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8486 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8487 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008488 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008489 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008490 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008491 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008492
Douglas Gregor22584312010-07-02 23:41:54 +00008493 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008494 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8495
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008496 // Add the parameter to the constructor.
8497 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008498 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008499 /*IdentifierInfo=*/0,
8500 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008501 SC_None,
8502 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008503 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008504
Douglas Gregor23c94db2010-07-02 17:43:08 +00008505 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008506 PushOnScopeChains(CopyConstructor, S, false);
8507 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008508
Nico Weberafcc96a2012-01-23 03:19:29 +00008509 // C++11 [class.copy]p8:
8510 // ... If the class definition does not explicitly declare a copy
8511 // constructor, there is no user-declared move constructor, and there is no
8512 // user-declared move assignment operator, a copy constructor is implicitly
8513 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008514 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008515 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008516
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008517 return CopyConstructor;
8518}
8519
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008520void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008521 CXXConstructorDecl *CopyConstructor) {
8522 assert((CopyConstructor->isDefaulted() &&
8523 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008524 !CopyConstructor->doesThisDeclarationHaveABody() &&
8525 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008526 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008527
Anders Carlsson63010a72010-04-23 16:24:12 +00008528 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008529 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008530
Douglas Gregor39957dc2010-05-01 15:04:51 +00008531 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008532 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008533
Sean Huntcbb67482011-01-08 20:30:50 +00008534 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008535 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008536 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008537 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008538 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008539 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008540 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008541 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8542 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008543 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008544 /*isStmtExpr=*/false)
8545 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008546 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008547 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008548
8549 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008550 if (ASTMutationListener *L = getASTMutationListener()) {
8551 L->CompletedImplicitDefinition(CopyConstructor);
8552 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008553}
8554
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008555Sema::ImplicitExceptionSpecification
8556Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8557 // C++ [except.spec]p14:
8558 // An implicitly declared special member function (Clause 12) shall have an
8559 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008560 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008561 if (ClassDecl->isInvalidDecl())
8562 return ExceptSpec;
8563
8564 // Direct base-class constructors.
8565 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8566 BEnd = ClassDecl->bases_end();
8567 B != BEnd; ++B) {
8568 if (B->isVirtual()) // Handled below.
8569 continue;
8570
8571 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8572 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8573 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8574 // If this is a deleted function, add it anyway. This might be conformant
8575 // with the standard. This might not. I'm not sure. It might not matter.
8576 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008577 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008578 }
8579 }
8580
8581 // Virtual base-class constructors.
8582 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8583 BEnd = ClassDecl->vbases_end();
8584 B != BEnd; ++B) {
8585 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8586 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8587 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8588 // If this is a deleted function, add it anyway. This might be conformant
8589 // with the standard. This might not. I'm not sure. It might not matter.
8590 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008591 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008592 }
8593 }
8594
8595 // Field constructors.
8596 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8597 FEnd = ClassDecl->field_end();
8598 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008599 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008600 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8601 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8602 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8603 // If this is a deleted function, add it anyway. This might be conformant
8604 // with the standard. This might not. I'm not sure. It might not matter.
8605 // In particular, the problem is that this function never gets called. It
8606 // might just be ill-formed because this function attempts to refer to
8607 // a deleted function here.
8608 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008609 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008610 }
8611 }
8612
8613 return ExceptSpec;
8614}
8615
8616CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8617 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008618 // C++11 [class.copy]p9:
8619 // If the definition of a class X does not explicitly declare a move
8620 // constructor, one will be implicitly declared as defaulted if and only if:
8621 //
8622 // - [first 4 bullets]
8623 assert(ClassDecl->needsImplicitMoveConstructor());
8624
8625 // [Checked after we build the declaration]
8626 // - the move assignment operator would not be implicitly defined as
8627 // deleted,
8628
8629 // [DR1402]:
8630 // - each of X's non-static data members and direct or virtual base classes
8631 // has a type that either has a move constructor or is trivially copyable.
8632 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8633 ClassDecl->setFailedImplicitMoveConstructor();
8634 return 0;
8635 }
8636
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008637 ImplicitExceptionSpecification Spec(
8638 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8639
8640 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8641 QualType ArgType = Context.getRValueReferenceType(ClassType);
8642
8643 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8644
8645 DeclarationName Name
8646 = Context.DeclarationNames.getCXXConstructorName(
8647 Context.getCanonicalType(ClassType));
8648 SourceLocation ClassLoc = ClassDecl->getLocation();
8649 DeclarationNameInfo NameInfo(Name, ClassLoc);
8650
8651 // C++0x [class.copy]p11:
8652 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008653 // member of its class.
8654 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8655 Context, ClassDecl, ClassLoc, NameInfo,
8656 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8657 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8658 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008659 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008660 MoveConstructor->setAccess(AS_public);
8661 MoveConstructor->setDefaulted();
8662 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008663
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008664 // Add the parameter to the constructor.
8665 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8666 ClassLoc, ClassLoc,
8667 /*IdentifierInfo=*/0,
8668 ArgType, /*TInfo=*/0,
8669 SC_None,
8670 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008671 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008672
8673 // C++0x [class.copy]p9:
8674 // If the definition of a class X does not explicitly declare a move
8675 // constructor, one will be implicitly declared as defaulted if and only if:
8676 // [...]
8677 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008678 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008679 // Cache this result so that we don't try to generate this over and over
8680 // on every lookup, leaking memory and wasting time.
8681 ClassDecl->setFailedImplicitMoveConstructor();
8682 return 0;
8683 }
8684
8685 // Note that we have declared this constructor.
8686 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8687
8688 if (Scope *S = getScopeForContext(ClassDecl))
8689 PushOnScopeChains(MoveConstructor, S, false);
8690 ClassDecl->addDecl(MoveConstructor);
8691
8692 return MoveConstructor;
8693}
8694
8695void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8696 CXXConstructorDecl *MoveConstructor) {
8697 assert((MoveConstructor->isDefaulted() &&
8698 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008699 !MoveConstructor->doesThisDeclarationHaveABody() &&
8700 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008701 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8702
8703 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8704 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8705
8706 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8707 DiagnosticErrorTrap Trap(Diags);
8708
8709 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8710 Trap.hasErrorOccurred()) {
8711 Diag(CurrentLocation, diag::note_member_synthesized_at)
8712 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8713 MoveConstructor->setInvalidDecl();
8714 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008715 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008716 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8717 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008718 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008719 /*isStmtExpr=*/false)
8720 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008721 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008722 }
8723
8724 MoveConstructor->setUsed();
8725
8726 if (ASTMutationListener *L = getASTMutationListener()) {
8727 L->CompletedImplicitDefinition(MoveConstructor);
8728 }
8729}
8730
Douglas Gregore4e68d42012-02-15 19:33:52 +00008731bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8732 return FD->isDeleted() &&
8733 (FD->isDefaulted() || FD->isImplicit()) &&
8734 isa<CXXMethodDecl>(FD);
8735}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008736
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008737/// \brief Mark the call operator of the given lambda closure type as "used".
8738static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8739 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008740 = cast<CXXMethodDecl>(
8741 *Lambda->lookup(
8742 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008743 CallOperator->setReferenced();
8744 CallOperator->setUsed();
8745}
8746
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008747void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8748 SourceLocation CurrentLocation,
8749 CXXConversionDecl *Conv)
8750{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008751 CXXRecordDecl *Lambda = Conv->getParent();
8752
8753 // Make sure that the lambda call operator is marked used.
8754 markLambdaCallOperatorUsed(*this, Lambda);
8755
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008756 Conv->setUsed();
8757
8758 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8759 DiagnosticErrorTrap Trap(Diags);
8760
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008761 // Return the address of the __invoke function.
8762 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8763 CXXMethodDecl *Invoke
8764 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8765 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8766 VK_LValue, Conv->getLocation()).take();
8767 assert(FunctionRef && "Can't refer to __invoke function?");
8768 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8769 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8770 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008771 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008772
8773 // Fill in the __invoke function with a dummy implementation. IR generation
8774 // will fill in the actual details.
8775 Invoke->setUsed();
8776 Invoke->setReferenced();
8777 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8778 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008779
8780 if (ASTMutationListener *L = getASTMutationListener()) {
8781 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008782 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008783 }
8784}
8785
8786void Sema::DefineImplicitLambdaToBlockPointerConversion(
8787 SourceLocation CurrentLocation,
8788 CXXConversionDecl *Conv)
8789{
8790 Conv->setUsed();
8791
8792 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8793 DiagnosticErrorTrap Trap(Diags);
8794
Douglas Gregorac1303e2012-02-22 05:02:47 +00008795 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008796 Expr *This = ActOnCXXThis(CurrentLocation).take();
8797 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008798
Eli Friedman23f02672012-03-01 04:01:32 +00008799 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8800 Conv->getLocation(),
8801 Conv, DerefThis);
8802
8803 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8804 // behavior. Note that only the general conversion function does this
8805 // (since it's unusable otherwise); in the case where we inline the
8806 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008807 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008808 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8809 CK_CopyAndAutoreleaseBlockObject,
8810 BuildBlock.get(), 0, VK_RValue);
8811
8812 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008813 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008814 Conv->setInvalidDecl();
8815 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008816 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008817
Douglas Gregorac1303e2012-02-22 05:02:47 +00008818 // Create the return statement that returns the block from the conversion
8819 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008820 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008821 if (Return.isInvalid()) {
8822 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8823 Conv->setInvalidDecl();
8824 return;
8825 }
8826
8827 // Set the body of the conversion function.
8828 Stmt *ReturnS = Return.take();
8829 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8830 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008831 Conv->getLocation()));
8832
Douglas Gregorac1303e2012-02-22 05:02:47 +00008833 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008834 if (ASTMutationListener *L = getASTMutationListener()) {
8835 L->CompletedImplicitDefinition(Conv);
8836 }
8837}
8838
Douglas Gregorf52757d2012-03-10 06:53:13 +00008839/// \brief Determine whether the given list arguments contains exactly one
8840/// "real" (non-default) argument.
8841static bool hasOneRealArgument(MultiExprArg Args) {
8842 switch (Args.size()) {
8843 case 0:
8844 return false;
8845
8846 default:
8847 if (!Args.get()[1]->isDefaultArgument())
8848 return false;
8849
8850 // fall through
8851 case 1:
8852 return !Args.get()[0]->isDefaultArgument();
8853 }
8854
8855 return false;
8856}
8857
John McCall60d7b3a2010-08-24 06:29:42 +00008858ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008859Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008860 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008861 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008862 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008863 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008864 unsigned ConstructKind,
8865 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008866 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008867
Douglas Gregor2f599792010-04-02 18:24:57 +00008868 // C++0x [class.copy]p34:
8869 // When certain criteria are met, an implementation is allowed to
8870 // omit the copy/move construction of a class object, even if the
8871 // copy/move constructor and/or destructor for the object have
8872 // side effects. [...]
8873 // - when a temporary class object that has not been bound to a
8874 // reference (12.2) would be copied/moved to a class object
8875 // with the same cv-unqualified type, the copy/move operation
8876 // can be omitted by constructing the temporary object
8877 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008878 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00008879 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008880 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008881 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008882 }
Mike Stump1eb44332009-09-09 15:08:12 +00008883
8884 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008885 Elidable, move(ExprArgs), HadMultipleCandidates,
8886 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008887}
8888
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008889/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8890/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008891ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008892Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8893 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008894 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008895 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008896 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008897 unsigned ConstructKind,
8898 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008899 unsigned NumExprs = ExprArgs.size();
8900 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008901
Nick Lewycky909a70d2011-03-25 01:44:32 +00008902 for (specific_attr_iterator<NonNullAttr>
8903 i = Constructor->specific_attr_begin<NonNullAttr>(),
8904 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8905 const NonNullAttr *NonNull = *i;
8906 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8907 }
8908
Eli Friedman5f2987c2012-02-02 03:46:19 +00008909 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008910 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008911 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008912 HadMultipleCandidates, /*FIXME*/false,
8913 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008914 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8915 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008916}
8917
Mike Stump1eb44332009-09-09 15:08:12 +00008918bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008919 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008920 MultiExprArg Exprs,
8921 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008922 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008923 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008924 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008925 move(Exprs), HadMultipleCandidates, false,
8926 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008927 if (TempResult.isInvalid())
8928 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008929
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008930 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008931 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00008932 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008933 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008934 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008935
Anders Carlssonfe2de492009-08-25 05:18:00 +00008936 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008937}
8938
John McCall68c6c9a2010-02-02 09:10:11 +00008939void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008940 if (VD->isInvalidDecl()) return;
8941
John McCall68c6c9a2010-02-02 09:10:11 +00008942 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008943 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00008944 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008945 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008946
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008947 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00008948 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008949 CheckDestructorAccess(VD->getLocation(), Destructor,
8950 PDiag(diag::err_access_dtor_var)
8951 << VD->getDeclName()
8952 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00008953 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008954
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008955 if (!VD->hasGlobalStorage()) return;
8956
8957 // Emit warning for non-trivial dtor in global scope (a real global,
8958 // class-static, function-static).
8959 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8960
8961 // TODO: this should be re-enabled for static locals by !CXAAtExit
8962 if (!VD->isStaticLocal())
8963 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008964}
8965
Douglas Gregor39da0b82009-09-09 23:08:42 +00008966/// \brief Given a constructor and the set of arguments provided for the
8967/// constructor, convert the arguments and add any required default arguments
8968/// to form a proper call to this constructor.
8969///
8970/// \returns true if an error occurred, false otherwise.
8971bool
8972Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8973 MultiExprArg ArgsPtr,
8974 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00008975 ASTOwningVector<Expr*> &ConvertedArgs,
8976 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008977 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8978 unsigned NumArgs = ArgsPtr.size();
8979 Expr **Args = (Expr **)ArgsPtr.get();
8980
8981 const FunctionProtoType *Proto
8982 = Constructor->getType()->getAs<FunctionProtoType>();
8983 assert(Proto && "Constructor without a prototype?");
8984 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008985
8986 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008987 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008988 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008989 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008990 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008991
8992 VariadicCallType CallType =
8993 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008994 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008995 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8996 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00008997 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00008998 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00008999
9000 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9001
9002 // FIXME: Missing call to CheckFunctionCall or equivalent
9003
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009004 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009005}
9006
Anders Carlsson20d45d22009-12-12 00:32:00 +00009007static inline bool
9008CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9009 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009010 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009011 if (isa<NamespaceDecl>(DC)) {
9012 return SemaRef.Diag(FnDecl->getLocation(),
9013 diag::err_operator_new_delete_declared_in_namespace)
9014 << FnDecl->getDeclName();
9015 }
9016
9017 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009018 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009019 return SemaRef.Diag(FnDecl->getLocation(),
9020 diag::err_operator_new_delete_declared_static)
9021 << FnDecl->getDeclName();
9022 }
9023
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009024 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009025}
9026
Anders Carlsson156c78e2009-12-13 17:53:43 +00009027static inline bool
9028CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9029 CanQualType ExpectedResultType,
9030 CanQualType ExpectedFirstParamType,
9031 unsigned DependentParamTypeDiag,
9032 unsigned InvalidParamTypeDiag) {
9033 QualType ResultType =
9034 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9035
9036 // Check that the result type is not dependent.
9037 if (ResultType->isDependentType())
9038 return SemaRef.Diag(FnDecl->getLocation(),
9039 diag::err_operator_new_delete_dependent_result_type)
9040 << FnDecl->getDeclName() << ExpectedResultType;
9041
9042 // Check that the result type is what we expect.
9043 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9044 return SemaRef.Diag(FnDecl->getLocation(),
9045 diag::err_operator_new_delete_invalid_result_type)
9046 << FnDecl->getDeclName() << ExpectedResultType;
9047
9048 // A function template must have at least 2 parameters.
9049 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9050 return SemaRef.Diag(FnDecl->getLocation(),
9051 diag::err_operator_new_delete_template_too_few_parameters)
9052 << FnDecl->getDeclName();
9053
9054 // The function decl must have at least 1 parameter.
9055 if (FnDecl->getNumParams() == 0)
9056 return SemaRef.Diag(FnDecl->getLocation(),
9057 diag::err_operator_new_delete_too_few_parameters)
9058 << FnDecl->getDeclName();
9059
9060 // Check the the first parameter type is not dependent.
9061 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9062 if (FirstParamType->isDependentType())
9063 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9064 << FnDecl->getDeclName() << ExpectedFirstParamType;
9065
9066 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009067 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009068 ExpectedFirstParamType)
9069 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9070 << FnDecl->getDeclName() << ExpectedFirstParamType;
9071
9072 return false;
9073}
9074
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009075static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009076CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009077 // C++ [basic.stc.dynamic.allocation]p1:
9078 // A program is ill-formed if an allocation function is declared in a
9079 // namespace scope other than global scope or declared static in global
9080 // scope.
9081 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9082 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009083
9084 CanQualType SizeTy =
9085 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9086
9087 // C++ [basic.stc.dynamic.allocation]p1:
9088 // The return type shall be void*. The first parameter shall have type
9089 // std::size_t.
9090 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9091 SizeTy,
9092 diag::err_operator_new_dependent_param_type,
9093 diag::err_operator_new_param_type))
9094 return true;
9095
9096 // C++ [basic.stc.dynamic.allocation]p1:
9097 // The first parameter shall not have an associated default argument.
9098 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009099 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009100 diag::err_operator_new_default_arg)
9101 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9102
9103 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009104}
9105
9106static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009107CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9108 // C++ [basic.stc.dynamic.deallocation]p1:
9109 // A program is ill-formed if deallocation functions are declared in a
9110 // namespace scope other than global scope or declared static in global
9111 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009112 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9113 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009114
9115 // C++ [basic.stc.dynamic.deallocation]p2:
9116 // Each deallocation function shall return void and its first parameter
9117 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009118 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9119 SemaRef.Context.VoidPtrTy,
9120 diag::err_operator_delete_dependent_param_type,
9121 diag::err_operator_delete_param_type))
9122 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009123
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009124 return false;
9125}
9126
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009127/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9128/// of this overloaded operator is well-formed. If so, returns false;
9129/// otherwise, emits appropriate diagnostics and returns true.
9130bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009131 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009132 "Expected an overloaded operator declaration");
9133
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009134 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9135
Mike Stump1eb44332009-09-09 15:08:12 +00009136 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009137 // The allocation and deallocation functions, operator new,
9138 // operator new[], operator delete and operator delete[], are
9139 // described completely in 3.7.3. The attributes and restrictions
9140 // found in the rest of this subclause do not apply to them unless
9141 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009142 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009143 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009144
Anders Carlssona3ccda52009-12-12 00:26:23 +00009145 if (Op == OO_New || Op == OO_Array_New)
9146 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009147
9148 // C++ [over.oper]p6:
9149 // An operator function shall either be a non-static member
9150 // function or be a non-member function and have at least one
9151 // parameter whose type is a class, a reference to a class, an
9152 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009153 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9154 if (MethodDecl->isStatic())
9155 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009156 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009157 } else {
9158 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009159 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9160 ParamEnd = FnDecl->param_end();
9161 Param != ParamEnd; ++Param) {
9162 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009163 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9164 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009165 ClassOrEnumParam = true;
9166 break;
9167 }
9168 }
9169
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009170 if (!ClassOrEnumParam)
9171 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009172 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009173 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009174 }
9175
9176 // C++ [over.oper]p8:
9177 // An operator function cannot have default arguments (8.3.6),
9178 // except where explicitly stated below.
9179 //
Mike Stump1eb44332009-09-09 15:08:12 +00009180 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009181 // (C++ [over.call]p1).
9182 if (Op != OO_Call) {
9183 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9184 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009185 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009186 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009187 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009188 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009189 }
9190 }
9191
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009192 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9193 { false, false, false }
9194#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9195 , { Unary, Binary, MemberOnly }
9196#include "clang/Basic/OperatorKinds.def"
9197 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009198
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009199 bool CanBeUnaryOperator = OperatorUses[Op][0];
9200 bool CanBeBinaryOperator = OperatorUses[Op][1];
9201 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009202
9203 // C++ [over.oper]p8:
9204 // [...] Operator functions cannot have more or fewer parameters
9205 // than the number required for the corresponding operator, as
9206 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009207 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009208 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009209 if (Op != OO_Call &&
9210 ((NumParams == 1 && !CanBeUnaryOperator) ||
9211 (NumParams == 2 && !CanBeBinaryOperator) ||
9212 (NumParams < 1) || (NumParams > 2))) {
9213 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009214 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009215 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009216 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009217 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009218 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009219 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009220 assert(CanBeBinaryOperator &&
9221 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009222 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009223 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009224
Chris Lattner416e46f2008-11-21 07:57:12 +00009225 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009226 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009227 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009228
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009229 // Overloaded operators other than operator() cannot be variadic.
9230 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009231 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009232 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009233 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009234 }
9235
9236 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009237 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9238 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009239 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009240 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009241 }
9242
9243 // C++ [over.inc]p1:
9244 // The user-defined function called operator++ implements the
9245 // prefix and postfix ++ operator. If this function is a member
9246 // function with no parameters, or a non-member function with one
9247 // parameter of class or enumeration type, it defines the prefix
9248 // increment operator ++ for objects of that type. If the function
9249 // is a member function with one parameter (which shall be of type
9250 // int) or a non-member function with two parameters (the second
9251 // of which shall be of type int), it defines the postfix
9252 // increment operator ++ for objects of that type.
9253 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9254 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9255 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009256 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009257 ParamIsInt = BT->getKind() == BuiltinType::Int;
9258
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009259 if (!ParamIsInt)
9260 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009261 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009262 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009263 }
9264
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009265 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009266}
Chris Lattner5a003a42008-12-17 07:09:26 +00009267
Sean Hunta6c058d2010-01-13 09:01:02 +00009268/// CheckLiteralOperatorDeclaration - Check whether the declaration
9269/// of this literal operator function is well-formed. If so, returns
9270/// false; otherwise, emits appropriate diagnostics and returns true.
9271bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009272 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009273 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9274 << FnDecl->getDeclName();
9275 return true;
9276 }
9277
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009278 if (FnDecl->isExternC()) {
9279 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9280 return true;
9281 }
9282
Sean Hunta6c058d2010-01-13 09:01:02 +00009283 bool Valid = false;
9284
Richard Smith36f5cfe2012-03-09 08:00:36 +00009285 // This might be the definition of a literal operator template.
9286 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9287 // This might be a specialization of a literal operator template.
9288 if (!TpDecl)
9289 TpDecl = FnDecl->getPrimaryTemplate();
9290
Sean Hunt216c2782010-04-07 23:11:06 +00009291 // template <char...> type operator "" name() is the only valid template
9292 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009293 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009294 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009295 // Must have only one template parameter
9296 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9297 if (Params->size() == 1) {
9298 NonTypeTemplateParmDecl *PmDecl =
9299 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009300
Sean Hunt216c2782010-04-07 23:11:06 +00009301 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009302 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9303 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9304 Valid = true;
9305 }
9306 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009307 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009308 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009309 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9310
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009311 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009312
Sean Hunt30019c02010-04-07 22:57:35 +00009313 // unsigned long long int, long double, and any character type are allowed
9314 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009315 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9316 Context.hasSameType(T, Context.LongDoubleTy) ||
9317 Context.hasSameType(T, Context.CharTy) ||
9318 Context.hasSameType(T, Context.WCharTy) ||
9319 Context.hasSameType(T, Context.Char16Ty) ||
9320 Context.hasSameType(T, Context.Char32Ty)) {
9321 if (++Param == FnDecl->param_end())
9322 Valid = true;
9323 goto FinishedParams;
9324 }
9325
Sean Hunt30019c02010-04-07 22:57:35 +00009326 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009327 const PointerType *PT = T->getAs<PointerType>();
9328 if (!PT)
9329 goto FinishedParams;
9330 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009331 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009332 goto FinishedParams;
9333 T = T.getUnqualifiedType();
9334
9335 // Move on to the second parameter;
9336 ++Param;
9337
9338 // If there is no second parameter, the first must be a const char *
9339 if (Param == FnDecl->param_end()) {
9340 if (Context.hasSameType(T, Context.CharTy))
9341 Valid = true;
9342 goto FinishedParams;
9343 }
9344
9345 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9346 // are allowed as the first parameter to a two-parameter function
9347 if (!(Context.hasSameType(T, Context.CharTy) ||
9348 Context.hasSameType(T, Context.WCharTy) ||
9349 Context.hasSameType(T, Context.Char16Ty) ||
9350 Context.hasSameType(T, Context.Char32Ty)))
9351 goto FinishedParams;
9352
9353 // The second and final parameter must be an std::size_t
9354 T = (*Param)->getType().getUnqualifiedType();
9355 if (Context.hasSameType(T, Context.getSizeType()) &&
9356 ++Param == FnDecl->param_end())
9357 Valid = true;
9358 }
9359
9360 // FIXME: This diagnostic is absolutely terrible.
9361FinishedParams:
9362 if (!Valid) {
9363 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9364 << FnDecl->getDeclName();
9365 return true;
9366 }
9367
Richard Smitha9e88b22012-03-09 08:16:22 +00009368 // A parameter-declaration-clause containing a default argument is not
9369 // equivalent to any of the permitted forms.
9370 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9371 ParamEnd = FnDecl->param_end();
9372 Param != ParamEnd; ++Param) {
9373 if ((*Param)->hasDefaultArg()) {
9374 Diag((*Param)->getDefaultArgRange().getBegin(),
9375 diag::err_literal_operator_default_argument)
9376 << (*Param)->getDefaultArgRange();
9377 break;
9378 }
9379 }
9380
Richard Smith2fb4ae32012-03-08 02:39:21 +00009381 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009382 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9383 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009384 // C++11 [usrlit.suffix]p1:
9385 // Literal suffix identifiers that do not start with an underscore
9386 // are reserved for future standardization.
9387 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009388 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009389
Sean Hunta6c058d2010-01-13 09:01:02 +00009390 return false;
9391}
9392
Douglas Gregor074149e2009-01-05 19:45:36 +00009393/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9394/// linkage specification, including the language and (if present)
9395/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9396/// the location of the language string literal, which is provided
9397/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9398/// the '{' brace. Otherwise, this linkage specification does not
9399/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009400Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9401 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009402 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009403 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009404 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009405 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009406 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009407 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009408 Language = LinkageSpecDecl::lang_cxx;
9409 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009410 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009411 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009412 }
Mike Stump1eb44332009-09-09 15:08:12 +00009413
Chris Lattnercc98eac2008-12-17 07:13:27 +00009414 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009415
Douglas Gregor074149e2009-01-05 19:45:36 +00009416 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009417 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009418 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009419 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009420 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009421}
9422
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009423/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009424/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9425/// valid, it's the position of the closing '}' brace in a linkage
9426/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009427Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009428 Decl *LinkageSpec,
9429 SourceLocation RBraceLoc) {
9430 if (LinkageSpec) {
9431 if (RBraceLoc.isValid()) {
9432 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9433 LSDecl->setRBraceLoc(RBraceLoc);
9434 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009435 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009436 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009437 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009438}
9439
Douglas Gregord308e622009-05-18 20:51:54 +00009440/// \brief Perform semantic analysis for the variable declaration that
9441/// occurs within a C++ catch clause, returning the newly-created
9442/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009443VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009444 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009445 SourceLocation StartLoc,
9446 SourceLocation Loc,
9447 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009448 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009449 QualType ExDeclType = TInfo->getType();
9450
Sebastian Redl4b07b292008-12-22 19:15:10 +00009451 // Arrays and functions decay.
9452 if (ExDeclType->isArrayType())
9453 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9454 else if (ExDeclType->isFunctionType())
9455 ExDeclType = Context.getPointerType(ExDeclType);
9456
9457 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9458 // The exception-declaration shall not denote a pointer or reference to an
9459 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009460 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009461 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009462 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009463 Invalid = true;
9464 }
Douglas Gregord308e622009-05-18 20:51:54 +00009465
Sebastian Redl4b07b292008-12-22 19:15:10 +00009466 QualType BaseType = ExDeclType;
9467 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009468 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009469 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009470 BaseType = Ptr->getPointeeType();
9471 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009472 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009473 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009474 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009475 BaseType = Ref->getPointeeType();
9476 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009477 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009478 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009479 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009480 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009481 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009482
Mike Stump1eb44332009-09-09 15:08:12 +00009483 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009484 RequireNonAbstractType(Loc, ExDeclType,
9485 diag::err_abstract_type_in_decl,
9486 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009487 Invalid = true;
9488
John McCall5a180392010-07-24 00:37:23 +00009489 // Only the non-fragile NeXT runtime currently supports C++ catches
9490 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009491 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009492 QualType T = ExDeclType;
9493 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9494 T = RT->getPointeeType();
9495
9496 if (T->isObjCObjectType()) {
9497 Diag(Loc, diag::err_objc_object_catch);
9498 Invalid = true;
9499 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009500 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009501 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009502 }
9503 }
9504
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009505 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9506 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009507 ExDecl->setExceptionVariable(true);
9508
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009509 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009510 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009511 Invalid = true;
9512
Douglas Gregorc41b8782011-07-06 18:14:43 +00009513 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009514 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009515 // C++ [except.handle]p16:
9516 // The object declared in an exception-declaration or, if the
9517 // exception-declaration does not specify a name, a temporary (12.2) is
9518 // copy-initialized (8.5) from the exception object. [...]
9519 // The object is destroyed when the handler exits, after the destruction
9520 // of any automatic objects initialized within the handler.
9521 //
9522 // We just pretend to initialize the object with itself, then make sure
9523 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009524 QualType initType = ExDeclType;
9525
9526 InitializedEntity entity =
9527 InitializedEntity::InitializeVariable(ExDecl);
9528 InitializationKind initKind =
9529 InitializationKind::CreateCopy(Loc, SourceLocation());
9530
9531 Expr *opaqueValue =
9532 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9533 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9534 ExprResult result = sequence.Perform(*this, entity, initKind,
9535 MultiExprArg(&opaqueValue, 1));
9536 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009537 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009538 else {
9539 // If the constructor used was non-trivial, set this as the
9540 // "initializer".
9541 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9542 if (!construct->getConstructor()->isTrivial()) {
9543 Expr *init = MaybeCreateExprWithCleanups(construct);
9544 ExDecl->setInit(init);
9545 }
9546
9547 // And make sure it's destructable.
9548 FinalizeVarWithDestructor(ExDecl, recordType);
9549 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009550 }
9551 }
9552
Douglas Gregord308e622009-05-18 20:51:54 +00009553 if (Invalid)
9554 ExDecl->setInvalidDecl();
9555
9556 return ExDecl;
9557}
9558
9559/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9560/// handler.
John McCalld226f652010-08-21 09:40:31 +00009561Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009562 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009563 bool Invalid = D.isInvalidType();
9564
9565 // Check for unexpanded parameter packs.
9566 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9567 UPPC_ExceptionType)) {
9568 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9569 D.getIdentifierLoc());
9570 Invalid = true;
9571 }
9572
Sebastian Redl4b07b292008-12-22 19:15:10 +00009573 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009574 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009575 LookupOrdinaryName,
9576 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009577 // The scope should be freshly made just for us. There is just no way
9578 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009579 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009580 if (PrevDecl->isTemplateParameter()) {
9581 // Maybe we will complain about the shadowed template parameter.
9582 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009583 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009584 }
9585 }
9586
Chris Lattnereaaebc72009-04-25 08:06:05 +00009587 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009588 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9589 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009590 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009591 }
9592
Douglas Gregor83cb9422010-09-09 17:09:21 +00009593 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009594 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009595 D.getIdentifierLoc(),
9596 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009597 if (Invalid)
9598 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009599
Sebastian Redl4b07b292008-12-22 19:15:10 +00009600 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009601 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009602 PushOnScopeChains(ExDecl, S);
9603 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009604 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009605
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009606 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009607 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009608}
Anders Carlssonfb311762009-03-14 00:25:26 +00009609
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009610Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009611 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009612 Expr *AssertMessageExpr_,
9613 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009614 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009615
Anders Carlssonc3082412009-03-14 00:33:21 +00009616 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009617 // In a static_assert-declaration, the constant-expression shall be a
9618 // constant expression that can be contextually converted to bool.
9619 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9620 if (Converted.isInvalid())
9621 return 0;
9622
Richard Smithdaaefc52011-12-14 23:32:26 +00009623 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009624 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009625 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009626 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009627 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009628
Richard Smith0cc323c2012-03-05 23:20:05 +00009629 if (!Cond) {
9630 llvm::SmallString<256> MsgBuffer;
9631 llvm::raw_svector_ostream Msg(MsgBuffer);
9632 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009633 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009634 << Msg.str() << AssertExpr->getSourceRange();
9635 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009636 }
Mike Stump1eb44332009-09-09 15:08:12 +00009637
Douglas Gregor399ad972010-12-15 23:55:21 +00009638 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9639 return 0;
9640
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009641 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9642 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009643
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009644 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009645 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009646}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009647
Douglas Gregor1d869352010-04-07 16:53:43 +00009648/// \brief Perform semantic analysis of the given friend type declaration.
9649///
9650/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009651FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9652 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009653 TypeSourceInfo *TSInfo) {
9654 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9655
9656 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009657 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009658
Richard Smith6b130222011-10-18 21:39:00 +00009659 // C++03 [class.friend]p2:
9660 // An elaborated-type-specifier shall be used in a friend declaration
9661 // for a class.*
9662 //
9663 // * The class-key of the elaborated-type-specifier is required.
9664 if (!ActiveTemplateInstantiations.empty()) {
9665 // Do not complain about the form of friend template types during
9666 // template instantiation; we will already have complained when the
9667 // template was declared.
9668 } else if (!T->isElaboratedTypeSpecifier()) {
9669 // If we evaluated the type to a record type, suggest putting
9670 // a tag in front.
9671 if (const RecordType *RT = T->getAs<RecordType>()) {
9672 RecordDecl *RD = RT->getDecl();
9673
9674 std::string InsertionText = std::string(" ") + RD->getKindName();
9675
9676 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009677 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009678 diag::warn_cxx98_compat_unelaborated_friend_type :
9679 diag::ext_unelaborated_friend_type)
9680 << (unsigned) RD->getTagKind()
9681 << T
9682 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9683 InsertionText);
9684 } else {
9685 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009686 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009687 diag::warn_cxx98_compat_nonclass_type_friend :
9688 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009689 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009690 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009691 }
Richard Smith6b130222011-10-18 21:39:00 +00009692 } else if (T->getAs<EnumType>()) {
9693 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009694 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009695 diag::warn_cxx98_compat_enum_friend :
9696 diag::ext_enum_friend)
9697 << T
9698 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009699 }
9700
Douglas Gregor06245bf2010-04-07 17:57:12 +00009701 // C++0x [class.friend]p3:
9702 // If the type specifier in a friend declaration designates a (possibly
9703 // cv-qualified) class type, that class is declared as a friend; otherwise,
9704 // the friend declaration is ignored.
9705
9706 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9707 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009708
Abramo Bagnara0216df82011-10-29 20:52:52 +00009709 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009710}
9711
John McCall9a34edb2010-10-19 01:40:49 +00009712/// Handle a friend tag declaration where the scope specifier was
9713/// templated.
9714Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9715 unsigned TagSpec, SourceLocation TagLoc,
9716 CXXScopeSpec &SS,
9717 IdentifierInfo *Name, SourceLocation NameLoc,
9718 AttributeList *Attr,
9719 MultiTemplateParamsArg TempParamLists) {
9720 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9721
9722 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009723 bool Invalid = false;
9724
9725 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009726 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009727 TempParamLists.get(),
9728 TempParamLists.size(),
9729 /*friend*/ true,
9730 isExplicitSpecialization,
9731 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009732 if (TemplateParams->size() > 0) {
9733 // This is a declaration of a class template.
9734 if (Invalid)
9735 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009736
Eric Christopher4110e132011-07-21 05:34:24 +00009737 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9738 SS, Name, NameLoc, Attr,
9739 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009740 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009741 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009742 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009743 } else {
9744 // The "template<>" header is extraneous.
9745 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9746 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9747 isExplicitSpecialization = true;
9748 }
9749 }
9750
9751 if (Invalid) return 0;
9752
John McCall9a34edb2010-10-19 01:40:49 +00009753 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009754 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009755 if (TempParamLists.get()[I]->size()) {
9756 isAllExplicitSpecializations = false;
9757 break;
9758 }
9759 }
9760
9761 // FIXME: don't ignore attributes.
9762
9763 // If it's explicit specializations all the way down, just forget
9764 // about the template header and build an appropriate non-templated
9765 // friend. TODO: for source fidelity, remember the headers.
9766 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009767 if (SS.isEmpty()) {
9768 bool Owned = false;
9769 bool IsDependent = false;
9770 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9771 Attr, AS_public,
9772 /*ModulePrivateLoc=*/SourceLocation(),
9773 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009774 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009775 /*ScopedEnumUsesClassTag=*/false,
9776 /*UnderlyingType=*/TypeResult());
9777 }
9778
Douglas Gregor2494dd02011-03-01 01:34:45 +00009779 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009780 ElaboratedTypeKeyword Keyword
9781 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009782 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009783 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009784 if (T.isNull())
9785 return 0;
9786
9787 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9788 if (isa<DependentNameType>(T)) {
9789 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009790 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009791 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009792 TL.setNameLoc(NameLoc);
9793 } else {
9794 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009795 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009796 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009797 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9798 }
9799
9800 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9801 TSI, FriendLoc);
9802 Friend->setAccess(AS_public);
9803 CurContext->addDecl(Friend);
9804 return Friend;
9805 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009806
9807 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9808
9809
John McCall9a34edb2010-10-19 01:40:49 +00009810
9811 // Handle the case of a templated-scope friend class. e.g.
9812 // template <class T> class A<T>::B;
9813 // FIXME: we don't support these right now.
9814 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9815 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9816 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9817 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009818 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009819 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009820 TL.setNameLoc(NameLoc);
9821
9822 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9823 TSI, FriendLoc);
9824 Friend->setAccess(AS_public);
9825 Friend->setUnsupportedFriend(true);
9826 CurContext->addDecl(Friend);
9827 return Friend;
9828}
9829
9830
John McCalldd4a3b02009-09-16 22:47:08 +00009831/// Handle a friend type declaration. This works in tandem with
9832/// ActOnTag.
9833///
9834/// Notes on friend class templates:
9835///
9836/// We generally treat friend class declarations as if they were
9837/// declaring a class. So, for example, the elaborated type specifier
9838/// in a friend declaration is required to obey the restrictions of a
9839/// class-head (i.e. no typedefs in the scope chain), template
9840/// parameters are required to match up with simple template-ids, &c.
9841/// However, unlike when declaring a template specialization, it's
9842/// okay to refer to a template specialization without an empty
9843/// template parameter declaration, e.g.
9844/// friend class A<T>::B<unsigned>;
9845/// We permit this as a special case; if there are any template
9846/// parameters present at all, require proper matching, i.e.
9847/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009848Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009849 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009850 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009851
9852 assert(DS.isFriendSpecified());
9853 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9854
John McCalldd4a3b02009-09-16 22:47:08 +00009855 // Try to convert the decl specifier to a type. This works for
9856 // friend templates because ActOnTag never produces a ClassTemplateDecl
9857 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009858 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009859 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9860 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009861 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009862 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009863
Douglas Gregor6ccab972010-12-16 01:14:37 +00009864 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9865 return 0;
9866
John McCalldd4a3b02009-09-16 22:47:08 +00009867 // This is definitely an error in C++98. It's probably meant to
9868 // be forbidden in C++0x, too, but the specification is just
9869 // poorly written.
9870 //
9871 // The problem is with declarations like the following:
9872 // template <T> friend A<T>::foo;
9873 // where deciding whether a class C is a friend or not now hinges
9874 // on whether there exists an instantiation of A that causes
9875 // 'foo' to equal C. There are restrictions on class-heads
9876 // (which we declare (by fiat) elaborated friend declarations to
9877 // be) that makes this tractable.
9878 //
9879 // FIXME: handle "template <> friend class A<T>;", which
9880 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009881 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009882 Diag(Loc, diag::err_tagless_friend_type_template)
9883 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009884 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009885 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009886
John McCall02cace72009-08-28 07:59:38 +00009887 // C++98 [class.friend]p1: A friend of a class is a function
9888 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009889 // This is fixed in DR77, which just barely didn't make the C++03
9890 // deadline. It's also a very silly restriction that seriously
9891 // affects inner classes and which nobody else seems to implement;
9892 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009893 //
9894 // But note that we could warn about it: it's always useless to
9895 // friend one of your own members (it's not, however, worthless to
9896 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009897
John McCalldd4a3b02009-09-16 22:47:08 +00009898 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009899 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009900 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009901 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009902 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009903 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009904 DS.getFriendSpecLoc());
9905 else
Abramo Bagnara0216df82011-10-29 20:52:52 +00009906 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +00009907
9908 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009909 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009910
John McCalldd4a3b02009-09-16 22:47:08 +00009911 D->setAccess(AS_public);
9912 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009913
John McCalld226f652010-08-21 09:40:31 +00009914 return D;
John McCall02cace72009-08-28 07:59:38 +00009915}
9916
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009917Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +00009918 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009919 const DeclSpec &DS = D.getDeclSpec();
9920
9921 assert(DS.isFriendSpecified());
9922 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9923
9924 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009925 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +00009926
9927 // C++ [class.friend]p1
9928 // A friend of a class is a function or class....
9929 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009930 // It *doesn't* see through dependent types, which is correct
9931 // according to [temp.arg.type]p3:
9932 // If a declaration acquires a function type through a
9933 // type dependent on a template-parameter and this causes
9934 // a declaration that does not use the syntactic form of a
9935 // function declarator to have a function type, the program
9936 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009937 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +00009938 Diag(Loc, diag::err_unexpected_friend);
9939
9940 // It might be worthwhile to try to recover by creating an
9941 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009942 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009943 }
9944
9945 // C++ [namespace.memdef]p3
9946 // - If a friend declaration in a non-local class first declares a
9947 // class or function, the friend class or function is a member
9948 // of the innermost enclosing namespace.
9949 // - The name of the friend is not found by simple name lookup
9950 // until a matching declaration is provided in that namespace
9951 // scope (either before or after the class declaration granting
9952 // friendship).
9953 // - If a friend function is called, its name may be found by the
9954 // name lookup that considers functions from namespaces and
9955 // classes associated with the types of the function arguments.
9956 // - When looking for a prior declaration of a class or a function
9957 // declared as a friend, scopes outside the innermost enclosing
9958 // namespace scope are not considered.
9959
John McCall337ec3d2010-10-12 23:13:28 +00009960 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009961 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9962 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009963 assert(Name);
9964
Douglas Gregor6ccab972010-12-16 01:14:37 +00009965 // Check for unexpanded parameter packs.
9966 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9967 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9968 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9969 return 0;
9970
John McCall67d1a672009-08-06 02:15:43 +00009971 // The context we found the declaration in, or in which we should
9972 // create the declaration.
9973 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009974 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009975 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009976 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009977
John McCall337ec3d2010-10-12 23:13:28 +00009978 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009979
John McCall337ec3d2010-10-12 23:13:28 +00009980 // There are four cases here.
9981 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009982 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009983 // there as appropriate.
9984 // Recover from invalid scope qualifiers as if they just weren't there.
9985 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009986 // C++0x [namespace.memdef]p3:
9987 // If the name in a friend declaration is neither qualified nor
9988 // a template-id and the declaration is a function or an
9989 // elaborated-type-specifier, the lookup to determine whether
9990 // the entity has been previously declared shall not consider
9991 // any scopes outside the innermost enclosing namespace.
9992 // C++0x [class.friend]p11:
9993 // If a friend declaration appears in a local class and the name
9994 // specified is an unqualified name, a prior declaration is
9995 // looked up without considering scopes that are outside the
9996 // innermost enclosing non-class scope. For a friend function
9997 // declaration, if there is no prior declaration, the program is
9998 // ill-formed.
9999 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010000 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010001
John McCall29ae6e52010-10-13 05:45:15 +000010002 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010003 DC = CurContext;
10004 while (true) {
10005 // Skip class contexts. If someone can cite chapter and verse
10006 // for this behavior, that would be nice --- it's what GCC and
10007 // EDG do, and it seems like a reasonable intent, but the spec
10008 // really only says that checks for unqualified existing
10009 // declarations should stop at the nearest enclosing namespace,
10010 // not that they should only consider the nearest enclosing
10011 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010012 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010013 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010014
John McCall68263142009-11-18 22:49:29 +000010015 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010016
10017 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010018 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010019 break;
John McCall29ae6e52010-10-13 05:45:15 +000010020
John McCall8a407372010-10-14 22:22:28 +000010021 if (isTemplateId) {
10022 if (isa<TranslationUnitDecl>(DC)) break;
10023 } else {
10024 if (DC->isFileContext()) break;
10025 }
John McCall67d1a672009-08-06 02:15:43 +000010026 DC = DC->getParent();
10027 }
10028
10029 // C++ [class.friend]p1: A friend of a class is a function or
10030 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010031 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010032 // Most C++ 98 compilers do seem to give an error here, so
10033 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010034 if (!Previous.empty() && DC->Equals(CurContext))
10035 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010036 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010037 diag::warn_cxx98_compat_friend_is_member :
10038 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010039
John McCall380aaa42010-10-13 06:22:15 +000010040 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010041
Douglas Gregor883af832011-10-10 01:11:59 +000010042 // C++ [class.friend]p6:
10043 // A function can be defined in a friend declaration of a class if and
10044 // only if the class is a non-local class (9.8), the function name is
10045 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010046 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010047 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10048 }
10049
John McCall337ec3d2010-10-12 23:13:28 +000010050 // - There's a non-dependent scope specifier, in which case we
10051 // compute it and do a previous lookup there for a function
10052 // or function template.
10053 } else if (!SS.getScopeRep()->isDependent()) {
10054 DC = computeDeclContext(SS);
10055 if (!DC) return 0;
10056
10057 if (RequireCompleteDeclContext(SS, DC)) return 0;
10058
10059 LookupQualifiedName(Previous, DC);
10060
10061 // Ignore things found implicitly in the wrong scope.
10062 // TODO: better diagnostics for this case. Suggesting the right
10063 // qualified scope would be nice...
10064 LookupResult::Filter F = Previous.makeFilter();
10065 while (F.hasNext()) {
10066 NamedDecl *D = F.next();
10067 if (!DC->InEnclosingNamespaceSetOf(
10068 D->getDeclContext()->getRedeclContext()))
10069 F.erase();
10070 }
10071 F.done();
10072
10073 if (Previous.empty()) {
10074 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010075 Diag(Loc, diag::err_qualified_friend_not_found)
10076 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010077 return 0;
10078 }
10079
10080 // C++ [class.friend]p1: A friend of a class is a function or
10081 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010082 if (DC->Equals(CurContext))
10083 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010084 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010085 diag::warn_cxx98_compat_friend_is_member :
10086 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010087
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010088 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010089 // C++ [class.friend]p6:
10090 // A function can be defined in a friend declaration of a class if and
10091 // only if the class is a non-local class (9.8), the function name is
10092 // unqualified, and the function has namespace scope.
10093 SemaDiagnosticBuilder DB
10094 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10095
10096 DB << SS.getScopeRep();
10097 if (DC->isFileContext())
10098 DB << FixItHint::CreateRemoval(SS.getRange());
10099 SS.clear();
10100 }
John McCall337ec3d2010-10-12 23:13:28 +000010101
10102 // - There's a scope specifier that does not match any template
10103 // parameter lists, in which case we use some arbitrary context,
10104 // create a method or method template, and wait for instantiation.
10105 // - There's a scope specifier that does match some template
10106 // parameter lists, which we don't handle right now.
10107 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010108 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010109 // C++ [class.friend]p6:
10110 // A function can be defined in a friend declaration of a class if and
10111 // only if the class is a non-local class (9.8), the function name is
10112 // unqualified, and the function has namespace scope.
10113 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10114 << SS.getScopeRep();
10115 }
10116
John McCall337ec3d2010-10-12 23:13:28 +000010117 DC = CurContext;
10118 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010119 }
Douglas Gregor883af832011-10-10 01:11:59 +000010120
John McCall29ae6e52010-10-13 05:45:15 +000010121 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010122 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010123 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10124 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10125 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010126 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010127 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10128 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010129 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010130 }
John McCall67d1a672009-08-06 02:15:43 +000010131 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010132
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010133 // FIXME: This is an egregious hack to cope with cases where the scope stack
10134 // does not contain the declaration context, i.e., in an out-of-line
10135 // definition of a class.
10136 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10137 if (!DCScope) {
10138 FakeDCScope.setEntity(DC);
10139 DCScope = &FakeDCScope;
10140 }
10141
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010142 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010143 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10144 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010145 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010146
Douglas Gregor182ddf02009-09-28 00:08:27 +000010147 assert(ND->getDeclContext() == DC);
10148 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010149
John McCallab88d972009-08-31 22:39:49 +000010150 // Add the function declaration to the appropriate lookup tables,
10151 // adjusting the redeclarations list as necessary. We don't
10152 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010153 //
John McCallab88d972009-08-31 22:39:49 +000010154 // Also update the scope-based lookup if the target context's
10155 // lookup context is in lexical scope.
10156 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010157 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010158 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010159 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010160 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010161 }
John McCall02cace72009-08-28 07:59:38 +000010162
10163 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010164 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010165 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010166 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010167 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010168
John McCall337ec3d2010-10-12 23:13:28 +000010169 if (ND->isInvalidDecl())
10170 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010171 else {
10172 FunctionDecl *FD;
10173 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10174 FD = FTD->getTemplatedDecl();
10175 else
10176 FD = cast<FunctionDecl>(ND);
10177
10178 // Mark templated-scope function declarations as unsupported.
10179 if (FD->getNumTemplateParameterLists())
10180 FrD->setUnsupportedFriend(true);
10181 }
John McCall337ec3d2010-10-12 23:13:28 +000010182
John McCalld226f652010-08-21 09:40:31 +000010183 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010184}
10185
John McCalld226f652010-08-21 09:40:31 +000010186void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10187 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010188
Sebastian Redl50de12f2009-03-24 22:27:57 +000010189 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10190 if (!Fn) {
10191 Diag(DelLoc, diag::err_deleted_non_function);
10192 return;
10193 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010194 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010195 Diag(DelLoc, diag::err_deleted_decl_not_first);
10196 Diag(Prev->getLocation(), diag::note_previous_declaration);
10197 // If the declaration wasn't the first, we delete the function anyway for
10198 // recovery.
10199 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010200 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010201
10202 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10203 if (!MD)
10204 return;
10205
10206 // A deleted special member function is trivial if the corresponding
10207 // implicitly-declared function would have been.
10208 switch (getSpecialMember(MD)) {
10209 case CXXInvalid:
10210 break;
10211 case CXXDefaultConstructor:
10212 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10213 break;
10214 case CXXCopyConstructor:
10215 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10216 break;
10217 case CXXMoveConstructor:
10218 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10219 break;
10220 case CXXCopyAssignment:
10221 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10222 break;
10223 case CXXMoveAssignment:
10224 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10225 break;
10226 case CXXDestructor:
10227 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10228 break;
10229 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010230}
Sebastian Redl13e88542009-04-27 21:33:24 +000010231
Sean Hunte4246a62011-05-12 06:15:49 +000010232void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10233 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10234
10235 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010236 if (MD->getParent()->isDependentType()) {
10237 MD->setDefaulted();
10238 MD->setExplicitlyDefaulted();
10239 return;
10240 }
10241
Sean Hunte4246a62011-05-12 06:15:49 +000010242 CXXSpecialMember Member = getSpecialMember(MD);
10243 if (Member == CXXInvalid) {
10244 Diag(DefaultLoc, diag::err_default_special_members);
10245 return;
10246 }
10247
10248 MD->setDefaulted();
10249 MD->setExplicitlyDefaulted();
10250
Sean Huntcd10dec2011-05-23 23:14:04 +000010251 // If this definition appears within the record, do the checking when
10252 // the record is complete.
10253 const FunctionDecl *Primary = MD;
10254 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10255 // Find the uninstantiated declaration that actually had the '= default'
10256 // on it.
10257 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10258
10259 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010260 return;
10261
10262 switch (Member) {
10263 case CXXDefaultConstructor: {
10264 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010265 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010266 if (!CD->isInvalidDecl())
10267 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10268 break;
10269 }
10270
10271 case CXXCopyConstructor: {
10272 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010273 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010274 if (!CD->isInvalidDecl())
10275 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010276 break;
10277 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010278
Sean Hunt2b188082011-05-14 05:23:28 +000010279 case CXXCopyAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010280 CheckExplicitlyDefaultedSpecialMember(MD);
Sean Hunt2b188082011-05-14 05:23:28 +000010281 if (!MD->isInvalidDecl())
10282 DefineImplicitCopyAssignment(DefaultLoc, MD);
10283 break;
10284 }
10285
Sean Huntcb45a0f2011-05-12 22:46:25 +000010286 case CXXDestructor: {
10287 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010288 CheckExplicitlyDefaultedSpecialMember(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010289 if (!DD->isInvalidDecl())
10290 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010291 break;
10292 }
10293
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010294 case CXXMoveConstructor: {
10295 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010296 CheckExplicitlyDefaultedSpecialMember(CD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010297 if (!CD->isInvalidDecl())
10298 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010299 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010300 }
Sean Hunt82713172011-05-25 23:16:36 +000010301
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010302 case CXXMoveAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010303 CheckExplicitlyDefaultedSpecialMember(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010304 if (!MD->isInvalidDecl())
10305 DefineImplicitMoveAssignment(DefaultLoc, MD);
10306 break;
10307 }
10308
10309 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010310 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010311 }
10312 } else {
10313 Diag(DefaultLoc, diag::err_default_special_members);
10314 }
10315}
10316
Sebastian Redl13e88542009-04-27 21:33:24 +000010317static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010318 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010319 Stmt *SubStmt = *CI;
10320 if (!SubStmt)
10321 continue;
10322 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010323 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010324 diag::err_return_in_constructor_handler);
10325 if (!isa<Expr>(SubStmt))
10326 SearchForReturnInStmt(Self, SubStmt);
10327 }
10328}
10329
10330void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10331 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10332 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10333 SearchForReturnInStmt(*this, Handler);
10334 }
10335}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010336
Mike Stump1eb44332009-09-09 15:08:12 +000010337bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010338 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010339 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10340 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010341
Chandler Carruth73857792010-02-15 11:53:20 +000010342 if (Context.hasSameType(NewTy, OldTy) ||
10343 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010344 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010345
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010346 // Check if the return types are covariant
10347 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010348
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010349 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010350 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10351 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010352 NewClassTy = NewPT->getPointeeType();
10353 OldClassTy = OldPT->getPointeeType();
10354 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010355 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10356 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10357 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10358 NewClassTy = NewRT->getPointeeType();
10359 OldClassTy = OldRT->getPointeeType();
10360 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010361 }
10362 }
Mike Stump1eb44332009-09-09 15:08:12 +000010363
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010364 // The return types aren't either both pointers or references to a class type.
10365 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010366 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010367 diag::err_different_return_type_for_overriding_virtual_function)
10368 << New->getDeclName() << NewTy << OldTy;
10369 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010370
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010371 return true;
10372 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010373
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010374 // C++ [class.virtual]p6:
10375 // If the return type of D::f differs from the return type of B::f, the
10376 // class type in the return type of D::f shall be complete at the point of
10377 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010378 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10379 if (!RT->isBeingDefined() &&
10380 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010381 diag::err_covariant_return_incomplete,
10382 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010383 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010384 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010385
Douglas Gregora4923eb2009-11-16 21:35:15 +000010386 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010387 // Check if the new class derives from the old class.
10388 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10389 Diag(New->getLocation(),
10390 diag::err_covariant_return_not_derived)
10391 << New->getDeclName() << NewTy << OldTy;
10392 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10393 return true;
10394 }
Mike Stump1eb44332009-09-09 15:08:12 +000010395
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010396 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010397 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010398 diag::err_covariant_return_inaccessible_base,
10399 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10400 // FIXME: Should this point to the return type?
10401 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010402 // FIXME: this note won't trigger for delayed access control
10403 // diagnostics, and it's impossible to get an undelayed error
10404 // here from access control during the original parse because
10405 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010406 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10407 return true;
10408 }
10409 }
Mike Stump1eb44332009-09-09 15:08:12 +000010410
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010411 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010412 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010413 Diag(New->getLocation(),
10414 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010415 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010416 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10417 return true;
10418 };
Mike Stump1eb44332009-09-09 15:08:12 +000010419
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010420
10421 // The new class type must have the same or less qualifiers as the old type.
10422 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10423 Diag(New->getLocation(),
10424 diag::err_covariant_return_type_class_type_more_qualified)
10425 << New->getDeclName() << NewTy << OldTy;
10426 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10427 return true;
10428 };
Mike Stump1eb44332009-09-09 15:08:12 +000010429
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010430 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010431}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010432
Douglas Gregor4ba31362009-12-01 17:24:26 +000010433/// \brief Mark the given method pure.
10434///
10435/// \param Method the method to be marked pure.
10436///
10437/// \param InitRange the source range that covers the "0" initializer.
10438bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010439 SourceLocation EndLoc = InitRange.getEnd();
10440 if (EndLoc.isValid())
10441 Method->setRangeEnd(EndLoc);
10442
Douglas Gregor4ba31362009-12-01 17:24:26 +000010443 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10444 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010445 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010446 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010447
10448 if (!Method->isInvalidDecl())
10449 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10450 << Method->getDeclName() << InitRange;
10451 return true;
10452}
10453
Douglas Gregor552e2992012-02-21 02:22:07 +000010454/// \brief Determine whether the given declaration is a static data member.
10455static bool isStaticDataMember(Decl *D) {
10456 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10457 if (!Var)
10458 return false;
10459
10460 return Var->isStaticDataMember();
10461}
John McCall731ad842009-12-19 09:28:58 +000010462/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10463/// an initializer for the out-of-line declaration 'Dcl'. The scope
10464/// is a fresh scope pushed for just this purpose.
10465///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010466/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10467/// static data member of class X, names should be looked up in the scope of
10468/// class X.
John McCalld226f652010-08-21 09:40:31 +000010469void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010470 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010471 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010472
John McCall731ad842009-12-19 09:28:58 +000010473 // We should only get called for declarations with scope specifiers, like:
10474 // int foo::bar;
10475 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010476 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010477
10478 // If we are parsing the initializer for a static data member, push a
10479 // new expression evaluation context that is associated with this static
10480 // data member.
10481 if (isStaticDataMember(D))
10482 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010483}
10484
10485/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010486/// initializer for the out-of-line declaration 'D'.
10487void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010488 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010489 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010490
Douglas Gregor552e2992012-02-21 02:22:07 +000010491 if (isStaticDataMember(D))
10492 PopExpressionEvaluationContext();
10493
John McCall731ad842009-12-19 09:28:58 +000010494 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010495 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010496}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010497
10498/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10499/// C++ if/switch/while/for statement.
10500/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010501DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010502 // C++ 6.4p2:
10503 // The declarator shall not specify a function or an array.
10504 // The type-specifier-seq shall not contain typedef and shall not declare a
10505 // new class or enumeration.
10506 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10507 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010508
10509 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010510 if (!Dcl)
10511 return true;
10512
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010513 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10514 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010515 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010516 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010517 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010518
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010519 return Dcl;
10520}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010521
Douglas Gregordfe65432011-07-28 19:11:31 +000010522void Sema::LoadExternalVTableUses() {
10523 if (!ExternalSource)
10524 return;
10525
10526 SmallVector<ExternalVTableUse, 4> VTables;
10527 ExternalSource->ReadUsedVTables(VTables);
10528 SmallVector<VTableUse, 4> NewUses;
10529 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10530 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10531 = VTablesUsed.find(VTables[I].Record);
10532 // Even if a definition wasn't required before, it may be required now.
10533 if (Pos != VTablesUsed.end()) {
10534 if (!Pos->second && VTables[I].DefinitionRequired)
10535 Pos->second = true;
10536 continue;
10537 }
10538
10539 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10540 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10541 }
10542
10543 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10544}
10545
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010546void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10547 bool DefinitionRequired) {
10548 // Ignore any vtable uses in unevaluated operands or for classes that do
10549 // not have a vtable.
10550 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10551 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010552 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010553 return;
10554
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010555 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010556 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010557 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10558 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10559 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10560 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010561 // If we already had an entry, check to see if we are promoting this vtable
10562 // to required a definition. If so, we need to reappend to the VTableUses
10563 // list, since we may have already processed the first entry.
10564 if (DefinitionRequired && !Pos.first->second) {
10565 Pos.first->second = true;
10566 } else {
10567 // Otherwise, we can early exit.
10568 return;
10569 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010570 }
10571
10572 // Local classes need to have their virtual members marked
10573 // immediately. For all other classes, we mark their virtual members
10574 // at the end of the translation unit.
10575 if (Class->isLocalClass())
10576 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010577 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010578 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010579}
10580
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010581bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010582 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010583 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010584 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010585
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010586 // Note: The VTableUses vector could grow as a result of marking
10587 // the members of a class as "used", so we check the size each
10588 // time through the loop and prefer indices (with are stable) to
10589 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010590 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010591 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010592 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010593 if (!Class)
10594 continue;
10595
10596 SourceLocation Loc = VTableUses[I].second;
10597
10598 // If this class has a key function, but that key function is
10599 // defined in another translation unit, we don't need to emit the
10600 // vtable even though we're using it.
10601 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010602 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010603 switch (KeyFunction->getTemplateSpecializationKind()) {
10604 case TSK_Undeclared:
10605 case TSK_ExplicitSpecialization:
10606 case TSK_ExplicitInstantiationDeclaration:
10607 // The key function is in another translation unit.
10608 continue;
10609
10610 case TSK_ExplicitInstantiationDefinition:
10611 case TSK_ImplicitInstantiation:
10612 // We will be instantiating the key function.
10613 break;
10614 }
10615 } else if (!KeyFunction) {
10616 // If we have a class with no key function that is the subject
10617 // of an explicit instantiation declaration, suppress the
10618 // vtable; it will live with the explicit instantiation
10619 // definition.
10620 bool IsExplicitInstantiationDeclaration
10621 = Class->getTemplateSpecializationKind()
10622 == TSK_ExplicitInstantiationDeclaration;
10623 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10624 REnd = Class->redecls_end();
10625 R != REnd; ++R) {
10626 TemplateSpecializationKind TSK
10627 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10628 if (TSK == TSK_ExplicitInstantiationDeclaration)
10629 IsExplicitInstantiationDeclaration = true;
10630 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10631 IsExplicitInstantiationDeclaration = false;
10632 break;
10633 }
10634 }
10635
10636 if (IsExplicitInstantiationDeclaration)
10637 continue;
10638 }
10639
10640 // Mark all of the virtual members of this class as referenced, so
10641 // that we can build a vtable. Then, tell the AST consumer that a
10642 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010643 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010644 MarkVirtualMembersReferenced(Loc, Class);
10645 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10646 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10647
10648 // Optionally warn if we're emitting a weak vtable.
10649 if (Class->getLinkage() == ExternalLinkage &&
10650 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010651 const FunctionDecl *KeyFunctionDef = 0;
10652 if (!KeyFunction ||
10653 (KeyFunction->hasBody(KeyFunctionDef) &&
10654 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010655 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10656 TSK_ExplicitInstantiationDefinition
10657 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10658 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010659 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010660 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010661 VTableUses.clear();
10662
Douglas Gregor78844032011-04-22 22:25:37 +000010663 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010664}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010665
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010666void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10667 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010668 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10669 e = RD->method_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +000010670 CXXMethodDecl *MD = *i;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010671
10672 // C++ [basic.def.odr]p2:
10673 // [...] A virtual member function is used if it is not pure. [...]
10674 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010675 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010676 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010677
10678 // Only classes that have virtual bases need a VTT.
10679 if (RD->getNumVBases() == 0)
10680 return;
10681
10682 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10683 e = RD->bases_end(); i != e; ++i) {
10684 const CXXRecordDecl *Base =
10685 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010686 if (Base->getNumVBases() == 0)
10687 continue;
10688 MarkVirtualMembersReferenced(Loc, Base);
10689 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010690}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010691
10692/// SetIvarInitializers - This routine builds initialization ASTs for the
10693/// Objective-C implementation whose ivars need be initialized.
10694void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010695 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010696 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010697 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010698 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010699 CollectIvarsToConstructOrDestruct(OID, ivars);
10700 if (ivars.empty())
10701 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010702 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010703 for (unsigned i = 0; i < ivars.size(); i++) {
10704 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010705 if (Field->isInvalidDecl())
10706 continue;
10707
Sean Huntcbb67482011-01-08 20:30:50 +000010708 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010709 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10710 InitializationKind InitKind =
10711 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10712
10713 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010714 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010715 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010716 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010717 // Note, MemberInit could actually come back empty if no initialization
10718 // is required (e.g., because it would call a trivial default constructor)
10719 if (!MemberInit.get() || MemberInit.isInvalid())
10720 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010721
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010722 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010723 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10724 SourceLocation(),
10725 MemberInit.takeAs<Expr>(),
10726 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010727 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010728
10729 // Be sure that the destructor is accessible and is marked as referenced.
10730 if (const RecordType *RecordTy
10731 = Context.getBaseElementType(Field->getType())
10732 ->getAs<RecordType>()) {
10733 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010734 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010735 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010736 CheckDestructorAccess(Field->getLocation(), Destructor,
10737 PDiag(diag::err_access_dtor_ivar)
10738 << Context.getBaseElementType(Field->getType()));
10739 }
10740 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010741 }
10742 ObjCImplementation->setIvarInitializers(Context,
10743 AllToInit.data(), AllToInit.size());
10744 }
10745}
Sean Huntfe57eef2011-05-04 05:57:24 +000010746
Sean Huntebcbe1d2011-05-04 23:29:54 +000010747static
10748void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10749 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10750 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10751 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10752 Sema &S) {
10753 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10754 CE = Current.end();
10755 if (Ctor->isInvalidDecl())
10756 return;
10757
10758 const FunctionDecl *FNTarget = 0;
10759 CXXConstructorDecl *Target;
10760
10761 // We ignore the result here since if we don't have a body, Target will be
10762 // null below.
10763 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10764 Target
10765= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10766
10767 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10768 // Avoid dereferencing a null pointer here.
10769 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10770
10771 if (!Current.insert(Canonical))
10772 return;
10773
10774 // We know that beyond here, we aren't chaining into a cycle.
10775 if (!Target || !Target->isDelegatingConstructor() ||
10776 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10777 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10778 Valid.insert(*CI);
10779 Current.clear();
10780 // We've hit a cycle.
10781 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10782 Current.count(TCanonical)) {
10783 // If we haven't diagnosed this cycle yet, do so now.
10784 if (!Invalid.count(TCanonical)) {
10785 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010786 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010787 << Ctor;
10788
10789 // Don't add a note for a function delegating directo to itself.
10790 if (TCanonical != Canonical)
10791 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10792
10793 CXXConstructorDecl *C = Target;
10794 while (C->getCanonicalDecl() != Canonical) {
10795 (void)C->getTargetConstructor()->hasBody(FNTarget);
10796 assert(FNTarget && "Ctor cycle through bodiless function");
10797
10798 C
10799 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10800 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10801 }
10802 }
10803
10804 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10805 Invalid.insert(*CI);
10806 Current.clear();
10807 } else {
10808 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10809 }
10810}
10811
10812
Sean Huntfe57eef2011-05-04 05:57:24 +000010813void Sema::CheckDelegatingCtorCycles() {
10814 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10815
Sean Huntebcbe1d2011-05-04 23:29:54 +000010816 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10817 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010818
Douglas Gregor0129b562011-07-27 21:57:17 +000010819 for (DelegatingCtorDeclsType::iterator
10820 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010821 E = DelegatingCtorDecls.end();
10822 I != E; ++I) {
10823 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010824 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010825
10826 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10827 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010828}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010829
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010830namespace {
10831 /// \brief AST visitor that finds references to the 'this' expression.
10832 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
10833 Sema &S;
10834
10835 public:
10836 explicit FindCXXThisExpr(Sema &S) : S(S) { }
10837
10838 bool VisitCXXThisExpr(CXXThisExpr *E) {
10839 S.Diag(E->getLocation(), diag::err_this_static_member_func)
10840 << E->isImplicit();
10841 return false;
10842 }
10843 };
10844}
10845
10846bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
10847 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10848 if (!TSInfo)
10849 return false;
10850
10851 TypeLoc TL = TSInfo->getTypeLoc();
10852 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10853 if (!ProtoTL)
10854 return false;
10855
10856 // C++11 [expr.prim.general]p3:
10857 // [The expression this] shall not appear before the optional
10858 // cv-qualifier-seq and it shall not appear within the declaration of a
10859 // static member function (although its type and value category are defined
10860 // within a static member function as they are within a non-static member
10861 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000010862 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010863 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10864 FindCXXThisExpr Finder(*this);
10865
10866 // If the return type came after the cv-qualifier-seq, check it now.
10867 if (Proto->hasTrailingReturn() &&
10868 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
10869 return true;
10870
10871 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010872 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
10873 return true;
10874
10875 return checkThisInStaticMemberFunctionAttributes(Method);
10876}
10877
10878bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
10879 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10880 if (!TSInfo)
10881 return false;
10882
10883 TypeLoc TL = TSInfo->getTypeLoc();
10884 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10885 if (!ProtoTL)
10886 return false;
10887
10888 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10889 FindCXXThisExpr Finder(*this);
10890
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010891 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000010892 case EST_Uninstantiated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010893 case EST_BasicNoexcept:
10894 case EST_Delayed:
10895 case EST_DynamicNone:
10896 case EST_MSAny:
10897 case EST_None:
10898 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010899
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010900 case EST_ComputedNoexcept:
10901 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
10902 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010903
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010904 case EST_Dynamic:
10905 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010906 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010907 E != EEnd; ++E) {
10908 if (!Finder.TraverseType(*E))
10909 return true;
10910 }
10911 break;
10912 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010913
10914 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010915}
10916
10917bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
10918 FindCXXThisExpr Finder(*this);
10919
10920 // Check attributes.
10921 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
10922 A != AEnd; ++A) {
10923 // FIXME: This should be emitted by tblgen.
10924 Expr *Arg = 0;
10925 ArrayRef<Expr *> Args;
10926 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
10927 Arg = G->getArg();
10928 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
10929 Arg = G->getArg();
10930 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
10931 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
10932 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
10933 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
10934 else if (ExclusiveLockFunctionAttr *ELF
10935 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
10936 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
10937 else if (SharedLockFunctionAttr *SLF
10938 = dyn_cast<SharedLockFunctionAttr>(*A))
10939 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
10940 else if (ExclusiveTrylockFunctionAttr *ETLF
10941 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
10942 Arg = ETLF->getSuccessValue();
10943 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
10944 } else if (SharedTrylockFunctionAttr *STLF
10945 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
10946 Arg = STLF->getSuccessValue();
10947 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
10948 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
10949 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
10950 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
10951 Arg = LR->getArg();
10952 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
10953 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
10954 else if (ExclusiveLocksRequiredAttr *ELR
10955 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
10956 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
10957 else if (SharedLocksRequiredAttr *SLR
10958 = dyn_cast<SharedLocksRequiredAttr>(*A))
10959 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
10960
10961 if (Arg && !Finder.TraverseStmt(Arg))
10962 return true;
10963
10964 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
10965 if (!Finder.TraverseStmt(Args[I]))
10966 return true;
10967 }
10968 }
10969
10970 return false;
10971}
10972
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010973void
10974Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
10975 ArrayRef<ParsedType> DynamicExceptions,
10976 ArrayRef<SourceRange> DynamicExceptionRanges,
10977 Expr *NoexceptExpr,
10978 llvm::SmallVectorImpl<QualType> &Exceptions,
10979 FunctionProtoType::ExtProtoInfo &EPI) {
10980 Exceptions.clear();
10981 EPI.ExceptionSpecType = EST;
10982 if (EST == EST_Dynamic) {
10983 Exceptions.reserve(DynamicExceptions.size());
10984 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
10985 // FIXME: Preserve type source info.
10986 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
10987
10988 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10989 collectUnexpandedParameterPacks(ET, Unexpanded);
10990 if (!Unexpanded.empty()) {
10991 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
10992 UPPC_ExceptionType,
10993 Unexpanded);
10994 continue;
10995 }
10996
10997 // Check that the type is valid for an exception spec, and
10998 // drop it if not.
10999 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11000 Exceptions.push_back(ET);
11001 }
11002 EPI.NumExceptions = Exceptions.size();
11003 EPI.Exceptions = Exceptions.data();
11004 return;
11005 }
11006
11007 if (EST == EST_ComputedNoexcept) {
11008 // If an error occurred, there's no expression here.
11009 if (NoexceptExpr) {
11010 assert((NoexceptExpr->isTypeDependent() ||
11011 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11012 Context.BoolTy) &&
11013 "Parser should have made sure that the expression is boolean");
11014 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11015 EPI.ExceptionSpecType = EST_BasicNoexcept;
11016 return;
11017 }
11018
11019 if (!NoexceptExpr->isValueDependent())
11020 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011021 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011022 /*AllowFold*/ false).take();
11023 EPI.NoexceptExpr = NoexceptExpr;
11024 }
11025 return;
11026 }
11027}
11028
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011029/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11030Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11031 // Implicitly declared functions (e.g. copy constructors) are
11032 // __host__ __device__
11033 if (D->isImplicit())
11034 return CFT_HostDevice;
11035
11036 if (D->hasAttr<CUDAGlobalAttr>())
11037 return CFT_Global;
11038
11039 if (D->hasAttr<CUDADeviceAttr>()) {
11040 if (D->hasAttr<CUDAHostAttr>())
11041 return CFT_HostDevice;
11042 else
11043 return CFT_Device;
11044 }
11045
11046 return CFT_Host;
11047}
11048
11049bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11050 CUDAFunctionTarget CalleeTarget) {
11051 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11052 // Callable from the device only."
11053 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11054 return true;
11055
11056 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11057 // Callable from the host only."
11058 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11059 // Callable from the host only."
11060 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11061 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11062 return true;
11063
11064 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11065 return true;
11066
11067 return false;
11068}