blob: 3e1899c76239cc1cae765a51762dba4c005cf724 [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 Blaikie262bc182012-04-30 02:36:29 +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 Blaikie262bc182012-04-30 02:36:29 +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
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001442/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1443/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001444/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1445/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1446/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001447Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001449 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001450 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001451 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001452 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001453 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1454 DeclarationName Name = NameInfo.getName();
1455 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001456
1457 // For anonymous bitfields, the location should point to the type.
1458 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001459 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001460
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001462
John McCall4bde1e12010-06-04 08:34:12 +00001463 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001464 assert(!DS.isFriendSpecified());
1465
Richard Smith1ab0d902011-06-25 02:28:38 +00001466 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001467
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001468 // C++ 9.2p6: A member shall not be declared to have automatic storage
1469 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001470 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1471 // data members and cannot be applied to names declared const or static,
1472 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473 switch (DS.getStorageClassSpec()) {
1474 case DeclSpec::SCS_unspecified:
1475 case DeclSpec::SCS_typedef:
1476 case DeclSpec::SCS_static:
1477 // FALL THROUGH.
1478 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 case DeclSpec::SCS_mutable:
1480 if (isFunc) {
1481 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001482 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001483 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Sebastian Redla11f42f2008-11-17 23:24:37 +00001486 // FIXME: It would be nicer if the keyword was ignored only for this
1487 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001488 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001489 }
1490 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001491 default:
1492 if (DS.getStorageClassSpecLoc().isValid())
1493 Diag(DS.getStorageClassSpecLoc(),
1494 diag::err_storageclass_invalid_for_member);
1495 else
1496 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1497 D.getMutableDeclSpec().ClearStorageClassSpecs();
1498 }
1499
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1501 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001502 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503
1504 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001505 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001506 CXXScopeSpec &SS = D.getCXXScopeSpec();
Benjamin Kramerc4704422012-05-19 16:03:58 +00001507 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001508
1509 // Data members must have identifiers for names.
Benjamin Kramerc4704422012-05-19 16:03:58 +00001510 if (!II) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001511 Diag(Loc, diag::err_bad_variable_name)
1512 << Name;
1513 return 0;
1514 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001515
1516 // Member field could not be with "template" keyword.
1517 // So TemplateParameterLists should be empty in this case.
1518 if (TemplateParameterLists.size()) {
1519 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1520 if (TemplateParams->size()) {
1521 // There is no such thing as a member field template.
1522 Diag(D.getIdentifierLoc(), diag::err_template_member)
1523 << II
1524 << SourceRange(TemplateParams->getTemplateLoc(),
1525 TemplateParams->getRAngleLoc());
1526 } else {
1527 // There is an extraneous 'template<>' for this member.
1528 Diag(TemplateParams->getTemplateLoc(),
1529 diag::err_template_member_noparams)
1530 << II
1531 << SourceRange(TemplateParams->getTemplateLoc(),
1532 TemplateParams->getRAngleLoc());
1533 }
1534 return 0;
1535 }
1536
Douglas Gregor922fff22010-10-13 22:19:53 +00001537 if (SS.isSet() && !SS.isInvalid()) {
1538 // The user provided a superfluous scope specifier inside a class
1539 // definition:
1540 //
1541 // class X {
1542 // int X::member;
1543 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001544 if (DeclContext *DC = computeDeclContext(SS, false))
1545 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001546 else
1547 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1548 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001549
Douglas Gregor922fff22010-10-13 22:19:53 +00001550 SS.clear();
1551 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001552
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001553 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001554 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001555 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001556 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001557 assert(!HasDeferredInit);
1558
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001559 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001560 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001561 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001562 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001563
1564 // Non-instance-fields can't have a bitfield.
1565 if (BitWidth) {
1566 if (Member->isInvalidDecl()) {
1567 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001568 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001569 // C++ 9.6p3: A bit-field shall not be a static member.
1570 // "static member 'A' cannot be a bit-field"
1571 Diag(Loc, diag::err_static_not_bitfield)
1572 << Name << BitWidth->getSourceRange();
1573 } else if (isa<TypedefDecl>(Member)) {
1574 // "typedef member 'x' cannot be a bit-field"
1575 Diag(Loc, diag::err_typedef_not_bitfield)
1576 << Name << BitWidth->getSourceRange();
1577 } else {
1578 // A function typedef ("typedef int f(); f a;").
1579 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1580 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001581 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001582 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattner8b963ef2009-03-05 23:01:03 +00001585 BitWidth = 0;
1586 Member->setInvalidDecl();
1587 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001588
1589 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor37b372b2009-08-20 22:52:58 +00001591 // If we have declared a member function template, set the access of the
1592 // templated declaration as well.
1593 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1594 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001595 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001596
Anders Carlssonaae5af22011-01-20 04:34:22 +00001597 if (VS.isOverrideSpecified()) {
1598 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1599 if (!MD || !MD->isVirtual()) {
1600 Diag(Member->getLocStart(),
1601 diag::override_keyword_only_allowed_on_virtual_member_functions)
1602 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001603 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001604 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001605 }
1606 if (VS.isFinalSpecified()) {
1607 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1608 if (!MD || !MD->isVirtual()) {
1609 Diag(Member->getLocStart(),
1610 diag::override_keyword_only_allowed_on_virtual_member_functions)
1611 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001612 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001613 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001614 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615
Douglas Gregorf5251602011-03-08 17:10:18 +00001616 if (VS.getLastLocation().isValid()) {
1617 // Update the end location of a method that has a virt-specifiers.
1618 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1619 MD->setRangeEnd(VS.getLastLocation());
1620 }
1621
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001622 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001623
Douglas Gregor10bd3682008-11-17 22:58:34 +00001624 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001625
John McCallb25b2952011-02-15 07:12:36 +00001626 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001627 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001628 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001629}
1630
Richard Smith7a614d82011-06-11 17:19:42 +00001631/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001632/// in-class initializer for a non-static C++ class member, and after
1633/// instantiating an in-class initializer in a class template. Such actions
1634/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001635void
1636Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1637 Expr *InitExpr) {
1638 FieldDecl *FD = cast<FieldDecl>(D);
1639
1640 if (!InitExpr) {
1641 FD->setInvalidDecl();
1642 FD->removeInClassInitializer();
1643 return;
1644 }
1645
Peter Collingbournefef21892011-10-23 18:59:44 +00001646 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1647 FD->setInvalidDecl();
1648 FD->removeInClassInitializer();
1649 return;
1650 }
1651
Richard Smith7a614d82011-06-11 17:19:42 +00001652 ExprResult Init = InitExpr;
1653 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001654 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001655 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001656 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1657 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001658 Expr **Inits = &InitExpr;
1659 unsigned NumInits = 1;
1660 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1661 InitializationKind Kind = EqualLoc.isInvalid()
1662 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1663 : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1664 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1665 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001666 if (Init.isInvalid()) {
1667 FD->setInvalidDecl();
1668 return;
1669 }
1670
1671 CheckImplicitConversions(Init.get(), EqualLoc);
1672 }
1673
1674 // C++0x [class.base.init]p7:
1675 // The initialization of each base and member constitutes a
1676 // full-expression.
1677 Init = MaybeCreateExprWithCleanups(Init);
1678 if (Init.isInvalid()) {
1679 FD->setInvalidDecl();
1680 return;
1681 }
1682
1683 InitExpr = Init.release();
1684
1685 FD->setInClassInitializer(InitExpr);
1686}
1687
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001688/// \brief Find the direct and/or virtual base specifiers that
1689/// correspond to the given base type, for use in base initialization
1690/// within a constructor.
1691static bool FindBaseInitializer(Sema &SemaRef,
1692 CXXRecordDecl *ClassDecl,
1693 QualType BaseType,
1694 const CXXBaseSpecifier *&DirectBaseSpec,
1695 const CXXBaseSpecifier *&VirtualBaseSpec) {
1696 // First, check for a direct base class.
1697 DirectBaseSpec = 0;
1698 for (CXXRecordDecl::base_class_const_iterator Base
1699 = ClassDecl->bases_begin();
1700 Base != ClassDecl->bases_end(); ++Base) {
1701 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1702 // We found a direct base of this type. That's what we're
1703 // initializing.
1704 DirectBaseSpec = &*Base;
1705 break;
1706 }
1707 }
1708
1709 // Check for a virtual base class.
1710 // FIXME: We might be able to short-circuit this if we know in advance that
1711 // there are no virtual bases.
1712 VirtualBaseSpec = 0;
1713 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1714 // We haven't found a base yet; search the class hierarchy for a
1715 // virtual base class.
1716 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1717 /*DetectVirtual=*/false);
1718 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1719 BaseType, Paths)) {
1720 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1721 Path != Paths.end(); ++Path) {
1722 if (Path->back().Base->isVirtual()) {
1723 VirtualBaseSpec = Path->back().Base;
1724 break;
1725 }
1726 }
1727 }
1728 }
1729
1730 return DirectBaseSpec || VirtualBaseSpec;
1731}
1732
Sebastian Redl6df65482011-09-24 17:48:25 +00001733/// \brief Handle a C++ member initializer using braced-init-list syntax.
1734MemInitResult
1735Sema::ActOnMemInitializer(Decl *ConstructorD,
1736 Scope *S,
1737 CXXScopeSpec &SS,
1738 IdentifierInfo *MemberOrBase,
1739 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001740 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001741 SourceLocation IdLoc,
1742 Expr *InitList,
1743 SourceLocation EllipsisLoc) {
1744 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001745 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001746 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001747}
1748
1749/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001750MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001751Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001752 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001753 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001754 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001755 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001756 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001757 SourceLocation IdLoc,
1758 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001759 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001760 SourceLocation RParenLoc,
1761 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001762 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1763 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001764 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001765 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001766}
1767
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001768namespace {
1769
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001770// Callback to only accept typo corrections that can be a valid C++ member
1771// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001772class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1773 public:
1774 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1775 : ClassDecl(ClassDecl) {}
1776
1777 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1778 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1779 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1780 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1781 else
1782 return isa<TypeDecl>(ND);
1783 }
1784 return false;
1785 }
1786
1787 private:
1788 CXXRecordDecl *ClassDecl;
1789};
1790
1791}
1792
Sebastian Redl6df65482011-09-24 17:48:25 +00001793/// \brief Handle a C++ member initializer.
1794MemInitResult
1795Sema::BuildMemInitializer(Decl *ConstructorD,
1796 Scope *S,
1797 CXXScopeSpec &SS,
1798 IdentifierInfo *MemberOrBase,
1799 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001800 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001801 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001802 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001803 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001804 if (!ConstructorD)
1805 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001807 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001808
1809 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001810 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001811 if (!Constructor) {
1812 // The user wrote a constructor initializer on a function that is
1813 // not a C++ constructor. Ignore the error for now, because we may
1814 // have more member initializers coming; we'll diagnose it just
1815 // once in ActOnMemInitializers.
1816 return true;
1817 }
1818
1819 CXXRecordDecl *ClassDecl = Constructor->getParent();
1820
1821 // C++ [class.base.init]p2:
1822 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001823 // constructor's class and, if not found in that scope, are looked
1824 // up in the scope containing the constructor's definition.
1825 // [Note: if the constructor's class contains a member with the
1826 // same name as a direct or virtual base class of the class, a
1827 // mem-initializer-id naming the member or base class and composed
1828 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001829 // mem-initializer-id for the hidden base class may be specified
1830 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001831 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001832 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001833 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001834 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001835 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001836 ValueDecl *Member;
1837 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1838 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001839 if (EllipsisLoc.isValid())
1840 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001841 << MemberOrBase
1842 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001843
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001844 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001845 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001846 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001848 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001849 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001850 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001851
1852 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001853 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001854 } else if (DS.getTypeSpecType() == TST_decltype) {
1855 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001856 } else {
1857 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1858 LookupParsedName(R, S, &SS);
1859
1860 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1861 if (!TyD) {
1862 if (R.isAmbiguous()) return true;
1863
John McCallfd225442010-04-09 19:01:14 +00001864 // We don't want access-control diagnostics here.
1865 R.suppressDiagnostics();
1866
Douglas Gregor7a886e12010-01-19 06:46:48 +00001867 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1868 bool NotUnknownSpecialization = false;
1869 DeclContext *DC = computeDeclContext(SS, false);
1870 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1871 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1872
1873 if (!NotUnknownSpecialization) {
1874 // When the scope specifier can refer to a member of an unknown
1875 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001876 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1877 SS.getWithLocInContext(Context),
1878 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001879 if (BaseType.isNull())
1880 return true;
1881
Douglas Gregor7a886e12010-01-19 06:46:48 +00001882 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001883 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001884 }
1885 }
1886
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001887 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001888 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001889 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001890 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001891 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001892 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001893 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1894 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001895 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001896 // We have found a non-static data member with a similar
1897 // name to what was typed; complain and initialize that
1898 // member.
1899 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1900 << MemberOrBase << true << CorrectedQuotedStr
1901 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1902 Diag(Member->getLocation(), diag::note_previous_decl)
1903 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001904
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001905 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001906 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001907 const CXXBaseSpecifier *DirectBaseSpec;
1908 const CXXBaseSpecifier *VirtualBaseSpec;
1909 if (FindBaseInitializer(*this, ClassDecl,
1910 Context.getTypeDeclType(Type),
1911 DirectBaseSpec, VirtualBaseSpec)) {
1912 // We have found a direct or virtual base class with a
1913 // similar name to what was typed; complain and initialize
1914 // that base class.
1915 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001916 << MemberOrBase << false << CorrectedQuotedStr
1917 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001918
1919 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1920 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001921 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001922 diag::note_base_class_specified_here)
1923 << BaseSpec->getType()
1924 << BaseSpec->getSourceRange();
1925
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001926 TyD = Type;
1927 }
1928 }
1929 }
1930
Douglas Gregor7a886e12010-01-19 06:46:48 +00001931 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001932 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001933 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001934 return true;
1935 }
John McCall2b194412009-12-21 10:41:20 +00001936 }
1937
Douglas Gregor7a886e12010-01-19 06:46:48 +00001938 if (BaseType.isNull()) {
1939 BaseType = Context.getTypeDeclType(TyD);
1940 if (SS.isSet()) {
1941 NestedNameSpecifier *Qualifier =
1942 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001943
Douglas Gregor7a886e12010-01-19 06:46:48 +00001944 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001945 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001946 }
John McCall2b194412009-12-21 10:41:20 +00001947 }
1948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
John McCalla93c9342009-12-07 02:54:59 +00001950 if (!TInfo)
1951 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001952
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001953 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001954}
1955
Chandler Carruth81c64772011-09-03 01:14:15 +00001956/// Checks a member initializer expression for cases where reference (or
1957/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001958static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1959 Expr *Init,
1960 SourceLocation IdLoc) {
1961 QualType MemberTy = Member->getType();
1962
1963 // We only handle pointers and references currently.
1964 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1965 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1966 return;
1967
1968 const bool IsPointer = MemberTy->isPointerType();
1969 if (IsPointer) {
1970 if (const UnaryOperator *Op
1971 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1972 // The only case we're worried about with pointers requires taking the
1973 // address.
1974 if (Op->getOpcode() != UO_AddrOf)
1975 return;
1976
1977 Init = Op->getSubExpr();
1978 } else {
1979 // We only handle address-of expression initializers for pointers.
1980 return;
1981 }
1982 }
1983
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001984 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1985 // Taking the address of a temporary will be diagnosed as a hard error.
1986 if (IsPointer)
1987 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001988
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001989 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1990 << Member << Init->getSourceRange();
1991 } else if (const DeclRefExpr *DRE
1992 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1993 // We only warn when referring to a non-reference parameter declaration.
1994 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1995 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001996 return;
1997
1998 S.Diag(Init->getExprLoc(),
1999 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2000 : diag::warn_bind_ref_member_to_parameter)
2001 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002002 } else {
2003 // Other initializers are fine.
2004 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002005 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002006
2007 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2008 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002009}
2010
John McCallb4190042009-11-04 23:02:40 +00002011/// Checks an initializer expression for use of uninitialized fields, such as
2012/// containing the field that is being initialized. Returns true if there is an
2013/// uninitialized field was used an updates the SourceLocation parameter; false
2014/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002015static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002016 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002017 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002018 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2019
Nick Lewycky43ad1822010-06-15 07:32:55 +00002020 if (isa<CallExpr>(S)) {
2021 // Do not descend into function calls or constructors, as the use
2022 // of an uninitialized field may be valid. One would have to inspect
2023 // the contents of the function/ctor to determine if it is safe or not.
2024 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2025 // may be safe, depending on what the function/ctor does.
2026 return false;
2027 }
2028 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2029 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002030
2031 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2032 // The member expression points to a static data member.
2033 assert(VD->isStaticDataMember() &&
2034 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002035 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002036 return false;
2037 }
2038
2039 if (isa<EnumConstantDecl>(RhsField)) {
2040 // The member expression points to an enum.
2041 return false;
2042 }
2043
John McCallb4190042009-11-04 23:02:40 +00002044 if (RhsField == LhsField) {
2045 // Initializing a field with itself. Throw a warning.
2046 // But wait; there are exceptions!
2047 // Exception #1: The field may not belong to this record.
2048 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002049 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002050 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2051 // Even though the field matches, it does not belong to this record.
2052 return false;
2053 }
2054 // None of the exceptions triggered; return true to indicate an
2055 // uninitialized field was used.
2056 *L = ME->getMemberLoc();
2057 return true;
2058 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002059 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002060 // sizeof/alignof doesn't reference contents, do not warn.
2061 return false;
2062 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2063 // address-of doesn't reference contents (the pointer may be dereferenced
2064 // in the same expression but it would be rare; and weird).
2065 if (UOE->getOpcode() == UO_AddrOf)
2066 return false;
John McCallb4190042009-11-04 23:02:40 +00002067 }
John McCall7502c1d2011-02-13 04:07:26 +00002068 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002069 if (!*it) {
2070 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002071 continue;
2072 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002073 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2074 return true;
John McCallb4190042009-11-04 23:02:40 +00002075 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002076 return false;
John McCallb4190042009-11-04 23:02:40 +00002077}
2078
John McCallf312b1e2010-08-26 23:41:50 +00002079MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002080Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002081 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002082 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2083 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2084 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002085 "Member must be a FieldDecl or IndirectFieldDecl");
2086
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002087 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002088 return true;
2089
Douglas Gregor464b2f02010-11-05 22:21:31 +00002090 if (Member->isInvalidDecl())
2091 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002092
John McCallb4190042009-11-04 23:02:40 +00002093 // Diagnose value-uses of fields to initialize themselves, e.g.
2094 // foo(foo)
2095 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002096 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002097 Expr **Args;
2098 unsigned NumArgs;
2099 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2100 Args = ParenList->getExprs();
2101 NumArgs = ParenList->getNumExprs();
2102 } else {
2103 InitListExpr *InitList = cast<InitListExpr>(Init);
2104 Args = InitList->getInits();
2105 NumArgs = InitList->getNumInits();
2106 }
2107 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002108 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002109 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002110 // FIXME: Return true in the case when other fields are used before being
2111 // uninitialized. For example, let this field be the i'th field. When
2112 // initializing the i'th field, throw a warning if any of the >= i'th
2113 // fields are used, as they are not yet initialized.
2114 // Right now we are only handling the case where the i'th field uses
2115 // itself in its initializer.
2116 Diag(L, diag::warn_field_is_uninit);
2117 }
2118 }
2119
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002120 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002121
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002122 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002123 // Can't check initialization for a member of dependent type or when
2124 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002125 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002126 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002127 bool InitList = false;
2128 if (isa<InitListExpr>(Init)) {
2129 InitList = true;
2130 Args = &Init;
2131 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002132
2133 if (isStdInitializerList(Member->getType(), 0)) {
2134 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2135 << /*at end of ctor*/1 << InitRange;
2136 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002137 }
2138
Chandler Carruth894aed92010-12-06 09:23:57 +00002139 // Initialize the member.
2140 InitializedEntity MemberEntity =
2141 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2142 : InitializedEntity::InitializeMember(IndirectMember, 0);
2143 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002144 InitList ? InitializationKind::CreateDirectList(IdLoc)
2145 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2146 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002147
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002148 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2149 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2150 MultiExprArg(*this, Args, NumArgs),
2151 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002152 if (MemberInit.isInvalid())
2153 return true;
2154
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002155 CheckImplicitConversions(MemberInit.get(),
2156 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002157
2158 // C++0x [class.base.init]p7:
2159 // The initialization of each base and member constitutes a
2160 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002161 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002162 if (MemberInit.isInvalid())
2163 return true;
2164
2165 // If we are in a dependent context, template instantiation will
2166 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002167 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002168 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2169 // of the information that we have about the member
2170 // initializer. However, deconstructing the ASTs is a dicey process,
2171 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002172 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002173 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002174 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002175 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002176 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2177 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002178 }
2179
Chandler Carruth894aed92010-12-06 09:23:57 +00002180 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002181 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2182 InitRange.getBegin(), Init,
2183 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002184 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002185 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2186 InitRange.getBegin(), Init,
2187 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002188 }
Eli Friedman59c04372009-07-29 19:44:27 +00002189}
2190
John McCallf312b1e2010-08-26 23:41:50 +00002191MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002192Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002193 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002194 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002195 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002196 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002197 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002198 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002199
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002200 bool InitList = true;
2201 Expr **Args = &Init;
2202 unsigned NumArgs = 1;
2203 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2204 InitList = false;
2205 Args = ParenList->getExprs();
2206 NumArgs = ParenList->getNumExprs();
2207 }
2208
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002209 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002210 // Initialize the object.
2211 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2212 QualType(ClassDecl->getTypeForDecl(), 0));
2213 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002214 InitList ? InitializationKind::CreateDirectList(NameLoc)
2215 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2216 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002217 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2218 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2219 MultiExprArg(*this, Args,NumArgs),
2220 0);
Sean Hunt41717662011-02-26 19:13:13 +00002221 if (DelegationInit.isInvalid())
2222 return true;
2223
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002224 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2225 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002226
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002227 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002228
2229 // C++0x [class.base.init]p7:
2230 // The initialization of each base and member constitutes a
2231 // full-expression.
2232 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2233 if (DelegationInit.isInvalid())
2234 return true;
2235
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002236 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002237 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002239}
2240
2241MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002242Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002244 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002245 SourceLocation BaseLoc
2246 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002247
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002248 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2249 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2250 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2251
2252 // C++ [class.base.init]p2:
2253 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002254 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002255 // of that class, the mem-initializer is ill-formed. A
2256 // mem-initializer-list can initialize a base class using any
2257 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002258 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002259
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002260 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002261 if (EllipsisLoc.isValid()) {
2262 // This is a pack expansion.
2263 if (!BaseType->containsUnexpandedParameterPack()) {
2264 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002265 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002266
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002267 EllipsisLoc = SourceLocation();
2268 }
2269 } else {
2270 // Check for any unexpanded parameter packs.
2271 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2272 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002273
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002274 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002275 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002276 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002277
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002278 // Check for direct and virtual base classes.
2279 const CXXBaseSpecifier *DirectBaseSpec = 0;
2280 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2281 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002282 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2283 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002284 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002285
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002286 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2287 VirtualBaseSpec);
2288
2289 // C++ [base.class.init]p2:
2290 // Unless the mem-initializer-id names a nonstatic data member of the
2291 // constructor's class or a direct or virtual base of that class, the
2292 // mem-initializer is ill-formed.
2293 if (!DirectBaseSpec && !VirtualBaseSpec) {
2294 // If the class has any dependent bases, then it's possible that
2295 // one of those types will resolve to the same type as
2296 // BaseType. Therefore, just treat this as a dependent base
2297 // class initialization. FIXME: Should we try to check the
2298 // initialization anyway? It seems odd.
2299 if (ClassDecl->hasAnyDependentBases())
2300 Dependent = true;
2301 else
2302 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2303 << BaseType << Context.getTypeDeclType(ClassDecl)
2304 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2305 }
2306 }
2307
2308 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002309 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Sebastian Redl6df65482011-09-24 17:48:25 +00002311 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2312 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002313 InitRange.getBegin(), Init,
2314 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002315 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002316
2317 // C++ [base.class.init]p2:
2318 // If a mem-initializer-id is ambiguous because it designates both
2319 // a direct non-virtual base class and an inherited virtual base
2320 // class, the mem-initializer is ill-formed.
2321 if (DirectBaseSpec && VirtualBaseSpec)
2322 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002323 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002325 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002326 if (!BaseSpec)
2327 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2328
2329 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002330 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002331 Expr **Args = &Init;
2332 unsigned NumArgs = 1;
2333 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002334 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002335 Args = ParenList->getExprs();
2336 NumArgs = ParenList->getNumExprs();
2337 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002338
2339 InitializedEntity BaseEntity =
2340 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2341 InitializationKind Kind =
2342 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2343 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2344 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002345 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2346 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2347 MultiExprArg(*this, Args, NumArgs),
2348 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002349 if (BaseInit.isInvalid())
2350 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002351
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002352 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002353
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002354 // C++0x [class.base.init]p7:
2355 // The initialization of each base and member constitutes a
2356 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002357 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002358 if (BaseInit.isInvalid())
2359 return true;
2360
2361 // If we are in a dependent context, template instantiation will
2362 // perform this type-checking again. Just save the arguments that we
2363 // received in a ParenListExpr.
2364 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2365 // of the information that we have about the base
2366 // initializer. However, deconstructing the ASTs is a dicey process,
2367 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002368 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002369 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002370
Sean Huntcbb67482011-01-08 20:30:50 +00002371 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002372 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002374 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002375 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002376}
2377
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002378// Create a static_cast\<T&&>(expr).
2379static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2380 QualType ExprType = E->getType();
2381 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2382 SourceLocation ExprLoc = E->getLocStart();
2383 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2384 TargetType, ExprLoc);
2385
2386 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2387 SourceRange(ExprLoc, ExprLoc),
2388 E->getSourceRange()).take();
2389}
2390
Anders Carlssone5ef7402010-04-23 03:10:23 +00002391/// ImplicitInitializerKind - How an implicit base or member initializer should
2392/// initialize its base or member.
2393enum ImplicitInitializerKind {
2394 IIK_Default,
2395 IIK_Copy,
2396 IIK_Move
2397};
2398
Anders Carlssondefefd22010-04-23 02:00:02 +00002399static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002400BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002401 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002402 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002403 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002404 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002405 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002406 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2407 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002408
John McCall60d7b3a2010-08-24 06:29:42 +00002409 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002410
2411 switch (ImplicitInitKind) {
2412 case IIK_Default: {
2413 InitializationKind InitKind
2414 = InitializationKind::CreateDefault(Constructor->getLocation());
2415 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2416 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002417 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002418 break;
2419 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002420
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002421 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002422 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002423 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002424 ParmVarDecl *Param = Constructor->getParamDecl(0);
2425 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002426
Anders Carlssone5ef7402010-04-23 03:10:23 +00002427 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002428 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002429 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002430 Constructor->getLocation(), ParamType,
2431 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002432
Eli Friedman5f2987c2012-02-02 03:46:19 +00002433 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2434
Anders Carlssonc7957502010-04-24 22:02:54 +00002435 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002436 QualType ArgTy =
2437 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2438 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002439
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002440 if (Moving) {
2441 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2442 }
2443
John McCallf871d0c2010-08-07 06:22:56 +00002444 CXXCastPath BasePath;
2445 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002446 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2447 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002448 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002449 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002450
Anders Carlssone5ef7402010-04-23 03:10:23 +00002451 InitializationKind InitKind
2452 = InitializationKind::CreateDirect(Constructor->getLocation(),
2453 SourceLocation(), SourceLocation());
2454 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2455 &CopyCtorArg, 1);
2456 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002457 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002458 break;
2459 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002460 }
John McCall9ae2f072010-08-23 23:25:46 +00002461
Douglas Gregor53c374f2010-12-07 00:41:46 +00002462 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002463 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002464 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002465
Anders Carlssondefefd22010-04-23 02:00:02 +00002466 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002467 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002468 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2469 SourceLocation()),
2470 BaseSpec->isVirtual(),
2471 SourceLocation(),
2472 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002473 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002474 SourceLocation());
2475
Anders Carlssondefefd22010-04-23 02:00:02 +00002476 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002477}
2478
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002479static bool RefersToRValueRef(Expr *MemRef) {
2480 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2481 return Referenced->getType()->isRValueReferenceType();
2482}
2483
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002484static bool
2485BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002486 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002487 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002488 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002489 if (Field->isInvalidDecl())
2490 return true;
2491
Chandler Carruthf186b542010-06-29 23:50:44 +00002492 SourceLocation Loc = Constructor->getLocation();
2493
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002494 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2495 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002496 ParmVarDecl *Param = Constructor->getParamDecl(0);
2497 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002498
2499 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002500 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2501 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002502
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002503 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002504 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002505 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002506 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002507
Eli Friedman5f2987c2012-02-02 03:46:19 +00002508 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2509
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002510 if (Moving) {
2511 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2512 }
2513
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002514 // Build a reference to this field within the parameter.
2515 CXXScopeSpec SS;
2516 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2517 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002518 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2519 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002520 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002521 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002522 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002523 ParamType, Loc,
2524 /*IsArrow=*/false,
2525 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002526 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002527 /*FirstQualifierInScope=*/0,
2528 MemberLookup,
2529 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002530 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002531 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002532
2533 // C++11 [class.copy]p15:
2534 // - if a member m has rvalue reference type T&&, it is direct-initialized
2535 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002536 if (RefersToRValueRef(CtorArg.get())) {
2537 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002538 }
2539
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002540 // When the field we are copying is an array, create index variables for
2541 // each dimension of the array. We use these index variables to subscript
2542 // the source array, and other clients (e.g., CodeGen) will perform the
2543 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002544 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 QualType BaseType = Field->getType();
2546 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002547 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 while (const ConstantArrayType *Array
2549 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002550 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002551 // Create the iteration variable for this array index.
2552 IdentifierInfo *IterationVarName = 0;
2553 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002554 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002555 llvm::raw_svector_ostream OS(Str);
2556 OS << "__i" << IndexVariables.size();
2557 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2558 }
2559 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002560 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002561 IterationVarName, SizeType,
2562 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002563 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002564 IndexVariables.push_back(IterationVar);
2565
2566 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002567 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002568 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002569 assert(!IterationVarRef.isInvalid() &&
2570 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002571 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2572 assert(!IterationVarRef.isInvalid() &&
2573 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002574
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002575 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002576 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002577 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002578 Loc);
2579 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002580 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002581
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 BaseType = Array->getElementType();
2583 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002584
2585 // The array subscript expression is an lvalue, which is wrong for moving.
2586 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002587 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002588
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002589 // Construct the entity that we will be initializing. For an array, this
2590 // will be first element in the array, which may require several levels
2591 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002593 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002594 if (Indirect)
2595 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2596 else
2597 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002598 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2599 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2600 0,
2601 Entities.back()));
2602
2603 // Direct-initialize to use the copy constructor.
2604 InitializationKind InitKind =
2605 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2606
Sebastian Redl74e611a2011-09-04 18:14:28 +00002607 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002608 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002609 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610
John McCall60d7b3a2010-08-24 06:29:42 +00002611 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002613 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002614 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002615 if (MemberInit.isInvalid())
2616 return true;
2617
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002618 if (Indirect) {
2619 assert(IndexVariables.size() == 0 &&
2620 "Indirect field improperly initialized");
2621 CXXMemberInit
2622 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2623 Loc, Loc,
2624 MemberInit.takeAs<Expr>(),
2625 Loc);
2626 } else
2627 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2628 Loc, MemberInit.takeAs<Expr>(),
2629 Loc,
2630 IndexVariables.data(),
2631 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002632 return false;
2633 }
2634
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002635 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2636
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002637 QualType FieldBaseElementType =
2638 SemaRef.Context.getBaseElementType(Field->getType());
2639
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002640 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002641 InitializedEntity InitEntity
2642 = Indirect? InitializedEntity::InitializeMember(Indirect)
2643 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002644 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002645 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002646
2647 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002648 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002649 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002650
Douglas Gregor53c374f2010-12-07 00:41:46 +00002651 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002652 if (MemberInit.isInvalid())
2653 return true;
2654
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002655 if (Indirect)
2656 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2657 Indirect, Loc,
2658 Loc,
2659 MemberInit.get(),
2660 Loc);
2661 else
2662 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2663 Field, Loc, Loc,
2664 MemberInit.get(),
2665 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002666 return false;
2667 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002668
Sean Hunt1f2f3842011-05-17 00:19:05 +00002669 if (!Field->getParent()->isUnion()) {
2670 if (FieldBaseElementType->isReferenceType()) {
2671 SemaRef.Diag(Constructor->getLocation(),
2672 diag::err_uninitialized_member_in_ctor)
2673 << (int)Constructor->isImplicit()
2674 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2675 << 0 << Field->getDeclName();
2676 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2677 return true;
2678 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002679
Sean Hunt1f2f3842011-05-17 00:19:05 +00002680 if (FieldBaseElementType.isConstQualified()) {
2681 SemaRef.Diag(Constructor->getLocation(),
2682 diag::err_uninitialized_member_in_ctor)
2683 << (int)Constructor->isImplicit()
2684 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2685 << 1 << Field->getDeclName();
2686 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2687 return true;
2688 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002689 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002690
David Blaikie4e4d0842012-03-11 07:00:24 +00002691 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002692 FieldBaseElementType->isObjCRetainableType() &&
2693 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2694 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2695 // Instant objects:
2696 // Default-initialize Objective-C pointers to NULL.
2697 CXXMemberInit
2698 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2699 Loc, Loc,
2700 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2701 Loc);
2702 return false;
2703 }
2704
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002705 // Nothing to initialize.
2706 CXXMemberInit = 0;
2707 return false;
2708}
John McCallf1860e52010-05-20 23:23:51 +00002709
2710namespace {
2711struct BaseAndFieldInfo {
2712 Sema &S;
2713 CXXConstructorDecl *Ctor;
2714 bool AnyErrorsInInits;
2715 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002716 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002717 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002718
2719 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2720 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002721 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2722 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002723 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002724 else if (Generated && Ctor->isMoveConstructor())
2725 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002726 else
2727 IIK = IIK_Default;
2728 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002729
2730 bool isImplicitCopyOrMove() const {
2731 switch (IIK) {
2732 case IIK_Copy:
2733 case IIK_Move:
2734 return true;
2735
2736 case IIK_Default:
2737 return false;
2738 }
David Blaikie30263482012-01-20 21:50:17 +00002739
2740 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002741 }
John McCallf1860e52010-05-20 23:23:51 +00002742};
2743}
2744
Richard Smitha4950662011-09-19 13:34:43 +00002745/// \brief Determine whether the given indirect field declaration is somewhere
2746/// within an anonymous union.
2747static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2748 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2749 CEnd = F->chain_end();
2750 C != CEnd; ++C)
2751 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2752 if (Record->isUnion())
2753 return true;
2754
2755 return false;
2756}
2757
Douglas Gregorddb21472011-11-02 23:04:16 +00002758/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2759/// array type.
2760static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2761 if (T->isIncompleteArrayType())
2762 return true;
2763
2764 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2765 if (!ArrayT->getSize())
2766 return true;
2767
2768 T = ArrayT->getElementType();
2769 }
2770
2771 return false;
2772}
2773
Richard Smith7a614d82011-06-11 17:19:42 +00002774static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002775 FieldDecl *Field,
2776 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002777
Chandler Carruthe861c602010-06-30 02:59:29 +00002778 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002779 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002780 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002781 return false;
2782 }
2783
Richard Smith7a614d82011-06-11 17:19:42 +00002784 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2785 // has a brace-or-equal-initializer, the entity is initialized as specified
2786 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002787 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002788 CXXCtorInitializer *Init;
2789 if (Indirect)
2790 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2791 SourceLocation(),
2792 SourceLocation(), 0,
2793 SourceLocation());
2794 else
2795 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2796 SourceLocation(),
2797 SourceLocation(), 0,
2798 SourceLocation());
2799 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002800 return false;
2801 }
2802
Richard Smithc115f632011-09-18 11:14:50 +00002803 // Don't build an implicit initializer for union members if none was
2804 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002805 if (Field->getParent()->isUnion() ||
2806 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002807 return false;
2808
Douglas Gregorddb21472011-11-02 23:04:16 +00002809 // Don't initialize incomplete or zero-length arrays.
2810 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2811 return false;
2812
John McCallf1860e52010-05-20 23:23:51 +00002813 // Don't try to build an implicit initializer if there were semantic
2814 // errors in any of the initializers (and therefore we might be
2815 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002816 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002817 return false;
2818
Sean Huntcbb67482011-01-08 20:30:50 +00002819 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002820 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2821 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002822 return true;
John McCallf1860e52010-05-20 23:23:51 +00002823
Francois Pichet00eb3f92010-12-04 09:14:42 +00002824 if (Init)
2825 Info.AllToInit.push_back(Init);
2826
John McCallf1860e52010-05-20 23:23:51 +00002827 return false;
2828}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002829
2830bool
2831Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2832 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002833 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002834 Constructor->setNumCtorInitializers(1);
2835 CXXCtorInitializer **initializer =
2836 new (Context) CXXCtorInitializer*[1];
2837 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2838 Constructor->setCtorInitializers(initializer);
2839
Sean Huntb76af9c2011-05-03 23:05:34 +00002840 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002841 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002842 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2843 }
2844
Sean Huntc1598702011-05-05 00:05:47 +00002845 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002846
Sean Hunt059ce0d2011-05-01 07:04:31 +00002847 return false;
2848}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002849
John McCallb77115d2011-06-17 00:18:42 +00002850bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2851 CXXCtorInitializer **Initializers,
2852 unsigned NumInitializers,
2853 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002854 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002855 // Just store the initializers as written, they will be checked during
2856 // instantiation.
2857 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002858 Constructor->setNumCtorInitializers(NumInitializers);
2859 CXXCtorInitializer **baseOrMemberInitializers =
2860 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002861 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002862 NumInitializers * sizeof(CXXCtorInitializer*));
2863 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002864 }
2865
2866 return false;
2867 }
2868
John McCallf1860e52010-05-20 23:23:51 +00002869 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002870
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002871 // We need to build the initializer AST according to order of construction
2872 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002873 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002874 if (!ClassDecl)
2875 return true;
2876
Eli Friedman80c30da2009-11-09 19:20:36 +00002877 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002879 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002880 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002881
2882 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002883 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002884 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002885 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002886 }
2887
Anders Carlsson711f34a2010-04-21 19:52:01 +00002888 // Keep track of the direct virtual bases.
2889 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2890 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2891 E = ClassDecl->bases_end(); I != E; ++I) {
2892 if (I->isVirtual())
2893 DirectVBases.insert(I);
2894 }
2895
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002896 // Push virtual bases before others.
2897 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2898 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2899
Sean Huntcbb67482011-01-08 20:30:50 +00002900 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002901 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2902 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002903 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002904 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002905 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002906 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002907 VBase, IsInheritedVirtualBase,
2908 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002909 HadError = true;
2910 continue;
2911 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002912
John McCallf1860e52010-05-20 23:23:51 +00002913 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002914 }
2915 }
Mike Stump1eb44332009-09-09 15:08:12 +00002916
John McCallf1860e52010-05-20 23:23:51 +00002917 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002918 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2919 E = ClassDecl->bases_end(); Base != E; ++Base) {
2920 // Virtuals are in the virtual base list and already constructed.
2921 if (Base->isVirtual())
2922 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Sean Huntcbb67482011-01-08 20:30:50 +00002924 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002925 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2926 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002927 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002928 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002929 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002930 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002931 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002932 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002933 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002934 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002935
John McCallf1860e52010-05-20 23:23:51 +00002936 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002937 }
2938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
John McCallf1860e52010-05-20 23:23:51 +00002940 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002941 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2942 MemEnd = ClassDecl->decls_end();
2943 Mem != MemEnd; ++Mem) {
2944 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002945 // C++ [class.bit]p2:
2946 // A declaration for a bit-field that omits the identifier declares an
2947 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2948 // initialized.
2949 if (F->isUnnamedBitfield())
2950 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002951
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002952 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002953 // handle anonymous struct/union fields based on their individual
2954 // indirect fields.
2955 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2956 continue;
2957
2958 if (CollectFieldInitializer(*this, Info, F))
2959 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002960 continue;
2961 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002962
2963 // Beyond this point, we only consider default initialization.
2964 if (Info.IIK != IIK_Default)
2965 continue;
2966
2967 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2968 if (F->getType()->isIncompleteArrayType()) {
2969 assert(ClassDecl->hasFlexibleArrayMember() &&
2970 "Incomplete array type is not valid");
2971 continue;
2972 }
2973
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002974 // Initialize each field of an anonymous struct individually.
2975 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2976 HadError = true;
2977
2978 continue;
2979 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002980 }
Mike Stump1eb44332009-09-09 15:08:12 +00002981
John McCallf1860e52010-05-20 23:23:51 +00002982 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002983 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002984 Constructor->setNumCtorInitializers(NumInitializers);
2985 CXXCtorInitializer **baseOrMemberInitializers =
2986 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002987 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002988 NumInitializers * sizeof(CXXCtorInitializer*));
2989 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002990
John McCallef027fe2010-03-16 21:39:52 +00002991 // Constructors implicitly reference the base and member
2992 // destructors.
2993 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2994 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002995 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002996
2997 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002998}
2999
Eli Friedman6347f422009-07-21 19:28:10 +00003000static void *GetKeyForTopLevelField(FieldDecl *Field) {
3001 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003002 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003003 if (RT->getDecl()->isAnonymousStructOrUnion())
3004 return static_cast<void *>(RT->getDecl());
3005 }
3006 return static_cast<void *>(Field);
3007}
3008
Anders Carlssonea356fb2010-04-02 05:42:15 +00003009static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003010 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003011}
3012
Anders Carlssonea356fb2010-04-02 05:42:15 +00003013static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003014 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003015 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003016 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003017
Eli Friedman6347f422009-07-21 19:28:10 +00003018 // For fields injected into the class via declaration of an anonymous union,
3019 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003020 FieldDecl *Field = Member->getAnyMember();
3021
John McCall3c3ccdb2010-04-10 09:28:51 +00003022 // If the field is a member of an anonymous struct or union, our key
3023 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003024 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003025 if (RD->isAnonymousStructOrUnion()) {
3026 while (true) {
3027 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3028 if (Parent->isAnonymousStructOrUnion())
3029 RD = Parent;
3030 else
3031 break;
3032 }
3033
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003034 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003035 }
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003037 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003038}
3039
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003040static void
3041DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003042 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003043 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003044 unsigned NumInits) {
3045 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003046 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003048 // Don't check initializers order unless the warning is enabled at the
3049 // location of at least one initializer.
3050 bool ShouldCheckOrder = false;
3051 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003052 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003053 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3054 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003055 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003056 ShouldCheckOrder = true;
3057 break;
3058 }
3059 }
3060 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003061 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003062
John McCalld6ca8da2010-04-10 07:37:23 +00003063 // Build the list of bases and members in the order that they'll
3064 // actually be initialized. The explicit initializers should be in
3065 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003066 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Anders Carlsson071d6102010-04-02 03:38:04 +00003068 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3069
John McCalld6ca8da2010-04-10 07:37:23 +00003070 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003071 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003072 ClassDecl->vbases_begin(),
3073 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003074 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003075
John McCalld6ca8da2010-04-10 07:37:23 +00003076 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003077 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003078 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003079 if (Base->isVirtual())
3080 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003081 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003082 }
Mike Stump1eb44332009-09-09 15:08:12 +00003083
John McCalld6ca8da2010-04-10 07:37:23 +00003084 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003085 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003086 E = ClassDecl->field_end(); Field != E; ++Field) {
3087 if (Field->isUnnamedBitfield())
3088 continue;
3089
David Blaikie262bc182012-04-30 02:36:29 +00003090 IdealInitKeys.push_back(GetKeyForTopLevelField(&*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003091 }
3092
John McCalld6ca8da2010-04-10 07:37:23 +00003093 unsigned NumIdealInits = IdealInitKeys.size();
3094 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003095
Sean Huntcbb67482011-01-08 20:30:50 +00003096 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003097 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003098 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003099 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003100
3101 // Scan forward to try to find this initializer in the idealized
3102 // initializers list.
3103 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3104 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003105 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003106
3107 // If we didn't find this initializer, it must be because we
3108 // scanned past it on a previous iteration. That can only
3109 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003110 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003111 Sema::SemaDiagnosticBuilder D =
3112 SemaRef.Diag(PrevInit->getSourceLocation(),
3113 diag::warn_initializer_out_of_order);
3114
Francois Pichet00eb3f92010-12-04 09:14:42 +00003115 if (PrevInit->isAnyMemberInitializer())
3116 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003117 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003118 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003119
Francois Pichet00eb3f92010-12-04 09:14:42 +00003120 if (Init->isAnyMemberInitializer())
3121 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003122 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003123 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003124
3125 // Move back to the initializer's location in the ideal list.
3126 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3127 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003128 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003129
3130 assert(IdealIndex != NumIdealInits &&
3131 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003132 }
John McCalld6ca8da2010-04-10 07:37:23 +00003133
3134 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003135 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003136}
3137
John McCall3c3ccdb2010-04-10 09:28:51 +00003138namespace {
3139bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003140 CXXCtorInitializer *Init,
3141 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003142 if (!PrevInit) {
3143 PrevInit = Init;
3144 return false;
3145 }
3146
3147 if (FieldDecl *Field = Init->getMember())
3148 S.Diag(Init->getSourceLocation(),
3149 diag::err_multiple_mem_initialization)
3150 << Field->getDeclName()
3151 << Init->getSourceRange();
3152 else {
John McCallf4c73712011-01-19 06:33:43 +00003153 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003154 assert(BaseClass && "neither field nor base");
3155 S.Diag(Init->getSourceLocation(),
3156 diag::err_multiple_base_initialization)
3157 << QualType(BaseClass, 0)
3158 << Init->getSourceRange();
3159 }
3160 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3161 << 0 << PrevInit->getSourceRange();
3162
3163 return true;
3164}
3165
Sean Huntcbb67482011-01-08 20:30:50 +00003166typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003167typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3168
3169bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003170 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003171 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003172 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003173 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003174 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003175
3176 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003177 if (Parent->isUnion()) {
3178 UnionEntry &En = Unions[Parent];
3179 if (En.first && En.first != Child) {
3180 S.Diag(Init->getSourceLocation(),
3181 diag::err_multiple_mem_union_initialization)
3182 << Field->getDeclName()
3183 << Init->getSourceRange();
3184 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3185 << 0 << En.second->getSourceRange();
3186 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003187 }
3188 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003189 En.first = Child;
3190 En.second = Init;
3191 }
David Blaikie6fe29652011-11-17 06:01:57 +00003192 if (!Parent->isAnonymousStructOrUnion())
3193 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003194 }
3195
3196 Child = Parent;
3197 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003198 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003199
3200 return false;
3201}
3202}
3203
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003204/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003205void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003206 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003207 CXXCtorInitializer **meminits,
3208 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003209 bool AnyErrors) {
3210 if (!ConstructorDecl)
3211 return;
3212
3213 AdjustDeclIfTemplate(ConstructorDecl);
3214
3215 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003216 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003217
3218 if (!Constructor) {
3219 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3220 return;
3221 }
3222
Sean Huntcbb67482011-01-08 20:30:50 +00003223 CXXCtorInitializer **MemInits =
3224 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003225
3226 // Mapping for the duplicate initializers check.
3227 // For member initializers, this is keyed with a FieldDecl*.
3228 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003229 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003230
3231 // Mapping for the inconsistent anonymous-union initializers check.
3232 RedundantUnionMap MemberUnions;
3233
Anders Carlssonea356fb2010-04-02 05:42:15 +00003234 bool HadError = false;
3235 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003236 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003237
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003238 // Set the source order index.
3239 Init->setSourceOrder(i);
3240
Francois Pichet00eb3f92010-12-04 09:14:42 +00003241 if (Init->isAnyMemberInitializer()) {
3242 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003243 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3244 CheckRedundantUnionInit(*this, Init, MemberUnions))
3245 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003246 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003247 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3248 if (CheckRedundantInit(*this, Init, Members[Key]))
3249 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003250 } else {
3251 assert(Init->isDelegatingInitializer());
3252 // This must be the only initializer
3253 if (i != 0 || NumMemInits > 1) {
3254 Diag(MemInits[0]->getSourceLocation(),
3255 diag::err_delegating_initializer_alone)
3256 << MemInits[0]->getSourceRange();
3257 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003258 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003259 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003260 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003261 // Return immediately as the initializer is set.
3262 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003263 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003264 }
3265
Anders Carlssonea356fb2010-04-02 05:42:15 +00003266 if (HadError)
3267 return;
3268
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003269 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003270
Sean Huntcbb67482011-01-08 20:30:50 +00003271 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003272}
3273
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003274void
John McCallef027fe2010-03-16 21:39:52 +00003275Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3276 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003277 // Ignore dependent contexts. Also ignore unions, since their members never
3278 // have destructors implicitly called.
3279 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003280 return;
John McCall58e6f342010-03-16 05:22:47 +00003281
3282 // FIXME: all the access-control diagnostics are positioned on the
3283 // field/base declaration. That's probably good; that said, the
3284 // user might reasonably want to know why the destructor is being
3285 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003286
Anders Carlsson9f853df2009-11-17 04:44:12 +00003287 // Non-static data members.
3288 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3289 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00003290 FieldDecl *Field = &*I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003291 if (Field->isInvalidDecl())
3292 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003293
3294 // Don't destroy incomplete or zero-length arrays.
3295 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3296 continue;
3297
Anders Carlsson9f853df2009-11-17 04:44:12 +00003298 QualType FieldType = Context.getBaseElementType(Field->getType());
3299
3300 const RecordType* RT = FieldType->getAs<RecordType>();
3301 if (!RT)
3302 continue;
3303
3304 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003305 if (FieldClassDecl->isInvalidDecl())
3306 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003307 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003308 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003309 // The destructor for an implicit anonymous union member is never invoked.
3310 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3311 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003312
Douglas Gregordb89f282010-07-01 22:47:18 +00003313 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003314 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003315 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003316 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003317 << Field->getDeclName()
3318 << FieldType);
3319
Eli Friedman5f2987c2012-02-02 03:46:19 +00003320 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003321 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003322 }
3323
John McCall58e6f342010-03-16 05:22:47 +00003324 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3325
Anders Carlsson9f853df2009-11-17 04:44:12 +00003326 // Bases.
3327 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3328 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003329 // Bases are always records in a well-formed non-dependent class.
3330 const RecordType *RT = Base->getType()->getAs<RecordType>();
3331
3332 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003333 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003334 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003335
John McCall58e6f342010-03-16 05:22:47 +00003336 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003337 // If our base class is invalid, we probably can't get its dtor anyway.
3338 if (BaseClassDecl->isInvalidDecl())
3339 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003340 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003341 continue;
John McCall58e6f342010-03-16 05:22:47 +00003342
Douglas Gregordb89f282010-07-01 22:47:18 +00003343 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003344 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003345
3346 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003347 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003348 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003349 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003350 << Base->getSourceRange(),
3351 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003352
Eli Friedman5f2987c2012-02-02 03:46:19 +00003353 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003354 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003355 }
3356
3357 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003358 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3359 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003360
3361 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003362 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003363
3364 // Ignore direct virtual bases.
3365 if (DirectVirtualBases.count(RT))
3366 continue;
3367
John McCall58e6f342010-03-16 05:22:47 +00003368 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003369 // If our base class is invalid, we probably can't get its dtor anyway.
3370 if (BaseClassDecl->isInvalidDecl())
3371 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003372 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003373 continue;
John McCall58e6f342010-03-16 05:22:47 +00003374
Douglas Gregordb89f282010-07-01 22:47:18 +00003375 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003376 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003377 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003378 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003379 << VBase->getType(),
3380 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003381
Eli Friedman5f2987c2012-02-02 03:46:19 +00003382 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003383 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003384 }
3385}
3386
John McCalld226f652010-08-21 09:40:31 +00003387void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003388 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003389 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Mike Stump1eb44332009-09-09 15:08:12 +00003391 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003392 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003393 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003394}
3395
Mike Stump1eb44332009-09-09 15:08:12 +00003396bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003397 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003398 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3399 unsigned DiagID;
3400 AbstractDiagSelID SelID;
3401
3402 public:
3403 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3404 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3405
3406 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3407 if (SelID == -1)
3408 S.Diag(Loc, DiagID) << T;
3409 else
3410 S.Diag(Loc, DiagID) << SelID << T;
3411 }
3412 } Diagnoser(DiagID, SelID);
3413
3414 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003415}
3416
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003417bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003418 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003419 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Anders Carlsson11f21a02009-03-23 19:10:31 +00003422 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003423 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Ted Kremenek6217b802009-07-29 21:53:49 +00003425 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003426 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003427 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003428 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003430 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003431 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003432 }
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Ted Kremenek6217b802009-07-29 21:53:49 +00003434 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003435 if (!RT)
3436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003437
John McCall86ff3082010-02-04 22:26:26 +00003438 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003439
John McCall94c3b562010-08-18 09:41:07 +00003440 // We can't answer whether something is abstract until it has a
3441 // definition. If it's currently being defined, we'll walk back
3442 // over all the declarations when we have a full definition.
3443 const CXXRecordDecl *Def = RD->getDefinition();
3444 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003445 return false;
3446
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003447 if (!RD->isAbstract())
3448 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003450 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003451 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003452
John McCall94c3b562010-08-18 09:41:07 +00003453 return true;
3454}
3455
3456void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3457 // Check if we've already emitted the list of pure virtual functions
3458 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003459 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003460 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003462 CXXFinalOverriderMap FinalOverriders;
3463 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003465 // Keep a set of seen pure methods so we won't diagnose the same method
3466 // more than once.
3467 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3468
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003469 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3470 MEnd = FinalOverriders.end();
3471 M != MEnd;
3472 ++M) {
3473 for (OverridingMethods::iterator SO = M->second.begin(),
3474 SOEnd = M->second.end();
3475 SO != SOEnd; ++SO) {
3476 // C++ [class.abstract]p4:
3477 // A class is abstract if it contains or inherits at least one
3478 // pure virtual function for which the final overrider is pure
3479 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003481 //
3482 if (SO->second.size() != 1)
3483 continue;
3484
3485 if (!SO->second.front().Method->isPure())
3486 continue;
3487
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003488 if (!SeenPureMethods.insert(SO->second.front().Method))
3489 continue;
3490
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003491 Diag(SO->second.front().Method->getLocation(),
3492 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003493 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003494 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003495 }
3496
3497 if (!PureVirtualClassDiagSet)
3498 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3499 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003500}
3501
Anders Carlsson8211eff2009-03-24 01:19:16 +00003502namespace {
John McCall94c3b562010-08-18 09:41:07 +00003503struct AbstractUsageInfo {
3504 Sema &S;
3505 CXXRecordDecl *Record;
3506 CanQualType AbstractType;
3507 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003508
John McCall94c3b562010-08-18 09:41:07 +00003509 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3510 : S(S), Record(Record),
3511 AbstractType(S.Context.getCanonicalType(
3512 S.Context.getTypeDeclType(Record))),
3513 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003514
John McCall94c3b562010-08-18 09:41:07 +00003515 void DiagnoseAbstractType() {
3516 if (Invalid) return;
3517 S.DiagnoseAbstractType(Record);
3518 Invalid = true;
3519 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003520
John McCall94c3b562010-08-18 09:41:07 +00003521 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3522};
3523
3524struct CheckAbstractUsage {
3525 AbstractUsageInfo &Info;
3526 const NamedDecl *Ctx;
3527
3528 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3529 : Info(Info), Ctx(Ctx) {}
3530
3531 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3532 switch (TL.getTypeLocClass()) {
3533#define ABSTRACT_TYPELOC(CLASS, PARENT)
3534#define TYPELOC(CLASS, PARENT) \
3535 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3536#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003537 }
John McCall94c3b562010-08-18 09:41:07 +00003538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCall94c3b562010-08-18 09:41:07 +00003540 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3541 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3542 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003543 if (!TL.getArg(I))
3544 continue;
3545
John McCall94c3b562010-08-18 09:41:07 +00003546 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3547 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003548 }
John McCall94c3b562010-08-18 09:41:07 +00003549 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003550
John McCall94c3b562010-08-18 09:41:07 +00003551 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3552 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3553 }
Mike Stump1eb44332009-09-09 15:08:12 +00003554
John McCall94c3b562010-08-18 09:41:07 +00003555 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3556 // Visit the type parameters from a permissive context.
3557 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3558 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3559 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3560 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3561 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3562 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003563 }
John McCall94c3b562010-08-18 09:41:07 +00003564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565
John McCall94c3b562010-08-18 09:41:07 +00003566 // Visit pointee types from a permissive context.
3567#define CheckPolymorphic(Type) \
3568 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3569 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3570 }
3571 CheckPolymorphic(PointerTypeLoc)
3572 CheckPolymorphic(ReferenceTypeLoc)
3573 CheckPolymorphic(MemberPointerTypeLoc)
3574 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003575 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003576
John McCall94c3b562010-08-18 09:41:07 +00003577 /// Handle all the types we haven't given a more specific
3578 /// implementation for above.
3579 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3580 // Every other kind of type that we haven't called out already
3581 // that has an inner type is either (1) sugar or (2) contains that
3582 // inner type in some way as a subobject.
3583 if (TypeLoc Next = TL.getNextTypeLoc())
3584 return Visit(Next, Sel);
3585
3586 // If there's no inner type and we're in a permissive context,
3587 // don't diagnose.
3588 if (Sel == Sema::AbstractNone) return;
3589
3590 // Check whether the type matches the abstract type.
3591 QualType T = TL.getType();
3592 if (T->isArrayType()) {
3593 Sel = Sema::AbstractArrayType;
3594 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003595 }
John McCall94c3b562010-08-18 09:41:07 +00003596 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3597 if (CT != Info.AbstractType) return;
3598
3599 // It matched; do some magic.
3600 if (Sel == Sema::AbstractArrayType) {
3601 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3602 << T << TL.getSourceRange();
3603 } else {
3604 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3605 << Sel << T << TL.getSourceRange();
3606 }
3607 Info.DiagnoseAbstractType();
3608 }
3609};
3610
3611void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3612 Sema::AbstractDiagSelID Sel) {
3613 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3614}
3615
3616}
3617
3618/// Check for invalid uses of an abstract type in a method declaration.
3619static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3620 CXXMethodDecl *MD) {
3621 // No need to do the check on definitions, which require that
3622 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003623 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003624 return;
3625
3626 // For safety's sake, just ignore it if we don't have type source
3627 // information. This should never happen for non-implicit methods,
3628 // but...
3629 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3630 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3631}
3632
3633/// Check for invalid uses of an abstract type within a class definition.
3634static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3635 CXXRecordDecl *RD) {
3636 for (CXXRecordDecl::decl_iterator
3637 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3638 Decl *D = *I;
3639 if (D->isImplicit()) continue;
3640
3641 // Methods and method templates.
3642 if (isa<CXXMethodDecl>(D)) {
3643 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3644 } else if (isa<FunctionTemplateDecl>(D)) {
3645 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3646 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3647
3648 // Fields and static variables.
3649 } else if (isa<FieldDecl>(D)) {
3650 FieldDecl *FD = cast<FieldDecl>(D);
3651 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3652 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3653 } else if (isa<VarDecl>(D)) {
3654 VarDecl *VD = cast<VarDecl>(D);
3655 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3656 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3657
3658 // Nested classes and class templates.
3659 } else if (isa<CXXRecordDecl>(D)) {
3660 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3661 } else if (isa<ClassTemplateDecl>(D)) {
3662 CheckAbstractClassUsage(Info,
3663 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3664 }
3665 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003666}
3667
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003668/// \brief Perform semantic checks on a class definition that has been
3669/// completing, introducing implicitly-declared members, checking for
3670/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003671void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003672 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003673 return;
3674
John McCall94c3b562010-08-18 09:41:07 +00003675 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3676 AbstractUsageInfo Info(*this, Record);
3677 CheckAbstractClassUsage(Info, Record);
3678 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003679
3680 // If this is not an aggregate type and has no user-declared constructor,
3681 // complain about any non-static data members of reference or const scalar
3682 // type, since they will never get initializers.
3683 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003684 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3685 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003686 bool Complained = false;
3687 for (RecordDecl::field_iterator F = Record->field_begin(),
3688 FEnd = Record->field_end();
3689 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003690 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003691 continue;
3692
Douglas Gregor325e5932010-04-15 00:00:53 +00003693 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003694 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003695 if (!Complained) {
3696 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3697 << Record->getTagKind() << Record;
3698 Complained = true;
3699 }
3700
3701 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3702 << F->getType()->isReferenceType()
3703 << F->getDeclName();
3704 }
3705 }
3706 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003707
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003708 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003709 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003710
3711 if (Record->getIdentifier()) {
3712 // C++ [class.mem]p13:
3713 // If T is the name of a class, then each of the following shall have a
3714 // name different from T:
3715 // - every member of every anonymous union that is a member of class T.
3716 //
3717 // C++ [class.mem]p14:
3718 // In addition, if class T has a user-declared constructor (12.1), every
3719 // non-static data member of class T shall have a name different from T.
3720 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003721 R.first != R.second; ++R.first) {
3722 NamedDecl *D = *R.first;
3723 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3724 isa<IndirectFieldDecl>(D)) {
3725 Diag(D->getLocation(), diag::err_member_name_of_class)
3726 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003727 break;
3728 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003729 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003730 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003731
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003732 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003733 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003734 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003735 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003736 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3737 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3738 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003739
3740 // See if a method overloads virtual methods in a base
3741 /// class without overriding any.
3742 if (!Record->isDependentType()) {
3743 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3744 MEnd = Record->method_end();
3745 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003746 if (!M->isStatic())
3747 DiagnoseHiddenVirtualMethods(Record, &*M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003748 }
3749 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003750
Richard Smith9f569cc2011-10-01 02:31:28 +00003751 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3752 // function that is not a constructor declares that member function to be
3753 // const. [...] The class of which that function is a member shall be
3754 // a literal type.
3755 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003756 // If the class has virtual bases, any constexpr members will already have
3757 // been diagnosed by the checks performed on the member declaration, so
3758 // suppress this (less useful) diagnostic.
3759 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3760 !Record->isLiteral() && !Record->getNumVBases()) {
3761 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3762 MEnd = Record->method_end();
3763 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003764 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003765 switch (Record->getTemplateSpecializationKind()) {
3766 case TSK_ImplicitInstantiation:
3767 case TSK_ExplicitInstantiationDeclaration:
3768 case TSK_ExplicitInstantiationDefinition:
3769 // If a template instantiates to a non-literal type, but its members
3770 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003771 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003772 continue;
3773
3774 case TSK_Undeclared:
3775 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003776 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003777 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003778 break;
3779 }
3780
3781 // Only produce one error per class.
3782 break;
3783 }
3784 }
3785 }
3786
Sebastian Redlf677ea32011-02-05 19:23:19 +00003787 // Declare inherited constructors. We do this eagerly here because:
3788 // - The standard requires an eager diagnostic for conflicting inherited
3789 // constructors from different classes.
3790 // - The lazy declaration of the other implicit constructors is so as to not
3791 // waste space and performance on classes that are not meant to be
3792 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3793 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003794 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003795
Sean Hunteb88ae52011-05-23 21:07:59 +00003796 if (!Record->isDependentType())
3797 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003798}
3799
3800void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003801 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3802 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003803 MI != ME; ++MI)
3804 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3805 CheckExplicitlyDefaultedSpecialMember(&*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003806}
3807
Richard Smith3003e1d2012-05-15 04:39:51 +00003808void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
3809 CXXRecordDecl *RD = MD->getParent();
3810 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00003811
Richard Smith3003e1d2012-05-15 04:39:51 +00003812 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
3813 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00003814
3815 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00003816 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00003817 bool First = MD == MD->getCanonicalDecl();
3818
3819 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00003820
3821 // C++11 [dcl.fct.def.default]p1:
3822 // A function that is explicitly defaulted shall
3823 // -- be a special member function (checked elsewhere),
3824 // -- have the same type (except for ref-qualifiers, and except that a
3825 // copy operation can take a non-const reference) as an implicit
3826 // declaration, and
3827 // -- not have default arguments.
3828 unsigned ExpectedParams = 1;
3829 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
3830 ExpectedParams = 0;
3831 if (MD->getNumParams() != ExpectedParams) {
3832 // This also checks for default arguments: a copy or move constructor with a
3833 // default argument is classified as a default constructor, and assignment
3834 // operations and destructors can't have default arguments.
3835 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
3836 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00003837 HadError = true;
3838 }
3839
Richard Smith3003e1d2012-05-15 04:39:51 +00003840 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00003841
Richard Smith3003e1d2012-05-15 04:39:51 +00003842 // Compute implicit exception specification, argument constness, constexpr
3843 // and triviality.
Richard Smithe6975e92012-04-17 00:58:00 +00003844 ImplicitExceptionSpecification Spec(*this);
Richard Smith3003e1d2012-05-15 04:39:51 +00003845 bool Const = false;
3846 bool Constexpr = false;
3847 bool Trivial;
3848 switch (CSM) {
3849 case CXXDefaultConstructor:
3850 Spec = ComputeDefaultedDefaultCtorExceptionSpec(RD);
3851 if (Spec.isDelayed())
3852 // Exception specification depends on some deferred part of the class.
3853 // We'll try again when the class's definition has been fully processed.
3854 return;
3855 Constexpr = RD->defaultedDefaultConstructorIsConstexpr();
3856 Trivial = RD->hasTrivialDefaultConstructor();
3857 break;
3858 case CXXCopyConstructor:
3859 llvm::tie(Spec, Const) =
3860 ComputeDefaultedCopyCtorExceptionSpecAndConst(RD);
3861 Constexpr = RD->defaultedCopyConstructorIsConstexpr();
3862 Trivial = RD->hasTrivialCopyConstructor();
3863 break;
3864 case CXXCopyAssignment:
3865 llvm::tie(Spec, Const) =
3866 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(RD);
3867 Trivial = RD->hasTrivialCopyAssignment();
3868 break;
3869 case CXXMoveConstructor:
3870 Spec = ComputeDefaultedMoveCtorExceptionSpec(RD);
3871 Constexpr = RD->defaultedMoveConstructorIsConstexpr();
3872 Trivial = RD->hasTrivialMoveConstructor();
3873 break;
3874 case CXXMoveAssignment:
3875 Spec = ComputeDefaultedMoveAssignmentExceptionSpec(RD);
3876 Trivial = RD->hasTrivialMoveAssignment();
3877 break;
3878 case CXXDestructor:
3879 Spec = ComputeDefaultedDtorExceptionSpec(RD);
3880 Trivial = RD->hasTrivialDestructor();
3881 break;
3882 case CXXInvalid:
3883 llvm_unreachable("non-special member explicitly defaulted!");
3884 }
Sean Hunt2b188082011-05-14 05:23:28 +00003885
Richard Smith3003e1d2012-05-15 04:39:51 +00003886 QualType ReturnType = Context.VoidTy;
3887 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
3888 // Check for return type matching.
3889 ReturnType = Type->getResultType();
3890 QualType ExpectedReturnType =
3891 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
3892 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
3893 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
3894 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
3895 HadError = true;
3896 }
3897
3898 // A defaulted special member cannot have cv-qualifiers.
3899 if (Type->getTypeQuals()) {
3900 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
3901 << (CSM == CXXMoveAssignment);
3902 HadError = true;
3903 }
3904 }
3905
3906 // Check for parameter type matching.
3907 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
3908 if (ExpectedParams && ArgType->isReferenceType()) {
3909 // Argument must be reference to possibly-const T.
3910 QualType ReferentType = ArgType->getPointeeType();
3911
3912 if (ReferentType.isVolatileQualified()) {
3913 Diag(MD->getLocation(),
3914 diag::err_defaulted_special_member_volatile_param) << CSM;
3915 HadError = true;
3916 }
3917
3918 if (ReferentType.isConstQualified() && !Const) {
3919 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
3920 Diag(MD->getLocation(),
3921 diag::err_defaulted_special_member_copy_const_param)
3922 << (CSM == CXXCopyAssignment);
3923 // FIXME: Explain why this special member can't be const.
3924 } else {
3925 Diag(MD->getLocation(),
3926 diag::err_defaulted_special_member_move_const_param)
3927 << (CSM == CXXMoveAssignment);
3928 }
3929 HadError = true;
3930 }
3931
3932 // If a function is explicitly defaulted on its first declaration, it shall
3933 // have the same parameter type as if it had been implicitly declared.
3934 // (Presumably this is to prevent it from being trivial?)
3935 if (!ReferentType.isConstQualified() && Const && First)
3936 Diag(MD->getLocation(),
3937 diag::err_defaulted_special_member_copy_non_const_param)
3938 << (CSM == CXXCopyAssignment);
3939 } else if (ExpectedParams) {
3940 // A copy assignment operator can take its argument by value, but a
3941 // defaulted one cannot.
3942 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00003943 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003944 HadError = true;
3945 }
Sean Huntbe631222011-05-17 20:44:43 +00003946
Richard Smith3003e1d2012-05-15 04:39:51 +00003947 // Rebuild the type with the implicit exception specification added.
3948 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
3949 Spec.getEPI(EPI);
3950 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
3951 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003952
Richard Smith61802452011-12-22 02:22:31 +00003953 // C++11 [dcl.fct.def.default]p2:
3954 // An explicitly-defaulted function may be declared constexpr only if it
3955 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00003956 // Do not apply this rule to members of class templates, since core issue 1358
3957 // makes such functions always instantiate to constexpr functions. For
3958 // non-constructors, this is checked elsewhere.
3959 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
3960 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3961 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
3962 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00003963 }
3964 // and may have an explicit exception-specification only if it is compatible
3965 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00003966 if (Type->hasExceptionSpec() &&
3967 CheckEquivalentExceptionSpec(
3968 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
3969 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
3970 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00003971
3972 // If a function is explicitly defaulted on its first declaration,
3973 if (First) {
3974 // -- it is implicitly considered to be constexpr if the implicit
3975 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00003976 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00003977
Richard Smith3003e1d2012-05-15 04:39:51 +00003978 // -- it is implicitly considered to have the same exception-specification
3979 // as if it had been implicitly declared,
3980 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00003981
3982 // Such a function is also trivial if the implicitly-declared function
3983 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00003984 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003985 }
3986
Richard Smith3003e1d2012-05-15 04:39:51 +00003987 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003988 if (First) {
3989 MD->setDeletedAsWritten();
3990 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00003991 // C++11 [dcl.fct.def.default]p4:
3992 // [For a] user-provided explicitly-defaulted function [...] if such a
3993 // function is implicitly defined as deleted, the program is ill-formed.
3994 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
3995 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003996 }
3997 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003998
Richard Smith3003e1d2012-05-15 04:39:51 +00003999 if (HadError)
4000 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004001}
4002
Richard Smith7d5088a2012-02-18 02:02:13 +00004003namespace {
4004struct SpecialMemberDeletionInfo {
4005 Sema &S;
4006 CXXMethodDecl *MD;
4007 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004008 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004009
4010 // Properties of the special member, computed for convenience.
4011 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4012 SourceLocation Loc;
4013
4014 bool AllFieldsAreConst;
4015
4016 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004017 Sema::CXXSpecialMember CSM, bool Diagnose)
4018 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004019 IsConstructor(false), IsAssignment(false), IsMove(false),
4020 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4021 AllFieldsAreConst(true) {
4022 switch (CSM) {
4023 case Sema::CXXDefaultConstructor:
4024 case Sema::CXXCopyConstructor:
4025 IsConstructor = true;
4026 break;
4027 case Sema::CXXMoveConstructor:
4028 IsConstructor = true;
4029 IsMove = true;
4030 break;
4031 case Sema::CXXCopyAssignment:
4032 IsAssignment = true;
4033 break;
4034 case Sema::CXXMoveAssignment:
4035 IsAssignment = true;
4036 IsMove = true;
4037 break;
4038 case Sema::CXXDestructor:
4039 break;
4040 case Sema::CXXInvalid:
4041 llvm_unreachable("invalid special member kind");
4042 }
4043
4044 if (MD->getNumParams()) {
4045 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4046 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4047 }
4048 }
4049
4050 bool inUnion() const { return MD->getParent()->isUnion(); }
4051
4052 /// Look up the corresponding special member in the given class.
4053 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4054 unsigned TQ = MD->getTypeQualifiers();
4055 return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4056 MD->getRefQualifier() == RQ_RValue,
4057 TQ & Qualifiers::Const,
4058 TQ & Qualifiers::Volatile);
4059 }
4060
Richard Smith6c4c36c2012-03-30 20:53:28 +00004061 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004062
Richard Smith6c4c36c2012-03-30 20:53:28 +00004063 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004064 bool shouldDeleteForField(FieldDecl *FD);
4065 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004066
4067 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4068 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4069 Sema::SpecialMemberOverloadResult *SMOR,
4070 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004071
4072 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004073};
4074}
4075
John McCall12d8d802012-04-09 20:53:23 +00004076/// Is the given special member inaccessible when used on the given
4077/// sub-object.
4078bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4079 CXXMethodDecl *target) {
4080 /// If we're operating on a base class, the object type is the
4081 /// type of this special member.
4082 QualType objectTy;
4083 AccessSpecifier access = target->getAccess();;
4084 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4085 objectTy = S.Context.getTypeDeclType(MD->getParent());
4086 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4087
4088 // If we're operating on a field, the object type is the type of the field.
4089 } else {
4090 objectTy = S.Context.getTypeDeclType(target->getParent());
4091 }
4092
4093 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4094}
4095
Richard Smith6c4c36c2012-03-30 20:53:28 +00004096/// Check whether we should delete a special member due to the implicit
4097/// definition containing a call to a special member of a subobject.
4098bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4099 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4100 bool IsDtorCallInCtor) {
4101 CXXMethodDecl *Decl = SMOR->getMethod();
4102 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4103
4104 int DiagKind = -1;
4105
4106 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4107 DiagKind = !Decl ? 0 : 1;
4108 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4109 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004110 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004111 DiagKind = 3;
4112 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4113 !Decl->isTrivial()) {
4114 // A member of a union must have a trivial corresponding special member.
4115 // As a weird special case, a destructor call from a union's constructor
4116 // must be accessible and non-deleted, but need not be trivial. Such a
4117 // destructor is never actually called, but is semantically checked as
4118 // if it were.
4119 DiagKind = 4;
4120 }
4121
4122 if (DiagKind == -1)
4123 return false;
4124
4125 if (Diagnose) {
4126 if (Field) {
4127 S.Diag(Field->getLocation(),
4128 diag::note_deleted_special_member_class_subobject)
4129 << CSM << MD->getParent() << /*IsField*/true
4130 << Field << DiagKind << IsDtorCallInCtor;
4131 } else {
4132 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4133 S.Diag(Base->getLocStart(),
4134 diag::note_deleted_special_member_class_subobject)
4135 << CSM << MD->getParent() << /*IsField*/false
4136 << Base->getType() << DiagKind << IsDtorCallInCtor;
4137 }
4138
4139 if (DiagKind == 1)
4140 S.NoteDeletedFunction(Decl);
4141 // FIXME: Explain inaccessibility if DiagKind == 3.
4142 }
4143
4144 return true;
4145}
4146
Richard Smith9a561d52012-02-26 09:11:52 +00004147/// Check whether we should delete a special member function due to having a
4148/// direct or virtual base class or static data member of class type M.
4149bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith6c4c36c2012-03-30 20:53:28 +00004150 CXXRecordDecl *Class, Subobject Subobj) {
4151 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004152
4153 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004154 // -- any direct or virtual base class, or non-static data member with no
4155 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004156 // either M has no default constructor or overload resolution as applied
4157 // to M's default constructor results in an ambiguity or in a function
4158 // that is deleted or inaccessible
4159 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4160 // -- a direct or virtual base class B that cannot be copied/moved because
4161 // overload resolution, as applied to B's corresponding special member,
4162 // results in an ambiguity or a function that is deleted or inaccessible
4163 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004164 // C++11 [class.dtor]p5:
4165 // -- any direct or virtual base class [...] has a type with a destructor
4166 // that is deleted or inaccessible
4167 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004168 Field && Field->hasInClassInitializer()) &&
4169 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4170 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004171
Richard Smith6c4c36c2012-03-30 20:53:28 +00004172 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4173 // -- any direct or virtual base class or non-static data member has a
4174 // type with a destructor that is deleted or inaccessible
4175 if (IsConstructor) {
4176 Sema::SpecialMemberOverloadResult *SMOR =
4177 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4178 false, false, false, false, false);
4179 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4180 return true;
4181 }
4182
Richard Smith9a561d52012-02-26 09:11:52 +00004183 return false;
4184}
4185
4186/// Check whether we should delete a special member function due to the class
4187/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004188bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004189 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4190 return shouldDeleteForClassSubobject(BaseClass, Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004191}
4192
4193/// Check whether we should delete a special member function due to the class
4194/// having a particular non-static data member.
4195bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4196 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4197 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4198
4199 if (CSM == Sema::CXXDefaultConstructor) {
4200 // For a default constructor, all references must be initialized in-class
4201 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004202 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4203 if (Diagnose)
4204 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4205 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004206 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004207 }
Richard Smith79363f52012-02-27 06:07:25 +00004208 // C++11 [class.ctor]p5: any non-variant non-static data member of
4209 // const-qualified type (or array thereof) with no
4210 // brace-or-equal-initializer does not have a user-provided default
4211 // constructor.
4212 if (!inUnion() && FieldType.isConstQualified() &&
4213 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004214 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4215 if (Diagnose)
4216 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004217 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004218 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004219 }
4220
4221 if (inUnion() && !FieldType.isConstQualified())
4222 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004223 } else if (CSM == Sema::CXXCopyConstructor) {
4224 // For a copy constructor, data members must not be of rvalue reference
4225 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004226 if (FieldType->isRValueReferenceType()) {
4227 if (Diagnose)
4228 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4229 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004230 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004231 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004232 } else if (IsAssignment) {
4233 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004234 if (FieldType->isReferenceType()) {
4235 if (Diagnose)
4236 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4237 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004238 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004239 }
4240 if (!FieldRecord && FieldType.isConstQualified()) {
4241 // C++11 [class.copy]p23:
4242 // -- a non-static data member of const non-class type (or array thereof)
4243 if (Diagnose)
4244 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004245 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004246 return true;
4247 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004248 }
4249
4250 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004251 // Some additional restrictions exist on the variant members.
4252 if (!inUnion() && FieldRecord->isUnion() &&
4253 FieldRecord->isAnonymousStructOrUnion()) {
4254 bool AllVariantFieldsAreConst = true;
4255
Richard Smithdf8dc862012-03-29 19:00:10 +00004256 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004257 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4258 UE = FieldRecord->field_end();
4259 UI != UE; ++UI) {
4260 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004261
4262 if (!UnionFieldType.isConstQualified())
4263 AllVariantFieldsAreConst = false;
4264
Richard Smith9a561d52012-02-26 09:11:52 +00004265 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4266 if (UnionFieldRecord &&
David Blaikie262bc182012-04-30 02:36:29 +00004267 shouldDeleteForClassSubobject(UnionFieldRecord, &*UI))
Richard Smith9a561d52012-02-26 09:11:52 +00004268 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004269 }
4270
4271 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004272 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004273 FieldRecord->field_begin() != FieldRecord->field_end()) {
4274 if (Diagnose)
4275 S.Diag(FieldRecord->getLocation(),
4276 diag::note_deleted_default_ctor_all_const)
4277 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004278 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004279 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004280
Richard Smithdf8dc862012-03-29 19:00:10 +00004281 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004282 // This is technically non-conformant, but sanity demands it.
4283 return false;
4284 }
4285
Richard Smithdf8dc862012-03-29 19:00:10 +00004286 if (shouldDeleteForClassSubobject(FieldRecord, FD))
4287 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004288 }
4289
4290 return false;
4291}
4292
4293/// C++11 [class.ctor] p5:
4294/// A defaulted default constructor for a class X is defined as deleted if
4295/// X is a union and all of its variant members are of const-qualified type.
4296bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004297 // This is a silly definition, because it gives an empty union a deleted
4298 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004299 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4300 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4301 if (Diagnose)
4302 S.Diag(MD->getParent()->getLocation(),
4303 diag::note_deleted_default_ctor_all_const)
4304 << MD->getParent() << /*not anonymous union*/0;
4305 return true;
4306 }
4307 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004308}
4309
4310/// Determine whether a defaulted special member function should be defined as
4311/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4312/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004313bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4314 bool Diagnose) {
Sean Hunte16da072011-10-10 06:18:57 +00004315 assert(!MD->isInvalidDecl());
4316 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004317 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004318 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004319 return false;
4320
Richard Smith7d5088a2012-02-18 02:02:13 +00004321 // C++11 [expr.lambda.prim]p19:
4322 // The closure type associated with a lambda-expression has a
4323 // deleted (8.4.3) default constructor and a deleted copy
4324 // assignment operator.
4325 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004326 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4327 if (Diagnose)
4328 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004329 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004330 }
4331
Richard Smith5bdaac52012-04-02 20:59:25 +00004332 // For an anonymous struct or union, the copy and assignment special members
4333 // will never be used, so skip the check. For an anonymous union declared at
4334 // namespace scope, the constructor and destructor are used.
4335 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4336 RD->isAnonymousStructOrUnion())
4337 return false;
4338
Richard Smith6c4c36c2012-03-30 20:53:28 +00004339 // C++11 [class.copy]p7, p18:
4340 // If the class definition declares a move constructor or move assignment
4341 // operator, an implicitly declared copy constructor or copy assignment
4342 // operator is defined as deleted.
4343 if (MD->isImplicit() &&
4344 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4345 CXXMethodDecl *UserDeclaredMove = 0;
4346
4347 // In Microsoft mode, a user-declared move only causes the deletion of the
4348 // corresponding copy operation, not both copy operations.
4349 if (RD->hasUserDeclaredMoveConstructor() &&
4350 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4351 if (!Diagnose) return true;
4352 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004353 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004354 } else if (RD->hasUserDeclaredMoveAssignment() &&
4355 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4356 if (!Diagnose) return true;
4357 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004358 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004359 }
4360
4361 if (UserDeclaredMove) {
4362 Diag(UserDeclaredMove->getLocation(),
4363 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004364 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004365 << UserDeclaredMove->isMoveAssignmentOperator();
4366 return true;
4367 }
4368 }
Sean Hunte16da072011-10-10 06:18:57 +00004369
Richard Smith5bdaac52012-04-02 20:59:25 +00004370 // Do access control from the special member function
4371 ContextRAII MethodContext(*this, MD);
4372
Richard Smith9a561d52012-02-26 09:11:52 +00004373 // C++11 [class.dtor]p5:
4374 // -- for a virtual destructor, lookup of the non-array deallocation function
4375 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004376 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004377 FunctionDecl *OperatorDelete = 0;
4378 DeclarationName Name =
4379 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4380 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004381 OperatorDelete, false)) {
4382 if (Diagnose)
4383 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004384 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004385 }
Richard Smith9a561d52012-02-26 09:11:52 +00004386 }
4387
Richard Smith6c4c36c2012-03-30 20:53:28 +00004388 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004389
Sean Huntcdee3fe2011-05-11 22:34:38 +00004390 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004391 BE = RD->bases_end(); BI != BE; ++BI)
4392 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004393 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004394 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004395
4396 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004397 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004398 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004399 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004400
4401 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004402 FE = RD->field_end(); FI != FE; ++FI)
4403 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie262bc182012-04-30 02:36:29 +00004404 SMI.shouldDeleteForField(&*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004405 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004406
Richard Smith7d5088a2012-02-18 02:02:13 +00004407 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004408 return true;
4409
4410 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004411}
4412
4413/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004414namespace {
4415 struct FindHiddenVirtualMethodData {
4416 Sema *S;
4417 CXXMethodDecl *Method;
4418 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004419 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004420 };
4421}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004422
4423/// \brief Member lookup function that determines whether a given C++
4424/// method overloads virtual methods in a base class without overriding any,
4425/// to be used with CXXRecordDecl::lookupInBases().
4426static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4427 CXXBasePath &Path,
4428 void *UserData) {
4429 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4430
4431 FindHiddenVirtualMethodData &Data
4432 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4433
4434 DeclarationName Name = Data.Method->getDeclName();
4435 assert(Name.getNameKind() == DeclarationName::Identifier);
4436
4437 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004438 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004439 for (Path.Decls = BaseRecord->lookup(Name);
4440 Path.Decls.first != Path.Decls.second;
4441 ++Path.Decls.first) {
4442 NamedDecl *D = *Path.Decls.first;
4443 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004444 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004445 foundSameNameMethod = true;
4446 // Interested only in hidden virtual methods.
4447 if (!MD->isVirtual())
4448 continue;
4449 // If the method we are checking overrides a method from its base
4450 // don't warn about the other overloaded methods.
4451 if (!Data.S->IsOverload(Data.Method, MD, false))
4452 return true;
4453 // Collect the overload only if its hidden.
4454 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4455 overloadedMethods.push_back(MD);
4456 }
4457 }
4458
4459 if (foundSameNameMethod)
4460 Data.OverloadedMethods.append(overloadedMethods.begin(),
4461 overloadedMethods.end());
4462 return foundSameNameMethod;
4463}
4464
4465/// \brief See if a method overloads virtual methods in a base class without
4466/// overriding any.
4467void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4468 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004469 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004470 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004471 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004472 return;
4473
4474 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4475 /*bool RecordPaths=*/false,
4476 /*bool DetectVirtual=*/false);
4477 FindHiddenVirtualMethodData Data;
4478 Data.Method = MD;
4479 Data.S = this;
4480
4481 // Keep the base methods that were overriden or introduced in the subclass
4482 // by 'using' in a set. A base method not in this set is hidden.
4483 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4484 res.first != res.second; ++res.first) {
4485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4486 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4487 E = MD->end_overridden_methods();
4488 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004489 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004490 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4491 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004492 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004493 }
4494
4495 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4496 !Data.OverloadedMethods.empty()) {
4497 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4498 << MD << (Data.OverloadedMethods.size() > 1);
4499
4500 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4501 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4502 Diag(overloadedMD->getLocation(),
4503 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4504 }
4505 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004506}
4507
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004508void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004509 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004510 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004511 SourceLocation RBrac,
4512 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004513 if (!TagDecl)
4514 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Douglas Gregor42af25f2009-05-11 19:58:34 +00004516 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004517
David Blaikie77b6de02011-09-22 02:58:26 +00004518 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004519 // strict aliasing violation!
4520 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004521 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004522
Douglas Gregor23c94db2010-07-02 17:43:08 +00004523 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004524 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004525}
4526
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004527/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4528/// special functions, such as the default constructor, copy
4529/// constructor, or destructor, to the given C++ class (C++
4530/// [special]p1). This routine can only be executed just before the
4531/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004532void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004533 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004534 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004535
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004536 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004537 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004538
David Blaikie4e4d0842012-03-11 07:00:24 +00004539 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004540 ++ASTContext::NumImplicitMoveConstructors;
4541
Douglas Gregora376d102010-07-02 21:50:04 +00004542 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4543 ++ASTContext::NumImplicitCopyAssignmentOperators;
4544
4545 // If we have a dynamic class, then the copy assignment operator may be
4546 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4547 // it shows up in the right place in the vtable and that we diagnose
4548 // problems with the implicit exception specification.
4549 if (ClassDecl->isDynamicClass())
4550 DeclareImplicitCopyAssignment(ClassDecl);
4551 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004552
Richard Smith1c931be2012-04-02 18:40:40 +00004553 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004554 ++ASTContext::NumImplicitMoveAssignmentOperators;
4555
4556 // Likewise for the move assignment operator.
4557 if (ClassDecl->isDynamicClass())
4558 DeclareImplicitMoveAssignment(ClassDecl);
4559 }
4560
Douglas Gregor4923aa22010-07-02 20:37:36 +00004561 if (!ClassDecl->hasUserDeclaredDestructor()) {
4562 ++ASTContext::NumImplicitDestructors;
4563
4564 // If we have a dynamic class, then the destructor may be virtual, so we
4565 // have to declare the destructor immediately. This ensures that, e.g., it
4566 // shows up in the right place in the vtable and that we diagnose problems
4567 // with the implicit exception specification.
4568 if (ClassDecl->isDynamicClass())
4569 DeclareImplicitDestructor(ClassDecl);
4570 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004571}
4572
Francois Pichet8387e2a2011-04-22 22:18:13 +00004573void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4574 if (!D)
4575 return;
4576
4577 int NumParamList = D->getNumTemplateParameterLists();
4578 for (int i = 0; i < NumParamList; i++) {
4579 TemplateParameterList* Params = D->getTemplateParameterList(i);
4580 for (TemplateParameterList::iterator Param = Params->begin(),
4581 ParamEnd = Params->end();
4582 Param != ParamEnd; ++Param) {
4583 NamedDecl *Named = cast<NamedDecl>(*Param);
4584 if (Named->getDeclName()) {
4585 S->AddDecl(Named);
4586 IdResolver.AddDecl(Named);
4587 }
4588 }
4589 }
4590}
4591
John McCalld226f652010-08-21 09:40:31 +00004592void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004593 if (!D)
4594 return;
4595
4596 TemplateParameterList *Params = 0;
4597 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4598 Params = Template->getTemplateParameters();
4599 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4600 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4601 Params = PartialSpec->getTemplateParameters();
4602 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004603 return;
4604
Douglas Gregor6569d682009-05-27 23:11:45 +00004605 for (TemplateParameterList::iterator Param = Params->begin(),
4606 ParamEnd = Params->end();
4607 Param != ParamEnd; ++Param) {
4608 NamedDecl *Named = cast<NamedDecl>(*Param);
4609 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004610 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004611 IdResolver.AddDecl(Named);
4612 }
4613 }
4614}
4615
John McCalld226f652010-08-21 09:40:31 +00004616void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004617 if (!RecordD) return;
4618 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004619 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004620 PushDeclContext(S, Record);
4621}
4622
John McCalld226f652010-08-21 09:40:31 +00004623void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004624 if (!RecordD) return;
4625 PopDeclContext();
4626}
4627
Douglas Gregor72b505b2008-12-16 21:30:33 +00004628/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4629/// parsing a top-level (non-nested) C++ class, and we are now
4630/// parsing those parts of the given Method declaration that could
4631/// not be parsed earlier (C++ [class.mem]p2), such as default
4632/// arguments. This action should enter the scope of the given
4633/// Method declaration as if we had just parsed the qualified method
4634/// name. However, it should not bring the parameters into scope;
4635/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004636void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004637}
4638
4639/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4640/// C++ method declaration. We're (re-)introducing the given
4641/// function parameter into scope for use in parsing later parts of
4642/// the method declaration. For example, we could see an
4643/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004644void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004645 if (!ParamD)
4646 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004647
John McCalld226f652010-08-21 09:40:31 +00004648 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004649
4650 // If this parameter has an unparsed default argument, clear it out
4651 // to make way for the parsed default argument.
4652 if (Param->hasUnparsedDefaultArg())
4653 Param->setDefaultArg(0);
4654
John McCalld226f652010-08-21 09:40:31 +00004655 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004656 if (Param->getDeclName())
4657 IdResolver.AddDecl(Param);
4658}
4659
4660/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4661/// processing the delayed method declaration for Method. The method
4662/// declaration is now considered finished. There may be a separate
4663/// ActOnStartOfFunctionDef action later (not necessarily
4664/// immediately!) for this method, if it was also defined inside the
4665/// class body.
John McCalld226f652010-08-21 09:40:31 +00004666void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004667 if (!MethodD)
4668 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004670 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004671
John McCalld226f652010-08-21 09:40:31 +00004672 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004673
4674 // Now that we have our default arguments, check the constructor
4675 // again. It could produce additional diagnostics or affect whether
4676 // the class has implicitly-declared destructors, among other
4677 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004678 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4679 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004680
4681 // Check the default arguments, which we may have added.
4682 if (!Method->isInvalidDecl())
4683 CheckCXXDefaultArguments(Method);
4684}
4685
Douglas Gregor42a552f2008-11-05 20:51:48 +00004686/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004687/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004688/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004689/// emit diagnostics and set the invalid bit to true. In any case, the type
4690/// will be updated to reflect a well-formed type for the constructor and
4691/// returned.
4692QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004693 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004694 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004695
4696 // C++ [class.ctor]p3:
4697 // A constructor shall not be virtual (10.3) or static (9.4). A
4698 // constructor can be invoked for a const, volatile or const
4699 // volatile object. A constructor shall not be declared const,
4700 // volatile, or const volatile (9.3.2).
4701 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004702 if (!D.isInvalidType())
4703 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4704 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4705 << SourceRange(D.getIdentifierLoc());
4706 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004707 }
John McCalld931b082010-08-26 03:08:43 +00004708 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004709 if (!D.isInvalidType())
4710 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4711 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4712 << SourceRange(D.getIdentifierLoc());
4713 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004714 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004715 }
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004717 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004718 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004719 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004720 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4721 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004722 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004723 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4724 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004725 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004726 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4727 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004728 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004729 }
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Douglas Gregorc938c162011-01-26 05:01:58 +00004731 // C++0x [class.ctor]p4:
4732 // A constructor shall not be declared with a ref-qualifier.
4733 if (FTI.hasRefQualifier()) {
4734 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4735 << FTI.RefQualifierIsLValueRef
4736 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4737 D.setInvalidType();
4738 }
4739
Douglas Gregor42a552f2008-11-05 20:51:48 +00004740 // Rebuild the function type "R" without any type qualifiers (in
4741 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004742 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004743 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004744 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4745 return R;
4746
4747 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4748 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004749 EPI.RefQualifier = RQ_None;
4750
Chris Lattner65401802009-04-25 08:28:21 +00004751 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004752 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004753}
4754
Douglas Gregor72b505b2008-12-16 21:30:33 +00004755/// CheckConstructor - Checks a fully-formed constructor for
4756/// well-formedness, issuing any diagnostics required. Returns true if
4757/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004758void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004759 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004760 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4761 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004762 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004763
4764 // C++ [class.copy]p3:
4765 // A declaration of a constructor for a class X is ill-formed if
4766 // its first parameter is of type (optionally cv-qualified) X and
4767 // either there are no other parameters or else all other
4768 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004769 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004770 ((Constructor->getNumParams() == 1) ||
4771 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004772 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4773 Constructor->getTemplateSpecializationKind()
4774 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004775 QualType ParamType = Constructor->getParamDecl(0)->getType();
4776 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4777 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004778 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004779 const char *ConstRef
4780 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4781 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004782 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004783 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004784
4785 // FIXME: Rather that making the constructor invalid, we should endeavor
4786 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004787 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004788 }
4789 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004790}
4791
John McCall15442822010-08-04 01:04:25 +00004792/// CheckDestructor - Checks a fully-formed destructor definition for
4793/// well-formedness, issuing any diagnostics required. Returns true
4794/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004795bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004796 CXXRecordDecl *RD = Destructor->getParent();
4797
4798 if (Destructor->isVirtual()) {
4799 SourceLocation Loc;
4800
4801 if (!Destructor->isImplicit())
4802 Loc = Destructor->getLocation();
4803 else
4804 Loc = RD->getLocation();
4805
4806 // If we have a virtual destructor, look up the deallocation function
4807 FunctionDecl *OperatorDelete = 0;
4808 DeclarationName Name =
4809 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004810 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004811 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004812
Eli Friedman5f2987c2012-02-02 03:46:19 +00004813 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004814
4815 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004816 }
Anders Carlsson37909802009-11-30 21:24:50 +00004817
4818 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004819}
4820
Mike Stump1eb44332009-09-09 15:08:12 +00004821static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004822FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4823 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4824 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004825 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004826}
4827
Douglas Gregor42a552f2008-11-05 20:51:48 +00004828/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4829/// the well-formednes of the destructor declarator @p D with type @p
4830/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004831/// emit diagnostics and set the declarator to invalid. Even if this happens,
4832/// will be updated to reflect a well-formed type for the destructor and
4833/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004834QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004835 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004836 // C++ [class.dtor]p1:
4837 // [...] A typedef-name that names a class is a class-name
4838 // (7.1.3); however, a typedef-name that names a class shall not
4839 // be used as the identifier in the declarator for a destructor
4840 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004841 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004842 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004843 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004844 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004845 else if (const TemplateSpecializationType *TST =
4846 DeclaratorType->getAs<TemplateSpecializationType>())
4847 if (TST->isTypeAlias())
4848 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4849 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004850
4851 // C++ [class.dtor]p2:
4852 // A destructor is used to destroy objects of its class type. A
4853 // destructor takes no parameters, and no return type can be
4854 // specified for it (not even void). The address of a destructor
4855 // shall not be taken. A destructor shall not be static. A
4856 // destructor can be invoked for a const, volatile or const
4857 // volatile object. A destructor shall not be declared const,
4858 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004859 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004860 if (!D.isInvalidType())
4861 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4862 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004863 << SourceRange(D.getIdentifierLoc())
4864 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4865
John McCalld931b082010-08-26 03:08:43 +00004866 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004867 }
Chris Lattner65401802009-04-25 08:28:21 +00004868 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004869 // Destructors don't have return types, but the parser will
4870 // happily parse something like:
4871 //
4872 // class X {
4873 // float ~X();
4874 // };
4875 //
4876 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004877 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4878 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4879 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004880 }
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004882 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004883 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004884 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004885 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4886 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004887 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004888 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4889 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004890 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004891 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4892 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004893 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004894 }
4895
Douglas Gregorc938c162011-01-26 05:01:58 +00004896 // C++0x [class.dtor]p2:
4897 // A destructor shall not be declared with a ref-qualifier.
4898 if (FTI.hasRefQualifier()) {
4899 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4900 << FTI.RefQualifierIsLValueRef
4901 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4902 D.setInvalidType();
4903 }
4904
Douglas Gregor42a552f2008-11-05 20:51:48 +00004905 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004906 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004907 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4908
4909 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004910 FTI.freeArgs();
4911 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004912 }
4913
Mike Stump1eb44332009-09-09 15:08:12 +00004914 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004915 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004916 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004917 D.setInvalidType();
4918 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004919
4920 // Rebuild the function type "R" without any type qualifiers or
4921 // parameters (in case any of the errors above fired) and with
4922 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004923 // types.
John McCalle23cf432010-12-14 08:05:40 +00004924 if (!D.isInvalidType())
4925 return R;
4926
Douglas Gregord92ec472010-07-01 05:10:53 +00004927 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004928 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4929 EPI.Variadic = false;
4930 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004931 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004932 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004933}
4934
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004935/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4936/// well-formednes of the conversion function declarator @p D with
4937/// type @p R. If there are any errors in the declarator, this routine
4938/// will emit diagnostics and return true. Otherwise, it will return
4939/// false. Either way, the type @p R will be updated to reflect a
4940/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004941void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004942 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004943 // C++ [class.conv.fct]p1:
4944 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004945 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004946 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004947 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004948 if (!D.isInvalidType())
4949 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4950 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4951 << SourceRange(D.getIdentifierLoc());
4952 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004953 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004954 }
John McCalla3f81372010-04-13 00:04:31 +00004955
4956 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4957
Chris Lattner6e475012009-04-25 08:35:12 +00004958 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004959 // Conversion functions don't have return types, but the parser will
4960 // happily parse something like:
4961 //
4962 // class X {
4963 // float operator bool();
4964 // };
4965 //
4966 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004967 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4968 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4969 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004970 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004971 }
4972
John McCalla3f81372010-04-13 00:04:31 +00004973 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4974
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004975 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004976 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004977 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4978
4979 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004980 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004981 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004982 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004983 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004984 D.setInvalidType();
4985 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004986
John McCalla3f81372010-04-13 00:04:31 +00004987 // Diagnose "&operator bool()" and other such nonsense. This
4988 // is actually a gcc extension which we don't support.
4989 if (Proto->getResultType() != ConvType) {
4990 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4991 << Proto->getResultType();
4992 D.setInvalidType();
4993 ConvType = Proto->getResultType();
4994 }
4995
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004996 // C++ [class.conv.fct]p4:
4997 // The conversion-type-id shall not represent a function type nor
4998 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004999 if (ConvType->isArrayType()) {
5000 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5001 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005002 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005003 } else if (ConvType->isFunctionType()) {
5004 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5005 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005006 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005007 }
5008
5009 // Rebuild the function type "R" without any parameters (in case any
5010 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005011 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005012 if (D.isInvalidType())
5013 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005014
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005015 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005016 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005017 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005018 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005019 diag::warn_cxx98_compat_explicit_conversion_functions :
5020 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005021 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005022}
5023
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005024/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5025/// the declaration of the given C++ conversion function. This routine
5026/// is responsible for recording the conversion function in the C++
5027/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005028Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005029 assert(Conversion && "Expected to receive a conversion function declaration");
5030
Douglas Gregor9d350972008-12-12 08:25:50 +00005031 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005032
5033 // Make sure we aren't redeclaring the conversion function.
5034 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005035
5036 // C++ [class.conv.fct]p1:
5037 // [...] A conversion function is never used to convert a
5038 // (possibly cv-qualified) object to the (possibly cv-qualified)
5039 // same object type (or a reference to it), to a (possibly
5040 // cv-qualified) base class of that type (or a reference to it),
5041 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005042 // FIXME: Suppress this warning if the conversion function ends up being a
5043 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005044 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005045 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005046 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005047 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005048 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5049 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005050 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005051 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005052 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5053 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005054 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005055 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005056 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005057 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005058 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005059 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005060 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005061 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005062 }
5063
Douglas Gregore80622f2010-09-29 04:25:11 +00005064 if (FunctionTemplateDecl *ConversionTemplate
5065 = Conversion->getDescribedFunctionTemplate())
5066 return ConversionTemplate;
5067
John McCalld226f652010-08-21 09:40:31 +00005068 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005069}
5070
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005071//===----------------------------------------------------------------------===//
5072// Namespace Handling
5073//===----------------------------------------------------------------------===//
5074
John McCallea318642010-08-26 09:15:37 +00005075
5076
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005077/// ActOnStartNamespaceDef - This is called at the start of a namespace
5078/// definition.
John McCalld226f652010-08-21 09:40:31 +00005079Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005080 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005081 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005082 SourceLocation IdentLoc,
5083 IdentifierInfo *II,
5084 SourceLocation LBrace,
5085 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005086 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5087 // For anonymous namespace, take the location of the left brace.
5088 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005089 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005090 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005091 bool IsStd = false;
5092 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005093 Scope *DeclRegionScope = NamespcScope->getParent();
5094
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005095 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005096 if (II) {
5097 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005098 // The identifier in an original-namespace-definition shall not
5099 // have been previously defined in the declarative region in
5100 // which the original-namespace-definition appears. The
5101 // identifier in an original-namespace-definition is the name of
5102 // the namespace. Subsequently in that declarative region, it is
5103 // treated as an original-namespace-name.
5104 //
5105 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005106 // look through using directives, just look for any ordinary names.
5107
5108 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005109 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5110 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005111 NamedDecl *PrevDecl = 0;
5112 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005113 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005114 R.first != R.second; ++R.first) {
5115 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5116 PrevDecl = *R.first;
5117 break;
5118 }
5119 }
5120
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005121 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5122
5123 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005124 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005125 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005126 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005127 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005128 // The user probably just forgot the 'inline', so suggest that it
5129 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005130 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005131 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5132 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005133 Diag(Loc, diag::err_inline_namespace_mismatch)
5134 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005135 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005136 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5137
5138 IsInline = PrevNS->isInline();
5139 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005140 } else if (PrevDecl) {
5141 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005142 Diag(Loc, diag::err_redefinition_different_kind)
5143 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005144 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005145 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005146 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005147 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005148 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005149 // This is the first "real" definition of the namespace "std", so update
5150 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005151 PrevNS = getStdNamespace();
5152 IsStd = true;
5153 AddToKnown = !IsInline;
5154 } else {
5155 // We've seen this namespace for the first time.
5156 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005157 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005158 } else {
John McCall9aeed322009-10-01 00:25:31 +00005159 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005160
5161 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005162 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005163 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005164 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005165 } else {
5166 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005167 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005168 }
5169
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005170 if (PrevNS && IsInline != PrevNS->isInline()) {
5171 // inline-ness must match
5172 Diag(Loc, diag::err_inline_namespace_mismatch)
5173 << IsInline;
5174 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005175
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005176 // Recover by ignoring the new namespace's inline status.
5177 IsInline = PrevNS->isInline();
5178 }
5179 }
5180
5181 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5182 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005183 if (IsInvalid)
5184 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005185
5186 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005187
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005188 // FIXME: Should we be merging attributes?
5189 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005190 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005191
5192 if (IsStd)
5193 StdNamespace = Namespc;
5194 if (AddToKnown)
5195 KnownNamespaces[Namespc] = false;
5196
5197 if (II) {
5198 PushOnScopeChains(Namespc, DeclRegionScope);
5199 } else {
5200 // Link the anonymous namespace into its parent.
5201 DeclContext *Parent = CurContext->getRedeclContext();
5202 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5203 TU->setAnonymousNamespace(Namespc);
5204 } else {
5205 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005206 }
John McCall9aeed322009-10-01 00:25:31 +00005207
Douglas Gregora4181472010-03-24 00:46:35 +00005208 CurContext->addDecl(Namespc);
5209
John McCall9aeed322009-10-01 00:25:31 +00005210 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5211 // behaves as if it were replaced by
5212 // namespace unique { /* empty body */ }
5213 // using namespace unique;
5214 // namespace unique { namespace-body }
5215 // where all occurrences of 'unique' in a translation unit are
5216 // replaced by the same identifier and this identifier differs
5217 // from all other identifiers in the entire program.
5218
5219 // We just create the namespace with an empty name and then add an
5220 // implicit using declaration, just like the standard suggests.
5221 //
5222 // CodeGen enforces the "universally unique" aspect by giving all
5223 // declarations semantically contained within an anonymous
5224 // namespace internal linkage.
5225
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005226 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005227 UsingDirectiveDecl* UD
5228 = UsingDirectiveDecl::Create(Context, CurContext,
5229 /* 'using' */ LBrace,
5230 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005231 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005232 /* identifier */ SourceLocation(),
5233 Namespc,
5234 /* Ancestor */ CurContext);
5235 UD->setImplicit();
5236 CurContext->addDecl(UD);
5237 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005238 }
5239
5240 // Although we could have an invalid decl (i.e. the namespace name is a
5241 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005242 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5243 // for the namespace has the declarations that showed up in that particular
5244 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005245 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005246 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005247}
5248
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005249/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5250/// is a namespace alias, returns the namespace it points to.
5251static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5252 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5253 return AD->getNamespace();
5254 return dyn_cast_or_null<NamespaceDecl>(D);
5255}
5256
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005257/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5258/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005259void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005260 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5261 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005262 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005263 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005264 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005265 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005266}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005267
John McCall384aff82010-08-25 07:42:41 +00005268CXXRecordDecl *Sema::getStdBadAlloc() const {
5269 return cast_or_null<CXXRecordDecl>(
5270 StdBadAlloc.get(Context.getExternalSource()));
5271}
5272
5273NamespaceDecl *Sema::getStdNamespace() const {
5274 return cast_or_null<NamespaceDecl>(
5275 StdNamespace.get(Context.getExternalSource()));
5276}
5277
Douglas Gregor66992202010-06-29 17:53:46 +00005278/// \brief Retrieve the special "std" namespace, which may require us to
5279/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005280NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005281 if (!StdNamespace) {
5282 // The "std" namespace has not yet been defined, so build one implicitly.
5283 StdNamespace = NamespaceDecl::Create(Context,
5284 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005285 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005286 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005287 &PP.getIdentifierTable().get("std"),
5288 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005289 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005290 }
5291
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005292 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005293}
5294
Sebastian Redl395e04d2012-01-17 22:49:33 +00005295bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005296 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005297 "Looking for std::initializer_list outside of C++.");
5298
5299 // We're looking for implicit instantiations of
5300 // template <typename E> class std::initializer_list.
5301
5302 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5303 return false;
5304
Sebastian Redl84760e32012-01-17 22:49:58 +00005305 ClassTemplateDecl *Template = 0;
5306 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005307
Sebastian Redl84760e32012-01-17 22:49:58 +00005308 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005309
Sebastian Redl84760e32012-01-17 22:49:58 +00005310 ClassTemplateSpecializationDecl *Specialization =
5311 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5312 if (!Specialization)
5313 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005314
Sebastian Redl84760e32012-01-17 22:49:58 +00005315 Template = Specialization->getSpecializedTemplate();
5316 Arguments = Specialization->getTemplateArgs().data();
5317 } else if (const TemplateSpecializationType *TST =
5318 Ty->getAs<TemplateSpecializationType>()) {
5319 Template = dyn_cast_or_null<ClassTemplateDecl>(
5320 TST->getTemplateName().getAsTemplateDecl());
5321 Arguments = TST->getArgs();
5322 }
5323 if (!Template)
5324 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005325
5326 if (!StdInitializerList) {
5327 // Haven't recognized std::initializer_list yet, maybe this is it.
5328 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5329 if (TemplateClass->getIdentifier() !=
5330 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005331 !getStdNamespace()->InEnclosingNamespaceSetOf(
5332 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005333 return false;
5334 // This is a template called std::initializer_list, but is it the right
5335 // template?
5336 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005337 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005338 return false;
5339 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5340 return false;
5341
5342 // It's the right template.
5343 StdInitializerList = Template;
5344 }
5345
5346 if (Template != StdInitializerList)
5347 return false;
5348
5349 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005350 if (Element)
5351 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005352 return true;
5353}
5354
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005355static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5356 NamespaceDecl *Std = S.getStdNamespace();
5357 if (!Std) {
5358 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5359 return 0;
5360 }
5361
5362 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5363 Loc, Sema::LookupOrdinaryName);
5364 if (!S.LookupQualifiedName(Result, Std)) {
5365 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5366 return 0;
5367 }
5368 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5369 if (!Template) {
5370 Result.suppressDiagnostics();
5371 // We found something weird. Complain about the first thing we found.
5372 NamedDecl *Found = *Result.begin();
5373 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5374 return 0;
5375 }
5376
5377 // We found some template called std::initializer_list. Now verify that it's
5378 // correct.
5379 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005380 if (Params->getMinRequiredArguments() != 1 ||
5381 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005382 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5383 return 0;
5384 }
5385
5386 return Template;
5387}
5388
5389QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5390 if (!StdInitializerList) {
5391 StdInitializerList = LookupStdInitializerList(*this, Loc);
5392 if (!StdInitializerList)
5393 return QualType();
5394 }
5395
5396 TemplateArgumentListInfo Args(Loc, Loc);
5397 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5398 Context.getTrivialTypeSourceInfo(Element,
5399 Loc)));
5400 return Context.getCanonicalType(
5401 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5402}
5403
Sebastian Redl98d36062012-01-17 22:50:14 +00005404bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5405 // C++ [dcl.init.list]p2:
5406 // A constructor is an initializer-list constructor if its first parameter
5407 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5408 // std::initializer_list<E> for some type E, and either there are no other
5409 // parameters or else all other parameters have default arguments.
5410 if (Ctor->getNumParams() < 1 ||
5411 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5412 return false;
5413
5414 QualType ArgType = Ctor->getParamDecl(0)->getType();
5415 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5416 ArgType = RT->getPointeeType().getUnqualifiedType();
5417
5418 return isStdInitializerList(ArgType, 0);
5419}
5420
Douglas Gregor9172aa62011-03-26 22:25:30 +00005421/// \brief Determine whether a using statement is in a context where it will be
5422/// apply in all contexts.
5423static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5424 switch (CurContext->getDeclKind()) {
5425 case Decl::TranslationUnit:
5426 return true;
5427 case Decl::LinkageSpec:
5428 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5429 default:
5430 return false;
5431 }
5432}
5433
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005434namespace {
5435
5436// Callback to only accept typo corrections that are namespaces.
5437class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5438 public:
5439 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5440 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5441 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5442 }
5443 return false;
5444 }
5445};
5446
5447}
5448
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005449static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5450 CXXScopeSpec &SS,
5451 SourceLocation IdentLoc,
5452 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005453 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005454 R.clear();
5455 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005456 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005457 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005458 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5459 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005460 if (DeclContext *DC = S.computeDeclContext(SS, false))
5461 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5462 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5463 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5464 else
5465 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5466 << Ident << CorrectedQuotedStr
5467 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005468
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005469 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5470 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005471
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005472 R.addDecl(Corrected.getCorrectionDecl());
5473 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005474 }
5475 return false;
5476}
5477
John McCalld226f652010-08-21 09:40:31 +00005478Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005479 SourceLocation UsingLoc,
5480 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005481 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005482 SourceLocation IdentLoc,
5483 IdentifierInfo *NamespcName,
5484 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005485 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5486 assert(NamespcName && "Invalid NamespcName.");
5487 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005488
5489 // This can only happen along a recovery path.
5490 while (S->getFlags() & Scope::TemplateParamScope)
5491 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005492 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005493
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005494 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005495 NestedNameSpecifier *Qualifier = 0;
5496 if (SS.isSet())
5497 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5498
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005499 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005500 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5501 LookupParsedName(R, S, &SS);
5502 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005503 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005504
Douglas Gregor66992202010-06-29 17:53:46 +00005505 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005506 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005507 // Allow "using namespace std;" or "using namespace ::std;" even if
5508 // "std" hasn't been defined yet, for GCC compatibility.
5509 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5510 NamespcName->isStr("std")) {
5511 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005512 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005513 R.resolveKind();
5514 }
5515 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005516 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005517 }
5518
John McCallf36e02d2009-10-09 21:13:30 +00005519 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005520 NamedDecl *Named = R.getFoundDecl();
5521 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5522 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005523 // C++ [namespace.udir]p1:
5524 // A using-directive specifies that the names in the nominated
5525 // namespace can be used in the scope in which the
5526 // using-directive appears after the using-directive. During
5527 // unqualified name lookup (3.4.1), the names appear as if they
5528 // were declared in the nearest enclosing namespace which
5529 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005530 // namespace. [Note: in this context, "contains" means "contains
5531 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005532
5533 // Find enclosing context containing both using-directive and
5534 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005535 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005536 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5537 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5538 CommonAncestor = CommonAncestor->getParent();
5539
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005540 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005541 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005542 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005543
Douglas Gregor9172aa62011-03-26 22:25:30 +00005544 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005545 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005546 Diag(IdentLoc, diag::warn_using_directive_in_header);
5547 }
5548
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005549 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005550 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005551 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005552 }
5553
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005554 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005555 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005556}
5557
5558void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005559 // If the scope has an associated entity and the using directive is at
5560 // namespace or translation unit scope, add the UsingDirectiveDecl into
5561 // its lookup structure so qualified name lookup can find it.
5562 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5563 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005564 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005565 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005566 // Otherwise, it is at block sope. The using-directives will affect lookup
5567 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005568 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005569}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005570
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005571
John McCalld226f652010-08-21 09:40:31 +00005572Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005573 AccessSpecifier AS,
5574 bool HasUsingKeyword,
5575 SourceLocation UsingLoc,
5576 CXXScopeSpec &SS,
5577 UnqualifiedId &Name,
5578 AttributeList *AttrList,
5579 bool IsTypeName,
5580 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005581 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Douglas Gregor12c118a2009-11-04 16:30:06 +00005583 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005584 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005585 case UnqualifiedId::IK_Identifier:
5586 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005587 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005588 case UnqualifiedId::IK_ConversionFunctionId:
5589 break;
5590
5591 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005592 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005593 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005594 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005595 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005596 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5597 // instead once inheriting constructors work.
5598 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005599 diag::err_using_decl_constructor)
5600 << SS.getRange();
5601
David Blaikie4e4d0842012-03-11 07:00:24 +00005602 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005603
John McCalld226f652010-08-21 09:40:31 +00005604 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005605
5606 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005607 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005608 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005609 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005610
5611 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005612 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005613 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005614 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005615 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005616
5617 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5618 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005619 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005620 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005621
John McCall60fa3cf2009-12-11 02:10:03 +00005622 // Warn about using declarations.
5623 // TODO: store that the declaration was written without 'using' and
5624 // talk about access decls instead of using decls in the
5625 // diagnostics.
5626 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005627 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005628
5629 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005630 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005631 }
5632
Douglas Gregor56c04582010-12-16 00:46:58 +00005633 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5634 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5635 return 0;
5636
John McCall9488ea12009-11-17 05:59:44 +00005637 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005638 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005639 /* IsInstantiation */ false,
5640 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005641 if (UD)
5642 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005643
John McCalld226f652010-08-21 09:40:31 +00005644 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005645}
5646
Douglas Gregor09acc982010-07-07 23:08:52 +00005647/// \brief Determine whether a using declaration considers the given
5648/// declarations as "equivalent", e.g., if they are redeclarations of
5649/// the same entity or are both typedefs of the same type.
5650static bool
5651IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5652 bool &SuppressRedeclaration) {
5653 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5654 SuppressRedeclaration = false;
5655 return true;
5656 }
5657
Richard Smith162e1c12011-04-15 14:24:37 +00005658 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5659 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005660 SuppressRedeclaration = true;
5661 return Context.hasSameType(TD1->getUnderlyingType(),
5662 TD2->getUnderlyingType());
5663 }
5664
5665 return false;
5666}
5667
5668
John McCall9f54ad42009-12-10 09:41:52 +00005669/// Determines whether to create a using shadow decl for a particular
5670/// decl, given the set of decls existing prior to this using lookup.
5671bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5672 const LookupResult &Previous) {
5673 // Diagnose finding a decl which is not from a base class of the
5674 // current class. We do this now because there are cases where this
5675 // function will silently decide not to build a shadow decl, which
5676 // will pre-empt further diagnostics.
5677 //
5678 // We don't need to do this in C++0x because we do the check once on
5679 // the qualifier.
5680 //
5681 // FIXME: diagnose the following if we care enough:
5682 // struct A { int foo; };
5683 // struct B : A { using A::foo; };
5684 // template <class T> struct C : A {};
5685 // template <class T> struct D : C<T> { using B::foo; } // <---
5686 // This is invalid (during instantiation) in C++03 because B::foo
5687 // resolves to the using decl in B, which is not a base class of D<T>.
5688 // We can't diagnose it immediately because C<T> is an unknown
5689 // specialization. The UsingShadowDecl in D<T> then points directly
5690 // to A::foo, which will look well-formed when we instantiate.
5691 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005692 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005693 DeclContext *OrigDC = Orig->getDeclContext();
5694
5695 // Handle enums and anonymous structs.
5696 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5697 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5698 while (OrigRec->isAnonymousStructOrUnion())
5699 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5700
5701 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5702 if (OrigDC == CurContext) {
5703 Diag(Using->getLocation(),
5704 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005705 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005706 Diag(Orig->getLocation(), diag::note_using_decl_target);
5707 return true;
5708 }
5709
Douglas Gregordc355712011-02-25 00:36:19 +00005710 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005711 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005712 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005713 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005714 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005715 Diag(Orig->getLocation(), diag::note_using_decl_target);
5716 return true;
5717 }
5718 }
5719
5720 if (Previous.empty()) return false;
5721
5722 NamedDecl *Target = Orig;
5723 if (isa<UsingShadowDecl>(Target))
5724 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5725
John McCalld7533ec2009-12-11 02:33:26 +00005726 // If the target happens to be one of the previous declarations, we
5727 // don't have a conflict.
5728 //
5729 // FIXME: but we might be increasing its access, in which case we
5730 // should redeclare it.
5731 NamedDecl *NonTag = 0, *Tag = 0;
5732 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5733 I != E; ++I) {
5734 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005735 bool Result;
5736 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5737 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005738
5739 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5740 }
5741
John McCall9f54ad42009-12-10 09:41:52 +00005742 if (Target->isFunctionOrFunctionTemplate()) {
5743 FunctionDecl *FD;
5744 if (isa<FunctionTemplateDecl>(Target))
5745 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5746 else
5747 FD = cast<FunctionDecl>(Target);
5748
5749 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005750 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005751 case Ovl_Overload:
5752 return false;
5753
5754 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005755 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005756 break;
5757
5758 // We found a decl with the exact signature.
5759 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005760 // If we're in a record, we want to hide the target, so we
5761 // return true (without a diagnostic) to tell the caller not to
5762 // build a shadow decl.
5763 if (CurContext->isRecord())
5764 return true;
5765
5766 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005767 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005768 break;
5769 }
5770
5771 Diag(Target->getLocation(), diag::note_using_decl_target);
5772 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5773 return true;
5774 }
5775
5776 // Target is not a function.
5777
John McCall9f54ad42009-12-10 09:41:52 +00005778 if (isa<TagDecl>(Target)) {
5779 // No conflict between a tag and a non-tag.
5780 if (!Tag) return false;
5781
John McCall41ce66f2009-12-10 19:51:03 +00005782 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005783 Diag(Target->getLocation(), diag::note_using_decl_target);
5784 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5785 return true;
5786 }
5787
5788 // No conflict between a tag and a non-tag.
5789 if (!NonTag) return false;
5790
John McCall41ce66f2009-12-10 19:51:03 +00005791 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005792 Diag(Target->getLocation(), diag::note_using_decl_target);
5793 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5794 return true;
5795}
5796
John McCall9488ea12009-11-17 05:59:44 +00005797/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005798UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005799 UsingDecl *UD,
5800 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005801
5802 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005803 NamedDecl *Target = Orig;
5804 if (isa<UsingShadowDecl>(Target)) {
5805 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5806 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005807 }
5808
5809 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005810 = UsingShadowDecl::Create(Context, CurContext,
5811 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005812 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005813
5814 Shadow->setAccess(UD->getAccess());
5815 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5816 Shadow->setInvalidDecl();
5817
John McCall9488ea12009-11-17 05:59:44 +00005818 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005819 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005820 else
John McCall604e7f12009-12-08 07:46:18 +00005821 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005822
John McCall604e7f12009-12-08 07:46:18 +00005823
John McCall9f54ad42009-12-10 09:41:52 +00005824 return Shadow;
5825}
John McCall604e7f12009-12-08 07:46:18 +00005826
John McCall9f54ad42009-12-10 09:41:52 +00005827/// Hides a using shadow declaration. This is required by the current
5828/// using-decl implementation when a resolvable using declaration in a
5829/// class is followed by a declaration which would hide or override
5830/// one or more of the using decl's targets; for example:
5831///
5832/// struct Base { void foo(int); };
5833/// struct Derived : Base {
5834/// using Base::foo;
5835/// void foo(int);
5836/// };
5837///
5838/// The governing language is C++03 [namespace.udecl]p12:
5839///
5840/// When a using-declaration brings names from a base class into a
5841/// derived class scope, member functions in the derived class
5842/// override and/or hide member functions with the same name and
5843/// parameter types in a base class (rather than conflicting).
5844///
5845/// There are two ways to implement this:
5846/// (1) optimistically create shadow decls when they're not hidden
5847/// by existing declarations, or
5848/// (2) don't create any shadow decls (or at least don't make them
5849/// visible) until we've fully parsed/instantiated the class.
5850/// The problem with (1) is that we might have to retroactively remove
5851/// a shadow decl, which requires several O(n) operations because the
5852/// decl structures are (very reasonably) not designed for removal.
5853/// (2) avoids this but is very fiddly and phase-dependent.
5854void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005855 if (Shadow->getDeclName().getNameKind() ==
5856 DeclarationName::CXXConversionFunctionName)
5857 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5858
John McCall9f54ad42009-12-10 09:41:52 +00005859 // Remove it from the DeclContext...
5860 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005861
John McCall9f54ad42009-12-10 09:41:52 +00005862 // ...and the scope, if applicable...
5863 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005864 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005865 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005866 }
5867
John McCall9f54ad42009-12-10 09:41:52 +00005868 // ...and the using decl.
5869 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5870
5871 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005872 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005873}
5874
John McCall7ba107a2009-11-18 02:36:19 +00005875/// Builds a using declaration.
5876///
5877/// \param IsInstantiation - Whether this call arises from an
5878/// instantiation of an unresolved using declaration. We treat
5879/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005880NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5881 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005882 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005883 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005884 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005885 bool IsInstantiation,
5886 bool IsTypeName,
5887 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005888 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005889 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005890 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005891
Anders Carlsson550b14b2009-08-28 05:49:21 +00005892 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005893
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005894 if (SS.isEmpty()) {
5895 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005896 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005897 }
Mike Stump1eb44332009-09-09 15:08:12 +00005898
John McCall9f54ad42009-12-10 09:41:52 +00005899 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005900 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005901 ForRedeclaration);
5902 Previous.setHideTags(false);
5903 if (S) {
5904 LookupName(Previous, S);
5905
5906 // It is really dumb that we have to do this.
5907 LookupResult::Filter F = Previous.makeFilter();
5908 while (F.hasNext()) {
5909 NamedDecl *D = F.next();
5910 if (!isDeclInScope(D, CurContext, S))
5911 F.erase();
5912 }
5913 F.done();
5914 } else {
5915 assert(IsInstantiation && "no scope in non-instantiation");
5916 assert(CurContext->isRecord() && "scope not record in instantiation");
5917 LookupQualifiedName(Previous, CurContext);
5918 }
5919
John McCall9f54ad42009-12-10 09:41:52 +00005920 // Check for invalid redeclarations.
5921 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5922 return 0;
5923
5924 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005925 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5926 return 0;
5927
John McCallaf8e6ed2009-11-12 03:15:40 +00005928 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005929 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005930 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005931 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005932 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005933 // FIXME: not all declaration name kinds are legal here
5934 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5935 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005936 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005937 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005938 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005939 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5940 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005941 }
John McCalled976492009-12-04 22:46:56 +00005942 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005943 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5944 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005945 }
John McCalled976492009-12-04 22:46:56 +00005946 D->setAccess(AS);
5947 CurContext->addDecl(D);
5948
5949 if (!LookupContext) return D;
5950 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005951
John McCall77bb1aa2010-05-01 00:40:08 +00005952 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005953 UD->setInvalidDecl();
5954 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005955 }
5956
Richard Smithc5a89a12012-04-02 01:30:27 +00005957 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00005958 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00005959 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005960 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005961 return UD;
5962 }
5963
5964 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005965
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005966 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00005967
John McCall604e7f12009-12-08 07:46:18 +00005968 // Unlike most lookups, we don't always want to hide tag
5969 // declarations: tag names are visible through the using declaration
5970 // even if hidden by ordinary names, *except* in a dependent context
5971 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005972 if (!IsInstantiation)
5973 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005974
John McCallb9abd8722012-04-07 03:04:20 +00005975 // For the purposes of this lookup, we have a base object type
5976 // equal to that of the current context.
5977 if (CurContext->isRecord()) {
5978 R.setBaseObjectType(
5979 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
5980 }
5981
John McCalla24dc2e2009-11-17 02:14:36 +00005982 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005983
John McCallf36e02d2009-10-09 21:13:30 +00005984 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005985 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005986 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005987 UD->setInvalidDecl();
5988 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005989 }
5990
John McCalled976492009-12-04 22:46:56 +00005991 if (R.isAmbiguous()) {
5992 UD->setInvalidDecl();
5993 return UD;
5994 }
Mike Stump1eb44332009-09-09 15:08:12 +00005995
John McCall7ba107a2009-11-18 02:36:19 +00005996 if (IsTypeName) {
5997 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005998 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005999 Diag(IdentLoc, diag::err_using_typename_non_type);
6000 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6001 Diag((*I)->getUnderlyingDecl()->getLocation(),
6002 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006003 UD->setInvalidDecl();
6004 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006005 }
6006 } else {
6007 // If we asked for a non-typename and we got a type, error out,
6008 // but only if this is an instantiation of an unresolved using
6009 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006010 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006011 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6012 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006013 UD->setInvalidDecl();
6014 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006015 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006016 }
6017
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006018 // C++0x N2914 [namespace.udecl]p6:
6019 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006020 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006021 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6022 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006023 UD->setInvalidDecl();
6024 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006025 }
Mike Stump1eb44332009-09-09 15:08:12 +00006026
John McCall9f54ad42009-12-10 09:41:52 +00006027 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6028 if (!CheckUsingShadowDecl(UD, *I, Previous))
6029 BuildUsingShadowDecl(S, UD, *I);
6030 }
John McCall9488ea12009-11-17 05:59:44 +00006031
6032 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006033}
6034
Sebastian Redlf677ea32011-02-05 19:23:19 +00006035/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006036bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6037 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006038
Douglas Gregordc355712011-02-25 00:36:19 +00006039 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006040 assert(SourceType &&
6041 "Using decl naming constructor doesn't have type in scope spec.");
6042 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6043
6044 // Check whether the named type is a direct base class.
6045 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6046 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6047 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6048 BaseIt != BaseE; ++BaseIt) {
6049 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6050 if (CanonicalSourceType == BaseType)
6051 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006052 if (BaseIt->getType()->isDependentType())
6053 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006054 }
6055
6056 if (BaseIt == BaseE) {
6057 // Did not find SourceType in the bases.
6058 Diag(UD->getUsingLocation(),
6059 diag::err_using_decl_constructor_not_in_direct_base)
6060 << UD->getNameInfo().getSourceRange()
6061 << QualType(SourceType, 0) << TargetClass;
6062 return true;
6063 }
6064
Richard Smithc5a89a12012-04-02 01:30:27 +00006065 if (!CurContext->isDependentContext())
6066 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006067
6068 return false;
6069}
6070
John McCall9f54ad42009-12-10 09:41:52 +00006071/// Checks that the given using declaration is not an invalid
6072/// redeclaration. Note that this is checking only for the using decl
6073/// itself, not for any ill-formedness among the UsingShadowDecls.
6074bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6075 bool isTypeName,
6076 const CXXScopeSpec &SS,
6077 SourceLocation NameLoc,
6078 const LookupResult &Prev) {
6079 // C++03 [namespace.udecl]p8:
6080 // C++0x [namespace.udecl]p10:
6081 // A using-declaration is a declaration and can therefore be used
6082 // repeatedly where (and only where) multiple declarations are
6083 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006084 //
John McCall8a726212010-11-29 18:01:58 +00006085 // That's in non-member contexts.
6086 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006087 return false;
6088
6089 NestedNameSpecifier *Qual
6090 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6091
6092 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6093 NamedDecl *D = *I;
6094
6095 bool DTypename;
6096 NestedNameSpecifier *DQual;
6097 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6098 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006099 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006100 } else if (UnresolvedUsingValueDecl *UD
6101 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6102 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006103 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006104 } else if (UnresolvedUsingTypenameDecl *UD
6105 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6106 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006107 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006108 } else continue;
6109
6110 // using decls differ if one says 'typename' and the other doesn't.
6111 // FIXME: non-dependent using decls?
6112 if (isTypeName != DTypename) continue;
6113
6114 // using decls differ if they name different scopes (but note that
6115 // template instantiation can cause this check to trigger when it
6116 // didn't before instantiation).
6117 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6118 Context.getCanonicalNestedNameSpecifier(DQual))
6119 continue;
6120
6121 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006122 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006123 return true;
6124 }
6125
6126 return false;
6127}
6128
John McCall604e7f12009-12-08 07:46:18 +00006129
John McCalled976492009-12-04 22:46:56 +00006130/// Checks that the given nested-name qualifier used in a using decl
6131/// in the current context is appropriately related to the current
6132/// scope. If an error is found, diagnoses it and returns true.
6133bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6134 const CXXScopeSpec &SS,
6135 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006136 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006137
John McCall604e7f12009-12-08 07:46:18 +00006138 if (!CurContext->isRecord()) {
6139 // C++03 [namespace.udecl]p3:
6140 // C++0x [namespace.udecl]p8:
6141 // A using-declaration for a class member shall be a member-declaration.
6142
6143 // If we weren't able to compute a valid scope, it must be a
6144 // dependent class scope.
6145 if (!NamedContext || NamedContext->isRecord()) {
6146 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6147 << SS.getRange();
6148 return true;
6149 }
6150
6151 // Otherwise, everything is known to be fine.
6152 return false;
6153 }
6154
6155 // The current scope is a record.
6156
6157 // If the named context is dependent, we can't decide much.
6158 if (!NamedContext) {
6159 // FIXME: in C++0x, we can diagnose if we can prove that the
6160 // nested-name-specifier does not refer to a base class, which is
6161 // still possible in some cases.
6162
6163 // Otherwise we have to conservatively report that things might be
6164 // okay.
6165 return false;
6166 }
6167
6168 if (!NamedContext->isRecord()) {
6169 // Ideally this would point at the last name in the specifier,
6170 // but we don't have that level of source info.
6171 Diag(SS.getRange().getBegin(),
6172 diag::err_using_decl_nested_name_specifier_is_not_class)
6173 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6174 return true;
6175 }
6176
Douglas Gregor6fb07292010-12-21 07:41:49 +00006177 if (!NamedContext->isDependentContext() &&
6178 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6179 return true;
6180
David Blaikie4e4d0842012-03-11 07:00:24 +00006181 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006182 // C++0x [namespace.udecl]p3:
6183 // In a using-declaration used as a member-declaration, the
6184 // nested-name-specifier shall name a base class of the class
6185 // being defined.
6186
6187 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6188 cast<CXXRecordDecl>(NamedContext))) {
6189 if (CurContext == NamedContext) {
6190 Diag(NameLoc,
6191 diag::err_using_decl_nested_name_specifier_is_current_class)
6192 << SS.getRange();
6193 return true;
6194 }
6195
6196 Diag(SS.getRange().getBegin(),
6197 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6198 << (NestedNameSpecifier*) SS.getScopeRep()
6199 << cast<CXXRecordDecl>(CurContext)
6200 << SS.getRange();
6201 return true;
6202 }
6203
6204 return false;
6205 }
6206
6207 // C++03 [namespace.udecl]p4:
6208 // A using-declaration used as a member-declaration shall refer
6209 // to a member of a base class of the class being defined [etc.].
6210
6211 // Salient point: SS doesn't have to name a base class as long as
6212 // lookup only finds members from base classes. Therefore we can
6213 // diagnose here only if we can prove that that can't happen,
6214 // i.e. if the class hierarchies provably don't intersect.
6215
6216 // TODO: it would be nice if "definitely valid" results were cached
6217 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6218 // need to be repeated.
6219
6220 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006221 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006222
6223 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6224 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6225 Data->Bases.insert(Base);
6226 return true;
6227 }
6228
6229 bool hasDependentBases(const CXXRecordDecl *Class) {
6230 return !Class->forallBases(collect, this);
6231 }
6232
6233 /// Returns true if the base is dependent or is one of the
6234 /// accumulated base classes.
6235 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6236 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6237 return !Data->Bases.count(Base);
6238 }
6239
6240 bool mightShareBases(const CXXRecordDecl *Class) {
6241 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6242 }
6243 };
6244
6245 UserData Data;
6246
6247 // Returns false if we find a dependent base.
6248 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6249 return false;
6250
6251 // Returns false if the class has a dependent base or if it or one
6252 // of its bases is present in the base set of the current context.
6253 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6254 return false;
6255
6256 Diag(SS.getRange().getBegin(),
6257 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6258 << (NestedNameSpecifier*) SS.getScopeRep()
6259 << cast<CXXRecordDecl>(CurContext)
6260 << SS.getRange();
6261
6262 return true;
John McCalled976492009-12-04 22:46:56 +00006263}
6264
Richard Smith162e1c12011-04-15 14:24:37 +00006265Decl *Sema::ActOnAliasDeclaration(Scope *S,
6266 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006267 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006268 SourceLocation UsingLoc,
6269 UnqualifiedId &Name,
6270 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006271 // Skip up to the relevant declaration scope.
6272 while (S->getFlags() & Scope::TemplateParamScope)
6273 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006274 assert((S->getFlags() & Scope::DeclScope) &&
6275 "got alias-declaration outside of declaration scope");
6276
6277 if (Type.isInvalid())
6278 return 0;
6279
6280 bool Invalid = false;
6281 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6282 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006283 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006284
6285 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6286 return 0;
6287
6288 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006289 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006290 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006291 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6292 TInfo->getTypeLoc().getBeginLoc());
6293 }
Richard Smith162e1c12011-04-15 14:24:37 +00006294
6295 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6296 LookupName(Previous, S);
6297
6298 // Warn about shadowing the name of a template parameter.
6299 if (Previous.isSingleResult() &&
6300 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006301 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006302 Previous.clear();
6303 }
6304
6305 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6306 "name in alias declaration must be an identifier");
6307 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6308 Name.StartLocation,
6309 Name.Identifier, TInfo);
6310
6311 NewTD->setAccess(AS);
6312
6313 if (Invalid)
6314 NewTD->setInvalidDecl();
6315
Richard Smith3e4c6c42011-05-05 21:57:07 +00006316 CheckTypedefForVariablyModifiedType(S, NewTD);
6317 Invalid |= NewTD->isInvalidDecl();
6318
Richard Smith162e1c12011-04-15 14:24:37 +00006319 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006320
6321 NamedDecl *NewND;
6322 if (TemplateParamLists.size()) {
6323 TypeAliasTemplateDecl *OldDecl = 0;
6324 TemplateParameterList *OldTemplateParams = 0;
6325
6326 if (TemplateParamLists.size() != 1) {
6327 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6328 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6329 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6330 }
6331 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6332
6333 // Only consider previous declarations in the same scope.
6334 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6335 /*ExplicitInstantiationOrSpecialization*/false);
6336 if (!Previous.empty()) {
6337 Redeclaration = true;
6338
6339 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6340 if (!OldDecl && !Invalid) {
6341 Diag(UsingLoc, diag::err_redefinition_different_kind)
6342 << Name.Identifier;
6343
6344 NamedDecl *OldD = Previous.getRepresentativeDecl();
6345 if (OldD->getLocation().isValid())
6346 Diag(OldD->getLocation(), diag::note_previous_definition);
6347
6348 Invalid = true;
6349 }
6350
6351 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6352 if (TemplateParameterListsAreEqual(TemplateParams,
6353 OldDecl->getTemplateParameters(),
6354 /*Complain=*/true,
6355 TPL_TemplateMatch))
6356 OldTemplateParams = OldDecl->getTemplateParameters();
6357 else
6358 Invalid = true;
6359
6360 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6361 if (!Invalid &&
6362 !Context.hasSameType(OldTD->getUnderlyingType(),
6363 NewTD->getUnderlyingType())) {
6364 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6365 // but we can't reasonably accept it.
6366 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6367 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6368 if (OldTD->getLocation().isValid())
6369 Diag(OldTD->getLocation(), diag::note_previous_definition);
6370 Invalid = true;
6371 }
6372 }
6373 }
6374
6375 // Merge any previous default template arguments into our parameters,
6376 // and check the parameter list.
6377 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6378 TPC_TypeAliasTemplate))
6379 return 0;
6380
6381 TypeAliasTemplateDecl *NewDecl =
6382 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6383 Name.Identifier, TemplateParams,
6384 NewTD);
6385
6386 NewDecl->setAccess(AS);
6387
6388 if (Invalid)
6389 NewDecl->setInvalidDecl();
6390 else if (OldDecl)
6391 NewDecl->setPreviousDeclaration(OldDecl);
6392
6393 NewND = NewDecl;
6394 } else {
6395 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6396 NewND = NewTD;
6397 }
Richard Smith162e1c12011-04-15 14:24:37 +00006398
6399 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006400 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006401
Richard Smith3e4c6c42011-05-05 21:57:07 +00006402 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006403}
6404
John McCalld226f652010-08-21 09:40:31 +00006405Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006406 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006407 SourceLocation AliasLoc,
6408 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006409 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006410 SourceLocation IdentLoc,
6411 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006412
Anders Carlsson81c85c42009-03-28 23:53:49 +00006413 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006414 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6415 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006416
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006417 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006418 NamedDecl *PrevDecl
6419 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6420 ForRedeclaration);
6421 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6422 PrevDecl = 0;
6423
6424 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006425 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006426 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006427 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006428 // FIXME: At some point, we'll want to create the (redundant)
6429 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006430 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006431 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006432 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006433 }
Mike Stump1eb44332009-09-09 15:08:12 +00006434
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006435 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6436 diag::err_redefinition_different_kind;
6437 Diag(AliasLoc, DiagID) << Alias;
6438 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006439 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006440 }
6441
John McCalla24dc2e2009-11-17 02:14:36 +00006442 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006443 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006444
John McCallf36e02d2009-10-09 21:13:30 +00006445 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006446 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006447 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006448 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006449 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006450 }
Mike Stump1eb44332009-09-09 15:08:12 +00006451
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006452 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006453 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006454 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006455 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006456
John McCall3dbd3d52010-02-16 06:53:13 +00006457 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006458 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006459}
6460
Douglas Gregor39957dc2010-05-01 15:04:51 +00006461namespace {
6462 /// \brief Scoped object used to handle the state changes required in Sema
6463 /// to implicitly define the body of a C++ member function;
6464 class ImplicitlyDefinedFunctionScope {
6465 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006466 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006467
6468 public:
6469 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006470 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006471 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006472 S.PushFunctionScope();
6473 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6474 }
6475
6476 ~ImplicitlyDefinedFunctionScope() {
6477 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006478 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006479 }
6480 };
6481}
6482
Sean Hunt001cad92011-05-10 00:49:42 +00006483Sema::ImplicitExceptionSpecification
6484Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006485 // C++ [except.spec]p14:
6486 // An implicitly declared special member function (Clause 12) shall have an
6487 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006488 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006489 if (ClassDecl->isInvalidDecl())
6490 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006491
Sebastian Redl60618fa2011-03-12 11:50:43 +00006492 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006493 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6494 BEnd = ClassDecl->bases_end();
6495 B != BEnd; ++B) {
6496 if (B->isVirtual()) // Handled below.
6497 continue;
6498
Douglas Gregor18274032010-07-03 00:47:00 +00006499 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6500 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006501 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6502 // If this is a deleted function, add it anyway. This might be conformant
6503 // with the standard. This might not. I'm not sure. It might not matter.
6504 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006505 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006506 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006507 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006508
6509 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006510 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6511 BEnd = ClassDecl->vbases_end();
6512 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006513 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6514 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006515 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6516 // If this is a deleted function, add it anyway. This might be conformant
6517 // with the standard. This might not. I'm not sure. It might not matter.
6518 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006519 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006520 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006521 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006522
6523 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006524 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6525 FEnd = ClassDecl->field_end();
6526 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006527 if (F->hasInClassInitializer()) {
6528 if (Expr *E = F->getInClassInitializer())
6529 ExceptSpec.CalledExpr(E);
6530 else if (!F->isInvalidDecl())
6531 ExceptSpec.SetDelayed();
6532 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006533 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006534 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6535 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6536 // If this is a deleted function, add it anyway. This might be conformant
6537 // with the standard. This might not. I'm not sure. It might not matter.
6538 // In particular, the problem is that this function never gets called. It
6539 // might just be ill-formed because this function attempts to refer to
6540 // a deleted function here.
6541 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006542 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006543 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006544 }
John McCalle23cf432010-12-14 08:05:40 +00006545
Sean Hunt001cad92011-05-10 00:49:42 +00006546 return ExceptSpec;
6547}
6548
6549CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6550 CXXRecordDecl *ClassDecl) {
6551 // C++ [class.ctor]p5:
6552 // A default constructor for a class X is a constructor of class X
6553 // that can be called without an argument. If there is no
6554 // user-declared constructor for class X, a default constructor is
6555 // implicitly declared. An implicitly-declared default constructor
6556 // is an inline public member of its class.
6557 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6558 "Should not build implicit default constructor!");
6559
6560 ImplicitExceptionSpecification Spec =
6561 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6562 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006563
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006564 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006565 CanQualType ClassType
6566 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006567 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006568 DeclarationName Name
6569 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006570 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006571 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6572 Context, ClassDecl, ClassLoc, NameInfo,
6573 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6574 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6575 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006576 getLangOpts().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006577 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006578 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006579 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006580 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006581
6582 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006583 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6584
Douglas Gregor23c94db2010-07-02 17:43:08 +00006585 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006586 PushOnScopeChains(DefaultCon, S, false);
6587 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006588
Sean Hunte16da072011-10-10 06:18:57 +00006589 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006590 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006591
Douglas Gregor32df23e2010-07-01 22:02:46 +00006592 return DefaultCon;
6593}
6594
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006595void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6596 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006597 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006598 !Constructor->doesThisDeclarationHaveABody() &&
6599 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006600 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006601
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006602 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006603 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006604
Douglas Gregor39957dc2010-05-01 15:04:51 +00006605 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006606 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006607 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006608 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006609 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006610 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006611 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006612 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006613 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006614
6615 SourceLocation Loc = Constructor->getLocation();
6616 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6617
6618 Constructor->setUsed();
6619 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006620
6621 if (ASTMutationListener *L = getASTMutationListener()) {
6622 L->CompletedImplicitDefinition(Constructor);
6623 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006624}
6625
Richard Smith7a614d82011-06-11 17:19:42 +00006626/// Get any existing defaulted default constructor for the given class. Do not
6627/// implicitly define one if it does not exist.
6628static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6629 CXXRecordDecl *D) {
6630 ASTContext &Context = Self.Context;
6631 QualType ClassType = Context.getTypeDeclType(D);
6632 DeclarationName ConstructorName
6633 = Context.DeclarationNames.getCXXConstructorName(
6634 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6635
6636 DeclContext::lookup_const_iterator Con, ConEnd;
6637 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6638 Con != ConEnd; ++Con) {
6639 // A function template cannot be defaulted.
6640 if (isa<FunctionTemplateDecl>(*Con))
6641 continue;
6642
6643 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6644 if (Constructor->isDefaultConstructor())
6645 return Constructor->isDefaulted() ? Constructor : 0;
6646 }
6647 return 0;
6648}
6649
6650void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6651 if (!D) return;
6652 AdjustDeclIfTemplate(D);
6653
6654 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6655 CXXConstructorDecl *CtorDecl
6656 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6657
6658 if (!CtorDecl) return;
6659
6660 // Compute the exception specification for the default constructor.
6661 const FunctionProtoType *CtorTy =
6662 CtorDecl->getType()->castAs<FunctionProtoType>();
6663 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
Richard Smithe6975e92012-04-17 00:58:00 +00006664 // FIXME: Don't do this unless the exception spec is needed.
Richard Smith7a614d82011-06-11 17:19:42 +00006665 ImplicitExceptionSpecification Spec =
6666 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6667 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6668 assert(EPI.ExceptionSpecType != EST_Delayed);
6669
6670 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6671 }
6672
6673 // If the default constructor is explicitly defaulted, checking the exception
6674 // specification is deferred until now.
6675 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6676 !ClassDecl->isDependentType())
Richard Smith3003e1d2012-05-15 04:39:51 +00006677 CheckExplicitlyDefaultedSpecialMember(CtorDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006678}
6679
Sebastian Redlf677ea32011-02-05 19:23:19 +00006680void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6681 // We start with an initial pass over the base classes to collect those that
6682 // inherit constructors from. If there are none, we can forgo all further
6683 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006684 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006685 BasesVector BasesToInheritFrom;
6686 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6687 BaseE = ClassDecl->bases_end();
6688 BaseIt != BaseE; ++BaseIt) {
6689 if (BaseIt->getInheritConstructors()) {
6690 QualType Base = BaseIt->getType();
6691 if (Base->isDependentType()) {
6692 // If we inherit constructors from anything that is dependent, just
6693 // abort processing altogether. We'll get another chance for the
6694 // instantiations.
6695 return;
6696 }
6697 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6698 }
6699 }
6700 if (BasesToInheritFrom.empty())
6701 return;
6702
6703 // Now collect the constructors that we already have in the current class.
6704 // Those take precedence over inherited constructors.
6705 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6706 // unless there is a user-declared constructor with the same signature in
6707 // the class where the using-declaration appears.
6708 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6709 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6710 CtorE = ClassDecl->ctor_end();
6711 CtorIt != CtorE; ++CtorIt) {
6712 ExistingConstructors.insert(
6713 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6714 }
6715
Sebastian Redlf677ea32011-02-05 19:23:19 +00006716 DeclarationName CreatedCtorName =
6717 Context.DeclarationNames.getCXXConstructorName(
6718 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6719
6720 // Now comes the true work.
6721 // First, we keep a map from constructor types to the base that introduced
6722 // them. Needed for finding conflicting constructors. We also keep the
6723 // actually inserted declarations in there, for pretty diagnostics.
6724 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6725 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6726 ConstructorToSourceMap InheritedConstructors;
6727 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6728 BaseE = BasesToInheritFrom.end();
6729 BaseIt != BaseE; ++BaseIt) {
6730 const RecordType *Base = *BaseIt;
6731 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6732 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6733 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6734 CtorE = BaseDecl->ctor_end();
6735 CtorIt != CtorE; ++CtorIt) {
6736 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006737 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006738 DeclarationName Name =
6739 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006740 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6741 LookupQualifiedName(Result, CurContext);
6742 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006743 SourceLocation UsingLoc = UD ? UD->getLocation() :
6744 ClassDecl->getLocation();
6745
6746 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6747 // from the class X named in the using-declaration consists of actual
6748 // constructors and notional constructors that result from the
6749 // transformation of defaulted parameters as follows:
6750 // - all non-template default constructors of X, and
6751 // - for each non-template constructor of X that has at least one
6752 // parameter with a default argument, the set of constructors that
6753 // results from omitting any ellipsis parameter specification and
6754 // successively omitting parameters with a default argument from the
6755 // end of the parameter-type-list.
David Blaikie262bc182012-04-30 02:36:29 +00006756 CXXConstructorDecl *BaseCtor = &*CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006757 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6758 const FunctionProtoType *BaseCtorType =
6759 BaseCtor->getType()->getAs<FunctionProtoType>();
6760
6761 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6762 maxParams = BaseCtor->getNumParams();
6763 params <= maxParams; ++params) {
6764 // Skip default constructors. They're never inherited.
6765 if (params == 0)
6766 continue;
6767 // Skip copy and move constructors for the same reason.
6768 if (CanBeCopyOrMove && params == 1)
6769 continue;
6770
6771 // Build up a function type for this particular constructor.
6772 // FIXME: The working paper does not consider that the exception spec
6773 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006774 // source. This code doesn't yet, either. When it does, this code will
6775 // need to be delayed until after exception specifications and in-class
6776 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006777 const Type *NewCtorType;
6778 if (params == maxParams)
6779 NewCtorType = BaseCtorType;
6780 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006781 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006782 for (unsigned i = 0; i < params; ++i) {
6783 Args.push_back(BaseCtorType->getArgType(i));
6784 }
6785 FunctionProtoType::ExtProtoInfo ExtInfo =
6786 BaseCtorType->getExtProtoInfo();
6787 ExtInfo.Variadic = false;
6788 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6789 Args.data(), params, ExtInfo)
6790 .getTypePtr();
6791 }
6792 const Type *CanonicalNewCtorType =
6793 Context.getCanonicalType(NewCtorType);
6794
6795 // Now that we have the type, first check if the class already has a
6796 // constructor with this signature.
6797 if (ExistingConstructors.count(CanonicalNewCtorType))
6798 continue;
6799
6800 // Then we check if we have already declared an inherited constructor
6801 // with this signature.
6802 std::pair<ConstructorToSourceMap::iterator, bool> result =
6803 InheritedConstructors.insert(std::make_pair(
6804 CanonicalNewCtorType,
6805 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6806 if (!result.second) {
6807 // Already in the map. If it came from a different class, that's an
6808 // error. Not if it's from the same.
6809 CanQualType PreviousBase = result.first->second.first;
6810 if (CanonicalBase != PreviousBase) {
6811 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6812 const CXXConstructorDecl *PrevBaseCtor =
6813 PrevCtor->getInheritedConstructor();
6814 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6815
6816 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6817 Diag(BaseCtor->getLocation(),
6818 diag::note_using_decl_constructor_conflict_current_ctor);
6819 Diag(PrevBaseCtor->getLocation(),
6820 diag::note_using_decl_constructor_conflict_previous_ctor);
6821 Diag(PrevCtor->getLocation(),
6822 diag::note_using_decl_constructor_conflict_previous_using);
6823 }
6824 continue;
6825 }
6826
6827 // OK, we're there, now add the constructor.
6828 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006829 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006830 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6831 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006832 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6833 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006834 /*ImplicitlyDeclared=*/true,
6835 // FIXME: Due to a defect in the standard, we treat inherited
6836 // constructors as constexpr even if that makes them ill-formed.
6837 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006838 NewCtor->setAccess(BaseCtor->getAccess());
6839
6840 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006841 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006842 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006843 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6844 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006845 /*IdentifierInfo=*/0,
6846 BaseCtorType->getArgType(i),
6847 /*TInfo=*/0, SC_None,
6848 SC_None, /*DefaultArg=*/0));
6849 }
David Blaikie4278c652011-09-21 18:16:56 +00006850 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006851 NewCtor->setInheritedConstructor(BaseCtor);
6852
Sebastian Redlf677ea32011-02-05 19:23:19 +00006853 ClassDecl->addDecl(NewCtor);
6854 result.first->second.second = NewCtor;
6855 }
6856 }
6857 }
6858}
6859
Sean Huntcb45a0f2011-05-12 22:46:25 +00006860Sema::ImplicitExceptionSpecification
6861Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006862 // C++ [except.spec]p14:
6863 // An implicitly declared special member function (Clause 12) shall have
6864 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00006865 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006866 if (ClassDecl->isInvalidDecl())
6867 return ExceptSpec;
6868
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006869 // Direct base-class destructors.
6870 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6871 BEnd = ClassDecl->bases_end();
6872 B != BEnd; ++B) {
6873 if (B->isVirtual()) // Handled below.
6874 continue;
6875
6876 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006877 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006878 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006879 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006880
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006881 // Virtual base-class destructors.
6882 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6883 BEnd = ClassDecl->vbases_end();
6884 B != BEnd; ++B) {
6885 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006886 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006887 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006888 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006889
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006890 // Field destructors.
6891 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6892 FEnd = ClassDecl->field_end();
6893 F != FEnd; ++F) {
6894 if (const RecordType *RecordTy
6895 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00006896 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00006897 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006898 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006899
Sean Huntcb45a0f2011-05-12 22:46:25 +00006900 return ExceptSpec;
6901}
6902
6903CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6904 // C++ [class.dtor]p2:
6905 // If a class has no user-declared destructor, a destructor is
6906 // declared implicitly. An implicitly-declared destructor is an
6907 // inline public member of its class.
6908
6909 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006910 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006911 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6912
Douglas Gregor4923aa22010-07-02 20:37:36 +00006913 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006914 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006915
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006916 CanQualType ClassType
6917 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006918 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006919 DeclarationName Name
6920 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006921 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006922 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006923 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6924 /*isInline=*/true,
6925 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006926 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006927 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006928 Destructor->setImplicit();
6929 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006930
6931 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006932 ++ASTContext::NumImplicitDestructorsDeclared;
6933
6934 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006935 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006936 PushOnScopeChains(Destructor, S, false);
6937 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006938
6939 // This could be uniqued if it ever proves significant.
6940 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006941
Richard Smith9a561d52012-02-26 09:11:52 +00006942 AddOverriddenMethods(ClassDecl, Destructor);
6943
Richard Smith7d5088a2012-02-18 02:02:13 +00006944 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00006945 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00006946
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006947 return Destructor;
6948}
6949
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006950void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006951 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006952 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00006953 !Destructor->doesThisDeclarationHaveABody() &&
6954 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006955 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006956 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006957 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006958
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006959 if (Destructor->isInvalidDecl())
6960 return;
6961
Douglas Gregor39957dc2010-05-01 15:04:51 +00006962 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006963
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006964 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006965 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6966 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006967
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006968 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006969 Diag(CurrentLocation, diag::note_member_synthesized_at)
6970 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6971
6972 Destructor->setInvalidDecl();
6973 return;
6974 }
6975
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006976 SourceLocation Loc = Destructor->getLocation();
6977 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00006978 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006979 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006980 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006981
6982 if (ASTMutationListener *L = getASTMutationListener()) {
6983 L->CompletedImplicitDefinition(Destructor);
6984 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006985}
6986
Richard Smitha4156b82012-04-21 18:42:51 +00006987/// \brief Perform any semantic analysis which needs to be delayed until all
6988/// pending class member declarations have been parsed.
6989void Sema::ActOnFinishCXXMemberDecls() {
6990 // Now we have parsed all exception specifications, determine the implicit
6991 // exception specifications for destructors.
6992 for (unsigned i = 0, e = DelayedDestructorExceptionSpecs.size();
6993 i != e; ++i) {
6994 CXXDestructorDecl *Dtor = DelayedDestructorExceptionSpecs[i];
6995 AdjustDestructorExceptionSpec(Dtor->getParent(), Dtor, true);
6996 }
6997 DelayedDestructorExceptionSpecs.clear();
6998
6999 // Perform any deferred checking of exception specifications for virtual
7000 // destructors.
7001 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7002 i != e; ++i) {
7003 const CXXDestructorDecl *Dtor =
7004 DelayedDestructorExceptionSpecChecks[i].first;
7005 assert(!Dtor->getParent()->isDependentType() &&
7006 "Should not ever add destructors of templates into the list.");
7007 CheckOverridingFunctionExceptionSpec(Dtor,
7008 DelayedDestructorExceptionSpecChecks[i].second);
7009 }
7010 DelayedDestructorExceptionSpecChecks.clear();
7011}
7012
Sebastian Redl0ee33912011-05-19 05:13:44 +00007013void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
Richard Smitha4156b82012-04-21 18:42:51 +00007014 CXXDestructorDecl *destructor,
7015 bool WasDelayed) {
Sebastian Redl0ee33912011-05-19 05:13:44 +00007016 // C++11 [class.dtor]p3:
7017 // A declaration of a destructor that does not have an exception-
7018 // specification is implicitly considered to have the same exception-
7019 // specification as an implicit declaration.
7020 const FunctionProtoType *dtorType = destructor->getType()->
7021 getAs<FunctionProtoType>();
Richard Smitha4156b82012-04-21 18:42:51 +00007022 if (!WasDelayed && dtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007023 return;
7024
7025 ImplicitExceptionSpecification exceptSpec =
7026 ComputeDefaultedDtorExceptionSpec(classDecl);
7027
Chandler Carruth3f224b22011-09-20 04:55:26 +00007028 // Replace the destructor's type, building off the existing one. Fortunately,
7029 // the only thing of interest in the destructor type is its extended info.
7030 // The return and arguments are fixed.
7031 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007032 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7033 epi.NumExceptions = exceptSpec.size();
7034 epi.Exceptions = exceptSpec.data();
7035 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7036
7037 destructor->setType(ty);
7038
Richard Smitha4156b82012-04-21 18:42:51 +00007039 // If we can't compute the exception specification for this destructor yet
7040 // (because it depends on an exception specification which we have not parsed
7041 // yet), make a note that we need to try again when the class is complete.
7042 if (epi.ExceptionSpecType == EST_Delayed) {
7043 assert(!WasDelayed && "couldn't compute destructor exception spec");
7044 DelayedDestructorExceptionSpecs.push_back(destructor);
7045 }
7046
Sebastian Redl0ee33912011-05-19 05:13:44 +00007047 // FIXME: If the destructor has a body that could throw, and the newly created
7048 // spec doesn't allow exceptions, we should emit a warning, because this
7049 // change in behavior can break conforming C++03 programs at runtime.
7050 // However, we don't have a body yet, so it needs to be done somewhere else.
7051}
7052
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007053/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007054/// \c To.
7055///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007056/// This routine is used to copy/move the members of a class with an
7057/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007058/// copied are arrays, this routine builds for loops to copy them.
7059///
7060/// \param S The Sema object used for type-checking.
7061///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007062/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007063///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007064/// \param T The type of the expressions being copied/moved. Both expressions
7065/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007066///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007067/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007068///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007069/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007070///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007071/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007072/// Otherwise, it's a non-static member subobject.
7073///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007074/// \param Copying Whether we're copying or moving.
7075///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007076/// \param Depth Internal parameter recording the depth of the recursion.
7077///
7078/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007079static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007080BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007081 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007082 bool CopyingBaseSubobject, bool Copying,
7083 unsigned Depth = 0) {
7084 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007085 // Each subobject is assigned in the manner appropriate to its type:
7086 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007087 // - if the subobject is of class type, as if by a call to operator= with
7088 // the subobject as the object expression and the corresponding
7089 // subobject of x as a single function argument (as if by explicit
7090 // qualification; that is, ignoring any possible virtual overriding
7091 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007092 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7093 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7094
7095 // Look for operator=.
7096 DeclarationName Name
7097 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7098 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7099 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7100
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007101 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007102 LookupResult::Filter F = OpLookup.makeFilter();
7103 while (F.hasNext()) {
7104 NamedDecl *D = F.next();
7105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007106 if (Method->isCopyAssignmentOperator() ||
7107 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007108 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007109
Douglas Gregor06a9f362010-05-01 20:49:11 +00007110 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007111 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007112 F.done();
7113
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007114 // Suppress the protected check (C++ [class.protected]) for each of the
7115 // assignment operators we found. This strange dance is required when
7116 // we're assigning via a base classes's copy-assignment operator. To
7117 // ensure that we're getting the right base class subobject (without
7118 // ambiguities), we need to cast "this" to that subobject type; to
7119 // ensure that we don't go through the virtual call mechanism, we need
7120 // to qualify the operator= name with the base class (see below). However,
7121 // this means that if the base class has a protected copy assignment
7122 // operator, the protected member access check will fail. So, we
7123 // rewrite "protected" access to "public" access in this case, since we
7124 // know by construction that we're calling from a derived class.
7125 if (CopyingBaseSubobject) {
7126 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7127 L != LEnd; ++L) {
7128 if (L.getAccess() == AS_protected)
7129 L.setAccess(AS_public);
7130 }
7131 }
7132
Douglas Gregor06a9f362010-05-01 20:49:11 +00007133 // Create the nested-name-specifier that will be used to qualify the
7134 // reference to operator=; this is required to suppress the virtual
7135 // call mechanism.
7136 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007137 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007138 SS.MakeTrivial(S.Context,
7139 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007140 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007141 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007142
7143 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007144 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007145 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007146 /*TemplateKWLoc=*/SourceLocation(),
7147 /*FirstQualifierInScope=*/0,
7148 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007149 /*TemplateArgs=*/0,
7150 /*SuppressQualifierCheck=*/true);
7151 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007152 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007153
7154 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007155
John McCall60d7b3a2010-08-24 06:29:42 +00007156 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007157 OpEqualRef.takeAs<Expr>(),
7158 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007159 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007160 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007161
7162 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007163 }
John McCallb0207482010-03-16 06:11:48 +00007164
Douglas Gregor06a9f362010-05-01 20:49:11 +00007165 // - if the subobject is of scalar type, the built-in assignment
7166 // operator is used.
7167 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7168 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007169 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007170 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007171 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007172
7173 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007174 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007175
7176 // - if the subobject is an array, each element is assigned, in the
7177 // manner appropriate to the element type;
7178
7179 // Construct a loop over the array bounds, e.g.,
7180 //
7181 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7182 //
7183 // that will copy each of the array elements.
7184 QualType SizeType = S.Context.getSizeType();
7185
7186 // Create the iteration variable.
7187 IdentifierInfo *IterationVarName = 0;
7188 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007189 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007190 llvm::raw_svector_ostream OS(Str);
7191 OS << "__i" << Depth;
7192 IterationVarName = &S.Context.Idents.get(OS.str());
7193 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007194 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007195 IterationVarName, SizeType,
7196 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007197 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007198
7199 // Initialize the iteration variable to zero.
7200 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007201 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007202
7203 // Create a reference to the iteration variable; we'll use this several
7204 // times throughout.
7205 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007206 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007207 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007208 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7209 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7210
Douglas Gregor06a9f362010-05-01 20:49:11 +00007211 // Create the DeclStmt that holds the iteration variable.
7212 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7213
7214 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007215 llvm::APInt Upper
7216 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007217 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007218 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007219 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7220 BO_NE, S.Context.BoolTy,
7221 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007222
7223 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007224 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007225 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7226 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007227
7228 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007229 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007230 IterationVarRefRVal,
7231 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007232 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007233 IterationVarRefRVal,
7234 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007235 if (!Copying) // Cast to rvalue
7236 From = CastForMoving(S, From);
7237
7238 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007239 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7240 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007241 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007242 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007243 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007244
7245 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007246 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007247 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007248 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007249 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007250}
7251
Sean Hunt30de05c2011-05-14 05:23:20 +00007252std::pair<Sema::ImplicitExceptionSpecification, bool>
7253Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7254 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007255 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00007256 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007257
Douglas Gregord3c35902010-07-01 16:36:15 +00007258 // C++ [class.copy]p10:
7259 // If the class definition does not explicitly declare a copy
7260 // assignment operator, one is declared implicitly.
7261 // The implicitly-defined copy assignment operator for a class X
7262 // will have the form
7263 //
7264 // X& X::operator=(const X&)
7265 //
7266 // if
7267 bool HasConstCopyAssignment = true;
7268
7269 // -- each direct base class B of X has a copy assignment operator
7270 // whose parameter is of type const B&, const volatile B& or B,
7271 // and
7272 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7273 BaseEnd = ClassDecl->bases_end();
7274 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007275 // We'll handle this below
7276 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7277 continue;
7278
Douglas Gregord3c35902010-07-01 16:36:15 +00007279 assert(!Base->getType()->isDependentType() &&
7280 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007281 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007282 HasConstCopyAssignment &=
7283 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7284 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007285 }
7286
Richard Smithebaf0e62011-10-18 20:49:44 +00007287 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007288 if (LangOpts.CPlusPlus0x) {
7289 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7290 BaseEnd = ClassDecl->vbases_end();
7291 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7292 assert(!Base->getType()->isDependentType() &&
7293 "Cannot generate implicit members for class with dependent bases.");
7294 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smith704c8f72012-04-20 18:46:14 +00007295 HasConstCopyAssignment &=
7296 (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7297 false, 0);
Sean Hunt661c67a2011-06-21 23:42:56 +00007298 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007299 }
7300
7301 // -- for all the nonstatic data members of X that are of a class
7302 // type M (or array thereof), each such class type has a copy
7303 // assignment operator whose parameter is of type const M&,
7304 // const volatile M& or M.
7305 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7306 FieldEnd = ClassDecl->field_end();
7307 HasConstCopyAssignment && Field != FieldEnd;
7308 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007309 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007310 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00007311 HasConstCopyAssignment &=
7312 (bool)LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7313 false, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007314 }
7315 }
7316
7317 // Otherwise, the implicitly declared copy assignment operator will
7318 // have the form
7319 //
7320 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007321
Douglas Gregorb87786f2010-07-01 17:48:08 +00007322 // C++ [except.spec]p14:
7323 // An implicitly declared special member function (Clause 12) shall have an
7324 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007325
7326 // It is unspecified whether or not an implicit copy assignment operator
7327 // attempts to deduplicate calls to assignment operators of virtual bases are
7328 // made. As such, this exception specification is effectively unspecified.
7329 // Based on a similar decision made for constness in C++0x, we're erring on
7330 // the side of assuming such calls to be made regardless of whether they
7331 // actually happen.
Richard Smithe6975e92012-04-17 00:58:00 +00007332 ImplicitExceptionSpecification ExceptSpec(*this);
Sean Hunt661c67a2011-06-21 23:42:56 +00007333 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007334 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7335 BaseEnd = ClassDecl->bases_end();
7336 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007337 if (Base->isVirtual())
7338 continue;
7339
Douglas Gregora376d102010-07-02 21:50:04 +00007340 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007341 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007342 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7343 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007344 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007345 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007346
7347 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7348 BaseEnd = ClassDecl->vbases_end();
7349 Base != BaseEnd; ++Base) {
7350 CXXRecordDecl *BaseClassDecl
7351 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7352 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7353 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007354 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007355 }
7356
Douglas Gregorb87786f2010-07-01 17:48:08 +00007357 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7358 FieldEnd = ClassDecl->field_end();
7359 Field != FieldEnd;
7360 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007361 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007362 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7363 if (CXXMethodDecl *CopyAssign =
7364 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007365 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007366 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007367 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007368
Sean Hunt30de05c2011-05-14 05:23:20 +00007369 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7370}
7371
7372CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7373 // Note: The following rules are largely analoguous to the copy
7374 // constructor rules. Note that virtual bases are not taken into account
7375 // for determining the argument type of the operator. Note also that
7376 // operators taking an object instead of a reference are allowed.
7377
Richard Smithe6975e92012-04-17 00:58:00 +00007378 ImplicitExceptionSpecification Spec(*this);
Sean Hunt30de05c2011-05-14 05:23:20 +00007379 bool Const;
7380 llvm::tie(Spec, Const) =
7381 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7382
7383 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7384 QualType RetType = Context.getLValueReferenceType(ArgType);
7385 if (Const)
7386 ArgType = ArgType.withConst();
7387 ArgType = Context.getLValueReferenceType(ArgType);
7388
Douglas Gregord3c35902010-07-01 16:36:15 +00007389 // An implicitly-declared copy assignment operator is an inline public
7390 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007391 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007392 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007393 SourceLocation ClassLoc = ClassDecl->getLocation();
7394 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007395 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007396 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007397 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007398 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007399 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007400 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007401 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007402 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007403 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007404 CopyAssignment->setImplicit();
7405 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007406
7407 // Add the parameter to the operator.
7408 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007409 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007410 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007411 SC_None,
7412 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007413 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007414
Douglas Gregora376d102010-07-02 21:50:04 +00007415 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007416 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007417
Douglas Gregor23c94db2010-07-02 17:43:08 +00007418 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007419 PushOnScopeChains(CopyAssignment, S, false);
7420 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007421
Nico Weberafcc96a2012-01-23 03:19:29 +00007422 // C++0x [class.copy]p19:
7423 // .... If the class definition does not explicitly declare a copy
7424 // assignment operator, there is no user-declared move constructor, and
7425 // there is no user-declared move assignment operator, a copy assignment
7426 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007427 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007428 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007429
Douglas Gregord3c35902010-07-01 16:36:15 +00007430 AddOverriddenMethods(ClassDecl, CopyAssignment);
7431 return CopyAssignment;
7432}
7433
Douglas Gregor06a9f362010-05-01 20:49:11 +00007434void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7435 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007436 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007437 CopyAssignOperator->isOverloadedOperator() &&
7438 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007439 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7440 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007441 "DefineImplicitCopyAssignment called for wrong function");
7442
7443 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7444
7445 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7446 CopyAssignOperator->setInvalidDecl();
7447 return;
7448 }
7449
7450 CopyAssignOperator->setUsed();
7451
7452 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007453 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007454
7455 // C++0x [class.copy]p30:
7456 // The implicitly-defined or explicitly-defaulted copy assignment operator
7457 // for a non-union class X performs memberwise copy assignment of its
7458 // subobjects. The direct base classes of X are assigned first, in the
7459 // order of their declaration in the base-specifier-list, and then the
7460 // immediate non-static data members of X are assigned, in the order in
7461 // which they were declared in the class definition.
7462
7463 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007464 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007465
7466 // The parameter for the "other" object, which we are copying from.
7467 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7468 Qualifiers OtherQuals = Other->getType().getQualifiers();
7469 QualType OtherRefType = Other->getType();
7470 if (const LValueReferenceType *OtherRef
7471 = OtherRefType->getAs<LValueReferenceType>()) {
7472 OtherRefType = OtherRef->getPointeeType();
7473 OtherQuals = OtherRefType.getQualifiers();
7474 }
7475
7476 // Our location for everything implicitly-generated.
7477 SourceLocation Loc = CopyAssignOperator->getLocation();
7478
7479 // Construct a reference to the "other" object. We'll be using this
7480 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007481 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007482 assert(OtherRef && "Reference to parameter cannot fail!");
7483
7484 // Construct the "this" pointer. We'll be using this throughout the generated
7485 // ASTs.
7486 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7487 assert(This && "Reference to this cannot fail!");
7488
7489 // Assign base classes.
7490 bool Invalid = false;
7491 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7492 E = ClassDecl->bases_end(); Base != E; ++Base) {
7493 // Form the assignment:
7494 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7495 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007496 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007497 Invalid = true;
7498 continue;
7499 }
7500
John McCallf871d0c2010-08-07 06:22:56 +00007501 CXXCastPath BasePath;
7502 BasePath.push_back(Base);
7503
Douglas Gregor06a9f362010-05-01 20:49:11 +00007504 // Construct the "from" expression, which is an implicit cast to the
7505 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007506 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007507 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7508 CK_UncheckedDerivedToBase,
7509 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007510
7511 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007512 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007513
7514 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007515 To = ImpCastExprToType(To.take(),
7516 Context.getCVRQualifiedType(BaseType,
7517 CopyAssignOperator->getTypeQualifiers()),
7518 CK_UncheckedDerivedToBase,
7519 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007520
7521 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007522 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007523 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524 /*CopyingBaseSubobject=*/true,
7525 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007526 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007527 Diag(CurrentLocation, diag::note_member_synthesized_at)
7528 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7529 CopyAssignOperator->setInvalidDecl();
7530 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007531 }
7532
7533 // Success! Record the copy.
7534 Statements.push_back(Copy.takeAs<Expr>());
7535 }
7536
7537 // \brief Reference to the __builtin_memcpy function.
7538 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007539 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007540 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007541
7542 // Assign non-static members.
7543 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7544 FieldEnd = ClassDecl->field_end();
7545 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007546 if (Field->isUnnamedBitfield())
7547 continue;
7548
Douglas Gregor06a9f362010-05-01 20:49:11 +00007549 // Check for members of reference type; we can't copy those.
7550 if (Field->getType()->isReferenceType()) {
7551 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7552 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7553 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007554 Diag(CurrentLocation, diag::note_member_synthesized_at)
7555 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007556 Invalid = true;
7557 continue;
7558 }
7559
7560 // Check for members of const-qualified, non-class type.
7561 QualType BaseType = Context.getBaseElementType(Field->getType());
7562 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7563 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7564 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7565 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007566 Diag(CurrentLocation, diag::note_member_synthesized_at)
7567 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007568 Invalid = true;
7569 continue;
7570 }
John McCallb77115d2011-06-17 00:18:42 +00007571
7572 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007573 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7574 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007575
7576 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007577 if (FieldType->isIncompleteArrayType()) {
7578 assert(ClassDecl->hasFlexibleArrayMember() &&
7579 "Incomplete array type is not valid");
7580 continue;
7581 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007582
7583 // Build references to the field in the object we're copying from and to.
7584 CXXScopeSpec SS; // Intentionally empty
7585 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7586 LookupMemberName);
David Blaikie262bc182012-04-30 02:36:29 +00007587 MemberLookup.addDecl(&*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007588 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007589 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007590 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007591 SS, SourceLocation(), 0,
7592 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007593 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007594 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007595 SS, SourceLocation(), 0,
7596 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007597 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7598 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7599
7600 // If the field should be copied with __builtin_memcpy rather than via
7601 // explicit assignments, do so. This optimization only applies for arrays
7602 // of scalars and arrays of class type with trivial copy-assignment
7603 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007604 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007605 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007606 // Compute the size of the memory buffer to be copied.
7607 QualType SizeType = Context.getSizeType();
7608 llvm::APInt Size(Context.getTypeSize(SizeType),
7609 Context.getTypeSizeInChars(BaseType).getQuantity());
7610 for (const ConstantArrayType *Array
7611 = Context.getAsConstantArrayType(FieldType);
7612 Array;
7613 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007614 llvm::APInt ArraySize
7615 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616 Size *= ArraySize;
7617 }
7618
7619 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007620 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7621 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007622
7623 bool NeedsCollectableMemCpy =
7624 (BaseType->isRecordType() &&
7625 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7626
7627 if (NeedsCollectableMemCpy) {
7628 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007629 // Create a reference to the __builtin_objc_memmove_collectable function.
7630 LookupResult R(*this,
7631 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007632 Loc, LookupOrdinaryName);
7633 LookupName(R, TUScope, true);
7634
7635 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7636 if (!CollectableMemCpy) {
7637 // Something went horribly wrong earlier, and we will have
7638 // complained about it.
7639 Invalid = true;
7640 continue;
7641 }
7642
7643 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7644 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007645 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007646 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7647 }
7648 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007649 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007650 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007651 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7652 LookupOrdinaryName);
7653 LookupName(R, TUScope, true);
7654
7655 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7656 if (!BuiltinMemCpy) {
7657 // Something went horribly wrong earlier, and we will have complained
7658 // about it.
7659 Invalid = true;
7660 continue;
7661 }
7662
7663 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7664 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007665 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007666 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7667 }
7668
John McCallca0408f2010-08-23 06:44:23 +00007669 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007670 CallArgs.push_back(To.takeAs<Expr>());
7671 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007672 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007673 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007674 if (NeedsCollectableMemCpy)
7675 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007676 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007677 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007678 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007679 else
7680 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007681 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007682 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007683 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007684
Douglas Gregor06a9f362010-05-01 20:49:11 +00007685 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7686 Statements.push_back(Call.takeAs<Expr>());
7687 continue;
7688 }
7689
7690 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007691 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007692 To.get(), From.get(),
7693 /*CopyingBaseSubobject=*/false,
7694 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007695 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007696 Diag(CurrentLocation, diag::note_member_synthesized_at)
7697 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7698 CopyAssignOperator->setInvalidDecl();
7699 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007700 }
7701
7702 // Success! Record the copy.
7703 Statements.push_back(Copy.takeAs<Stmt>());
7704 }
7705
7706 if (!Invalid) {
7707 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007708 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709
John McCall60d7b3a2010-08-24 06:29:42 +00007710 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007711 if (Return.isInvalid())
7712 Invalid = true;
7713 else {
7714 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007715
7716 if (Trap.hasErrorOccurred()) {
7717 Diag(CurrentLocation, diag::note_member_synthesized_at)
7718 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7719 Invalid = true;
7720 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007721 }
7722 }
7723
7724 if (Invalid) {
7725 CopyAssignOperator->setInvalidDecl();
7726 return;
7727 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007728
7729 StmtResult Body;
7730 {
7731 CompoundScopeRAII CompoundScope(*this);
7732 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7733 /*isStmtExpr=*/false);
7734 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7735 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007736 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007737
7738 if (ASTMutationListener *L = getASTMutationListener()) {
7739 L->CompletedImplicitDefinition(CopyAssignOperator);
7740 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007741}
7742
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007743Sema::ImplicitExceptionSpecification
7744Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
Richard Smithe6975e92012-04-17 00:58:00 +00007745 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007746
7747 if (ClassDecl->isInvalidDecl())
7748 return ExceptSpec;
7749
7750 // C++0x [except.spec]p14:
7751 // An implicitly declared special member function (Clause 12) shall have an
7752 // exception-specification. [...]
7753
7754 // It is unspecified whether or not an implicit move assignment operator
7755 // attempts to deduplicate calls to assignment operators of virtual bases are
7756 // made. As such, this exception specification is effectively unspecified.
7757 // Based on a similar decision made for constness in C++0x, we're erring on
7758 // the side of assuming such calls to be made regardless of whether they
7759 // actually happen.
7760 // Note that a move constructor is not implicitly declared when there are
7761 // virtual bases, but it can still be user-declared and explicitly defaulted.
7762 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7763 BaseEnd = ClassDecl->bases_end();
7764 Base != BaseEnd; ++Base) {
7765 if (Base->isVirtual())
7766 continue;
7767
7768 CXXRecordDecl *BaseClassDecl
7769 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7770 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7771 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007772 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007773 }
7774
7775 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7776 BaseEnd = ClassDecl->vbases_end();
7777 Base != BaseEnd; ++Base) {
7778 CXXRecordDecl *BaseClassDecl
7779 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7780 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7781 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007782 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007783 }
7784
7785 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7786 FieldEnd = ClassDecl->field_end();
7787 Field != FieldEnd;
7788 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007789 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007790 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7791 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7792 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007793 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007794 }
7795 }
7796
7797 return ExceptSpec;
7798}
7799
Richard Smith1c931be2012-04-02 18:40:40 +00007800/// Determine whether the class type has any direct or indirect virtual base
7801/// classes which have a non-trivial move assignment operator.
7802static bool
7803hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
7804 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7805 BaseEnd = ClassDecl->vbases_end();
7806 Base != BaseEnd; ++Base) {
7807 CXXRecordDecl *BaseClass =
7808 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7809
7810 // Try to declare the move assignment. If it would be deleted, then the
7811 // class does not have a non-trivial move assignment.
7812 if (BaseClass->needsImplicitMoveAssignment())
7813 S.DeclareImplicitMoveAssignment(BaseClass);
7814
7815 // If the class has both a trivial move assignment and a non-trivial move
7816 // assignment, hasTrivialMoveAssignment() is false.
7817 if (BaseClass->hasDeclaredMoveAssignment() &&
7818 !BaseClass->hasTrivialMoveAssignment())
7819 return true;
7820 }
7821
7822 return false;
7823}
7824
7825/// Determine whether the given type either has a move constructor or is
7826/// trivially copyable.
7827static bool
7828hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
7829 Type = S.Context.getBaseElementType(Type);
7830
7831 // FIXME: Technically, non-trivially-copyable non-class types, such as
7832 // reference types, are supposed to return false here, but that appears
7833 // to be a standard defect.
7834 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00007835 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00007836 return true;
7837
7838 if (Type.isTriviallyCopyableType(S.Context))
7839 return true;
7840
7841 if (IsConstructor) {
7842 if (ClassDecl->needsImplicitMoveConstructor())
7843 S.DeclareImplicitMoveConstructor(ClassDecl);
7844 return ClassDecl->hasDeclaredMoveConstructor();
7845 }
7846
7847 if (ClassDecl->needsImplicitMoveAssignment())
7848 S.DeclareImplicitMoveAssignment(ClassDecl);
7849 return ClassDecl->hasDeclaredMoveAssignment();
7850}
7851
7852/// Determine whether all non-static data members and direct or virtual bases
7853/// of class \p ClassDecl have either a move operation, or are trivially
7854/// copyable.
7855static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
7856 bool IsConstructor) {
7857 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7858 BaseEnd = ClassDecl->bases_end();
7859 Base != BaseEnd; ++Base) {
7860 if (Base->isVirtual())
7861 continue;
7862
7863 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
7864 return false;
7865 }
7866
7867 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7868 BaseEnd = ClassDecl->vbases_end();
7869 Base != BaseEnd; ++Base) {
7870 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
7871 return false;
7872 }
7873
7874 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7875 FieldEnd = ClassDecl->field_end();
7876 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007877 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00007878 return false;
7879 }
7880
7881 return true;
7882}
7883
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007884CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00007885 // C++11 [class.copy]p20:
7886 // If the definition of a class X does not explicitly declare a move
7887 // assignment operator, one will be implicitly declared as defaulted
7888 // if and only if:
7889 //
7890 // - [first 4 bullets]
7891 assert(ClassDecl->needsImplicitMoveAssignment());
7892
7893 // [Checked after we build the declaration]
7894 // - the move assignment operator would not be implicitly defined as
7895 // deleted,
7896
7897 // [DR1402]:
7898 // - X has no direct or indirect virtual base class with a non-trivial
7899 // move assignment operator, and
7900 // - each of X's non-static data members and direct or virtual base classes
7901 // has a type that either has a move assignment operator or is trivially
7902 // copyable.
7903 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
7904 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
7905 ClassDecl->setFailedImplicitMoveAssignment();
7906 return 0;
7907 }
7908
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007909 // Note: The following rules are largely analoguous to the move
7910 // constructor rules.
7911
7912 ImplicitExceptionSpecification Spec(
7913 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7914
7915 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7916 QualType RetType = Context.getLValueReferenceType(ArgType);
7917 ArgType = Context.getRValueReferenceType(ArgType);
7918
7919 // An implicitly-declared move assignment operator is an inline public
7920 // member of its class.
7921 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7922 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7923 SourceLocation ClassLoc = ClassDecl->getLocation();
7924 DeclarationNameInfo NameInfo(Name, ClassLoc);
7925 CXXMethodDecl *MoveAssignment
7926 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7927 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7928 /*TInfo=*/0, /*isStatic=*/false,
7929 /*StorageClassAsWritten=*/SC_None,
7930 /*isInline=*/true,
7931 /*isConstexpr=*/false,
7932 SourceLocation());
7933 MoveAssignment->setAccess(AS_public);
7934 MoveAssignment->setDefaulted();
7935 MoveAssignment->setImplicit();
7936 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7937
7938 // Add the parameter to the operator.
7939 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7940 ClassLoc, ClassLoc, /*Id=*/0,
7941 ArgType, /*TInfo=*/0,
7942 SC_None,
7943 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007944 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007945
7946 // Note that we have added this copy-assignment operator.
7947 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7948
7949 // C++0x [class.copy]p9:
7950 // If the definition of a class X does not explicitly declare a move
7951 // assignment operator, one will be implicitly declared as defaulted if and
7952 // only if:
7953 // [...]
7954 // - the move assignment operator would not be implicitly defined as
7955 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00007956 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007957 // Cache this result so that we don't try to generate this over and over
7958 // on every lookup, leaking memory and wasting time.
7959 ClassDecl->setFailedImplicitMoveAssignment();
7960 return 0;
7961 }
7962
7963 if (Scope *S = getScopeForContext(ClassDecl))
7964 PushOnScopeChains(MoveAssignment, S, false);
7965 ClassDecl->addDecl(MoveAssignment);
7966
7967 AddOverriddenMethods(ClassDecl, MoveAssignment);
7968 return MoveAssignment;
7969}
7970
7971void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7972 CXXMethodDecl *MoveAssignOperator) {
7973 assert((MoveAssignOperator->isDefaulted() &&
7974 MoveAssignOperator->isOverloadedOperator() &&
7975 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007976 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
7977 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007978 "DefineImplicitMoveAssignment called for wrong function");
7979
7980 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7981
7982 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7983 MoveAssignOperator->setInvalidDecl();
7984 return;
7985 }
7986
7987 MoveAssignOperator->setUsed();
7988
7989 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7990 DiagnosticErrorTrap Trap(Diags);
7991
7992 // C++0x [class.copy]p28:
7993 // The implicitly-defined or move assignment operator for a non-union class
7994 // X performs memberwise move assignment of its subobjects. The direct base
7995 // classes of X are assigned first, in the order of their declaration in the
7996 // base-specifier-list, and then the immediate non-static data members of X
7997 // are assigned, in the order in which they were declared in the class
7998 // definition.
7999
8000 // The statements that form the synthesized function body.
8001 ASTOwningVector<Stmt*> Statements(*this);
8002
8003 // The parameter for the "other" object, which we are move from.
8004 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8005 QualType OtherRefType = Other->getType()->
8006 getAs<RValueReferenceType>()->getPointeeType();
8007 assert(OtherRefType.getQualifiers() == 0 &&
8008 "Bad argument type of defaulted move assignment");
8009
8010 // Our location for everything implicitly-generated.
8011 SourceLocation Loc = MoveAssignOperator->getLocation();
8012
8013 // Construct a reference to the "other" object. We'll be using this
8014 // throughout the generated ASTs.
8015 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8016 assert(OtherRef && "Reference to parameter cannot fail!");
8017 // Cast to rvalue.
8018 OtherRef = CastForMoving(*this, OtherRef);
8019
8020 // Construct the "this" pointer. We'll be using this throughout the generated
8021 // ASTs.
8022 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8023 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008024
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008025 // Assign base classes.
8026 bool Invalid = false;
8027 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8028 E = ClassDecl->bases_end(); Base != E; ++Base) {
8029 // Form the assignment:
8030 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8031 QualType BaseType = Base->getType().getUnqualifiedType();
8032 if (!BaseType->isRecordType()) {
8033 Invalid = true;
8034 continue;
8035 }
8036
8037 CXXCastPath BasePath;
8038 BasePath.push_back(Base);
8039
8040 // Construct the "from" expression, which is an implicit cast to the
8041 // appropriately-qualified base type.
8042 Expr *From = OtherRef;
8043 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008044 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008045
8046 // Dereference "this".
8047 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8048
8049 // Implicitly cast "this" to the appropriately-qualified base type.
8050 To = ImpCastExprToType(To.take(),
8051 Context.getCVRQualifiedType(BaseType,
8052 MoveAssignOperator->getTypeQualifiers()),
8053 CK_UncheckedDerivedToBase,
8054 VK_LValue, &BasePath);
8055
8056 // Build the move.
8057 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8058 To.get(), From,
8059 /*CopyingBaseSubobject=*/true,
8060 /*Copying=*/false);
8061 if (Move.isInvalid()) {
8062 Diag(CurrentLocation, diag::note_member_synthesized_at)
8063 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8064 MoveAssignOperator->setInvalidDecl();
8065 return;
8066 }
8067
8068 // Success! Record the move.
8069 Statements.push_back(Move.takeAs<Expr>());
8070 }
8071
8072 // \brief Reference to the __builtin_memcpy function.
8073 Expr *BuiltinMemCpyRef = 0;
8074 // \brief Reference to the __builtin_objc_memmove_collectable function.
8075 Expr *CollectableMemCpyRef = 0;
8076
8077 // Assign non-static members.
8078 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8079 FieldEnd = ClassDecl->field_end();
8080 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008081 if (Field->isUnnamedBitfield())
8082 continue;
8083
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008084 // Check for members of reference type; we can't move those.
8085 if (Field->getType()->isReferenceType()) {
8086 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8087 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8088 Diag(Field->getLocation(), diag::note_declared_at);
8089 Diag(CurrentLocation, diag::note_member_synthesized_at)
8090 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8091 Invalid = true;
8092 continue;
8093 }
8094
8095 // Check for members of const-qualified, non-class type.
8096 QualType BaseType = Context.getBaseElementType(Field->getType());
8097 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8098 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8099 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8100 Diag(Field->getLocation(), diag::note_declared_at);
8101 Diag(CurrentLocation, diag::note_member_synthesized_at)
8102 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8103 Invalid = true;
8104 continue;
8105 }
8106
8107 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008108 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8109 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008110
8111 QualType FieldType = Field->getType().getNonReferenceType();
8112 if (FieldType->isIncompleteArrayType()) {
8113 assert(ClassDecl->hasFlexibleArrayMember() &&
8114 "Incomplete array type is not valid");
8115 continue;
8116 }
8117
8118 // Build references to the field in the object we're copying from and to.
8119 CXXScopeSpec SS; // Intentionally empty
8120 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8121 LookupMemberName);
David Blaikie262bc182012-04-30 02:36:29 +00008122 MemberLookup.addDecl(&*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008123 MemberLookup.resolveKind();
8124 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8125 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008126 SS, SourceLocation(), 0,
8127 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008128 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8129 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008130 SS, SourceLocation(), 0,
8131 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008132 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8133 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8134
8135 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8136 "Member reference with rvalue base must be rvalue except for reference "
8137 "members, which aren't allowed for move assignment.");
8138
8139 // If the field should be copied with __builtin_memcpy rather than via
8140 // explicit assignments, do so. This optimization only applies for arrays
8141 // of scalars and arrays of class type with trivial move-assignment
8142 // operators.
8143 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8144 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8145 // Compute the size of the memory buffer to be copied.
8146 QualType SizeType = Context.getSizeType();
8147 llvm::APInt Size(Context.getTypeSize(SizeType),
8148 Context.getTypeSizeInChars(BaseType).getQuantity());
8149 for (const ConstantArrayType *Array
8150 = Context.getAsConstantArrayType(FieldType);
8151 Array;
8152 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8153 llvm::APInt ArraySize
8154 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8155 Size *= ArraySize;
8156 }
8157
Douglas Gregor45d3d712011-09-01 02:09:07 +00008158 // Take the address of the field references for "from" and "to". We
8159 // directly construct UnaryOperators here because semantic analysis
8160 // does not permit us to take the address of an xvalue.
8161 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8162 Context.getPointerType(From.get()->getType()),
8163 VK_RValue, OK_Ordinary, Loc);
8164 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8165 Context.getPointerType(To.get()->getType()),
8166 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008167
8168 bool NeedsCollectableMemCpy =
8169 (BaseType->isRecordType() &&
8170 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8171
8172 if (NeedsCollectableMemCpy) {
8173 if (!CollectableMemCpyRef) {
8174 // Create a reference to the __builtin_objc_memmove_collectable function.
8175 LookupResult R(*this,
8176 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8177 Loc, LookupOrdinaryName);
8178 LookupName(R, TUScope, true);
8179
8180 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8181 if (!CollectableMemCpy) {
8182 // Something went horribly wrong earlier, and we will have
8183 // complained about it.
8184 Invalid = true;
8185 continue;
8186 }
8187
8188 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8189 CollectableMemCpy->getType(),
8190 VK_LValue, Loc, 0).take();
8191 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8192 }
8193 }
8194 // Create a reference to the __builtin_memcpy builtin function.
8195 else if (!BuiltinMemCpyRef) {
8196 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8197 LookupOrdinaryName);
8198 LookupName(R, TUScope, true);
8199
8200 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8201 if (!BuiltinMemCpy) {
8202 // Something went horribly wrong earlier, and we will have complained
8203 // about it.
8204 Invalid = true;
8205 continue;
8206 }
8207
8208 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8209 BuiltinMemCpy->getType(),
8210 VK_LValue, Loc, 0).take();
8211 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8212 }
8213
8214 ASTOwningVector<Expr*> CallArgs(*this);
8215 CallArgs.push_back(To.takeAs<Expr>());
8216 CallArgs.push_back(From.takeAs<Expr>());
8217 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8218 ExprResult Call = ExprError();
8219 if (NeedsCollectableMemCpy)
8220 Call = ActOnCallExpr(/*Scope=*/0,
8221 CollectableMemCpyRef,
8222 Loc, move_arg(CallArgs),
8223 Loc);
8224 else
8225 Call = ActOnCallExpr(/*Scope=*/0,
8226 BuiltinMemCpyRef,
8227 Loc, move_arg(CallArgs),
8228 Loc);
8229
8230 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8231 Statements.push_back(Call.takeAs<Expr>());
8232 continue;
8233 }
8234
8235 // Build the move of this field.
8236 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8237 To.get(), From.get(),
8238 /*CopyingBaseSubobject=*/false,
8239 /*Copying=*/false);
8240 if (Move.isInvalid()) {
8241 Diag(CurrentLocation, diag::note_member_synthesized_at)
8242 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8243 MoveAssignOperator->setInvalidDecl();
8244 return;
8245 }
8246
8247 // Success! Record the copy.
8248 Statements.push_back(Move.takeAs<Stmt>());
8249 }
8250
8251 if (!Invalid) {
8252 // Add a "return *this;"
8253 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8254
8255 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8256 if (Return.isInvalid())
8257 Invalid = true;
8258 else {
8259 Statements.push_back(Return.takeAs<Stmt>());
8260
8261 if (Trap.hasErrorOccurred()) {
8262 Diag(CurrentLocation, diag::note_member_synthesized_at)
8263 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8264 Invalid = true;
8265 }
8266 }
8267 }
8268
8269 if (Invalid) {
8270 MoveAssignOperator->setInvalidDecl();
8271 return;
8272 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008273
8274 StmtResult Body;
8275 {
8276 CompoundScopeRAII CompoundScope(*this);
8277 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8278 /*isStmtExpr=*/false);
8279 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8280 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008281 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8282
8283 if (ASTMutationListener *L = getASTMutationListener()) {
8284 L->CompletedImplicitDefinition(MoveAssignOperator);
8285 }
8286}
8287
Sean Hunt49634cf2011-05-13 06:10:58 +00008288std::pair<Sema::ImplicitExceptionSpecification, bool>
8289Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008290 if (ClassDecl->isInvalidDecl())
Richard Smith3003e1d2012-05-15 04:39:51 +00008291 return std::make_pair(ImplicitExceptionSpecification(*this), true);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008292
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008293 // C++ [class.copy]p5:
8294 // The implicitly-declared copy constructor for a class X will
8295 // have the form
8296 //
8297 // X::X(const X&)
8298 //
8299 // if
Sean Huntc530d172011-06-10 04:44:37 +00008300 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008301 bool HasConstCopyConstructor = true;
8302
8303 // -- each direct or virtual base class B of X has a copy
8304 // constructor whose first parameter is of type const B& or
8305 // const volatile B&, and
8306 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8307 BaseEnd = ClassDecl->bases_end();
8308 HasConstCopyConstructor && Base != BaseEnd;
8309 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008310 // Virtual bases are handled below.
8311 if (Base->isVirtual())
8312 continue;
8313
Douglas Gregor22584312010-07-02 23:41:54 +00008314 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008315 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008316 HasConstCopyConstructor &=
8317 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor598a8542010-07-01 18:27:03 +00008318 }
8319
8320 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8321 BaseEnd = ClassDecl->vbases_end();
8322 HasConstCopyConstructor && Base != BaseEnd;
8323 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008324 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008325 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smith704c8f72012-04-20 18:46:14 +00008326 HasConstCopyConstructor &=
8327 (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008328 }
8329
8330 // -- for all the nonstatic data members of X that are of a
8331 // class type M (or array thereof), each such class type
8332 // has a copy constructor whose first parameter is of type
8333 // const M& or const volatile M&.
8334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8335 FieldEnd = ClassDecl->field_end();
8336 HasConstCopyConstructor && Field != FieldEnd;
8337 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008338 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008339 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith704c8f72012-04-20 18:46:14 +00008340 HasConstCopyConstructor &=
8341 (bool)LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008342 }
8343 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008344 // Otherwise, the implicitly declared copy constructor will have
8345 // the form
8346 //
8347 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008348
Douglas Gregor0d405db2010-07-01 20:59:04 +00008349 // C++ [except.spec]p14:
8350 // An implicitly declared special member function (Clause 12) shall have an
8351 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008352 ImplicitExceptionSpecification ExceptSpec(*this);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008353 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8354 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8355 BaseEnd = ClassDecl->bases_end();
8356 Base != BaseEnd;
8357 ++Base) {
8358 // Virtual bases are handled below.
8359 if (Base->isVirtual())
8360 continue;
8361
Douglas Gregor22584312010-07-02 23:41:54 +00008362 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008363 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008364 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008365 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008366 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008367 }
8368 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8369 BaseEnd = ClassDecl->vbases_end();
8370 Base != BaseEnd;
8371 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008372 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008373 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008374 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008375 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008376 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008377 }
8378 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8379 FieldEnd = ClassDecl->field_end();
8380 Field != FieldEnd;
8381 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008382 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008383 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8384 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008385 LookupCopyingConstructor(FieldClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008386 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008387 }
8388 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008389
Sean Hunt49634cf2011-05-13 06:10:58 +00008390 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8391}
8392
8393CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8394 CXXRecordDecl *ClassDecl) {
8395 // C++ [class.copy]p4:
8396 // If the class definition does not explicitly declare a copy
8397 // constructor, one is declared implicitly.
8398
Richard Smithe6975e92012-04-17 00:58:00 +00008399 ImplicitExceptionSpecification Spec(*this);
Sean Hunt49634cf2011-05-13 06:10:58 +00008400 bool Const;
8401 llvm::tie(Spec, Const) =
8402 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8403
8404 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8405 QualType ArgType = ClassType;
8406 if (Const)
8407 ArgType = ArgType.withConst();
8408 ArgType = Context.getLValueReferenceType(ArgType);
8409
8410 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8411
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008412 DeclarationName Name
8413 = Context.DeclarationNames.getCXXConstructorName(
8414 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008415 SourceLocation ClassLoc = ClassDecl->getLocation();
8416 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008417
8418 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008419 // member of its class.
8420 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8421 Context, ClassDecl, ClassLoc, NameInfo,
8422 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8423 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8424 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008425 getLangOpts().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008426 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008427 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008428 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008429
Douglas Gregor22584312010-07-02 23:41:54 +00008430 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008431 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8432
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008433 // Add the parameter to the constructor.
8434 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008435 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008436 /*IdentifierInfo=*/0,
8437 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008438 SC_None,
8439 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008440 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008441
Douglas Gregor23c94db2010-07-02 17:43:08 +00008442 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008443 PushOnScopeChains(CopyConstructor, S, false);
8444 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008445
Nico Weberafcc96a2012-01-23 03:19:29 +00008446 // C++11 [class.copy]p8:
8447 // ... If the class definition does not explicitly declare a copy
8448 // constructor, there is no user-declared move constructor, and there is no
8449 // user-declared move assignment operator, a copy constructor is implicitly
8450 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008451 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008452 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008453
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008454 return CopyConstructor;
8455}
8456
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008457void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008458 CXXConstructorDecl *CopyConstructor) {
8459 assert((CopyConstructor->isDefaulted() &&
8460 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008461 !CopyConstructor->doesThisDeclarationHaveABody() &&
8462 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008463 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008464
Anders Carlsson63010a72010-04-23 16:24:12 +00008465 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008466 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008467
Douglas Gregor39957dc2010-05-01 15:04:51 +00008468 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008469 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008470
Sean Huntcbb67482011-01-08 20:30:50 +00008471 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008472 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008473 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008474 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008475 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008476 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008477 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008478 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8479 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008480 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008481 /*isStmtExpr=*/false)
8482 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008483 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008484 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008485
8486 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008487 if (ASTMutationListener *L = getASTMutationListener()) {
8488 L->CompletedImplicitDefinition(CopyConstructor);
8489 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008490}
8491
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008492Sema::ImplicitExceptionSpecification
8493Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8494 // C++ [except.spec]p14:
8495 // An implicitly declared special member function (Clause 12) shall have an
8496 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008497 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008498 if (ClassDecl->isInvalidDecl())
8499 return ExceptSpec;
8500
8501 // Direct base-class constructors.
8502 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8503 BEnd = ClassDecl->bases_end();
8504 B != BEnd; ++B) {
8505 if (B->isVirtual()) // Handled below.
8506 continue;
8507
8508 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8509 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8510 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8511 // If this is a deleted function, add it anyway. This might be conformant
8512 // with the standard. This might not. I'm not sure. It might not matter.
8513 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008514 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008515 }
8516 }
8517
8518 // Virtual base-class constructors.
8519 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8520 BEnd = ClassDecl->vbases_end();
8521 B != BEnd; ++B) {
8522 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8523 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8524 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8525 // If this is a deleted function, add it anyway. This might be conformant
8526 // with the standard. This might not. I'm not sure. It might not matter.
8527 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008528 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008529 }
8530 }
8531
8532 // Field constructors.
8533 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8534 FEnd = ClassDecl->field_end();
8535 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008536 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008537 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8538 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8539 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8540 // If this is a deleted function, add it anyway. This might be conformant
8541 // with the standard. This might not. I'm not sure. It might not matter.
8542 // In particular, the problem is that this function never gets called. It
8543 // might just be ill-formed because this function attempts to refer to
8544 // a deleted function here.
8545 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008546 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008547 }
8548 }
8549
8550 return ExceptSpec;
8551}
8552
8553CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8554 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008555 // C++11 [class.copy]p9:
8556 // If the definition of a class X does not explicitly declare a move
8557 // constructor, one will be implicitly declared as defaulted if and only if:
8558 //
8559 // - [first 4 bullets]
8560 assert(ClassDecl->needsImplicitMoveConstructor());
8561
8562 // [Checked after we build the declaration]
8563 // - the move assignment operator would not be implicitly defined as
8564 // deleted,
8565
8566 // [DR1402]:
8567 // - each of X's non-static data members and direct or virtual base classes
8568 // has a type that either has a move constructor or is trivially copyable.
8569 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8570 ClassDecl->setFailedImplicitMoveConstructor();
8571 return 0;
8572 }
8573
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008574 ImplicitExceptionSpecification Spec(
8575 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8576
8577 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8578 QualType ArgType = Context.getRValueReferenceType(ClassType);
8579
8580 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8581
8582 DeclarationName Name
8583 = Context.DeclarationNames.getCXXConstructorName(
8584 Context.getCanonicalType(ClassType));
8585 SourceLocation ClassLoc = ClassDecl->getLocation();
8586 DeclarationNameInfo NameInfo(Name, ClassLoc);
8587
8588 // C++0x [class.copy]p11:
8589 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008590 // member of its class.
8591 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8592 Context, ClassDecl, ClassLoc, NameInfo,
8593 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8594 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8595 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008596 getLangOpts().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008597 MoveConstructor->setAccess(AS_public);
8598 MoveConstructor->setDefaulted();
8599 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008600
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008601 // Add the parameter to the constructor.
8602 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8603 ClassLoc, ClassLoc,
8604 /*IdentifierInfo=*/0,
8605 ArgType, /*TInfo=*/0,
8606 SC_None,
8607 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008608 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008609
8610 // C++0x [class.copy]p9:
8611 // If the definition of a class X does not explicitly declare a move
8612 // constructor, one will be implicitly declared as defaulted if and only if:
8613 // [...]
8614 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008615 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008616 // Cache this result so that we don't try to generate this over and over
8617 // on every lookup, leaking memory and wasting time.
8618 ClassDecl->setFailedImplicitMoveConstructor();
8619 return 0;
8620 }
8621
8622 // Note that we have declared this constructor.
8623 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8624
8625 if (Scope *S = getScopeForContext(ClassDecl))
8626 PushOnScopeChains(MoveConstructor, S, false);
8627 ClassDecl->addDecl(MoveConstructor);
8628
8629 return MoveConstructor;
8630}
8631
8632void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8633 CXXConstructorDecl *MoveConstructor) {
8634 assert((MoveConstructor->isDefaulted() &&
8635 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008636 !MoveConstructor->doesThisDeclarationHaveABody() &&
8637 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008638 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8639
8640 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8641 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8642
8643 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8644 DiagnosticErrorTrap Trap(Diags);
8645
8646 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8647 Trap.hasErrorOccurred()) {
8648 Diag(CurrentLocation, diag::note_member_synthesized_at)
8649 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8650 MoveConstructor->setInvalidDecl();
8651 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008652 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008653 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8654 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008655 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008656 /*isStmtExpr=*/false)
8657 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008658 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008659 }
8660
8661 MoveConstructor->setUsed();
8662
8663 if (ASTMutationListener *L = getASTMutationListener()) {
8664 L->CompletedImplicitDefinition(MoveConstructor);
8665 }
8666}
8667
Douglas Gregore4e68d42012-02-15 19:33:52 +00008668bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8669 return FD->isDeleted() &&
8670 (FD->isDefaulted() || FD->isImplicit()) &&
8671 isa<CXXMethodDecl>(FD);
8672}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008673
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008674/// \brief Mark the call operator of the given lambda closure type as "used".
8675static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8676 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008677 = cast<CXXMethodDecl>(
8678 *Lambda->lookup(
8679 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008680 CallOperator->setReferenced();
8681 CallOperator->setUsed();
8682}
8683
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008684void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8685 SourceLocation CurrentLocation,
8686 CXXConversionDecl *Conv)
8687{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008688 CXXRecordDecl *Lambda = Conv->getParent();
8689
8690 // Make sure that the lambda call operator is marked used.
8691 markLambdaCallOperatorUsed(*this, Lambda);
8692
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008693 Conv->setUsed();
8694
8695 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8696 DiagnosticErrorTrap Trap(Diags);
8697
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008698 // Return the address of the __invoke function.
8699 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8700 CXXMethodDecl *Invoke
8701 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8702 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8703 VK_LValue, Conv->getLocation()).take();
8704 assert(FunctionRef && "Can't refer to __invoke function?");
8705 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8706 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8707 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008708 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008709
8710 // Fill in the __invoke function with a dummy implementation. IR generation
8711 // will fill in the actual details.
8712 Invoke->setUsed();
8713 Invoke->setReferenced();
8714 Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8715 Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008716
8717 if (ASTMutationListener *L = getASTMutationListener()) {
8718 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008719 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008720 }
8721}
8722
8723void Sema::DefineImplicitLambdaToBlockPointerConversion(
8724 SourceLocation CurrentLocation,
8725 CXXConversionDecl *Conv)
8726{
8727 Conv->setUsed();
8728
8729 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8730 DiagnosticErrorTrap Trap(Diags);
8731
Douglas Gregorac1303e2012-02-22 05:02:47 +00008732 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008733 Expr *This = ActOnCXXThis(CurrentLocation).take();
8734 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008735
Eli Friedman23f02672012-03-01 04:01:32 +00008736 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8737 Conv->getLocation(),
8738 Conv, DerefThis);
8739
8740 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8741 // behavior. Note that only the general conversion function does this
8742 // (since it's unusable otherwise); in the case where we inline the
8743 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008744 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008745 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8746 CK_CopyAndAutoreleaseBlockObject,
8747 BuildBlock.get(), 0, VK_RValue);
8748
8749 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008750 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008751 Conv->setInvalidDecl();
8752 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008753 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008754
Douglas Gregorac1303e2012-02-22 05:02:47 +00008755 // Create the return statement that returns the block from the conversion
8756 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008757 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008758 if (Return.isInvalid()) {
8759 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8760 Conv->setInvalidDecl();
8761 return;
8762 }
8763
8764 // Set the body of the conversion function.
8765 Stmt *ReturnS = Return.take();
8766 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8767 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008768 Conv->getLocation()));
8769
Douglas Gregorac1303e2012-02-22 05:02:47 +00008770 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008771 if (ASTMutationListener *L = getASTMutationListener()) {
8772 L->CompletedImplicitDefinition(Conv);
8773 }
8774}
8775
Douglas Gregorf52757d2012-03-10 06:53:13 +00008776/// \brief Determine whether the given list arguments contains exactly one
8777/// "real" (non-default) argument.
8778static bool hasOneRealArgument(MultiExprArg Args) {
8779 switch (Args.size()) {
8780 case 0:
8781 return false;
8782
8783 default:
8784 if (!Args.get()[1]->isDefaultArgument())
8785 return false;
8786
8787 // fall through
8788 case 1:
8789 return !Args.get()[0]->isDefaultArgument();
8790 }
8791
8792 return false;
8793}
8794
John McCall60d7b3a2010-08-24 06:29:42 +00008795ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008796Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008797 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008798 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008799 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008800 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008801 unsigned ConstructKind,
8802 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008803 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008804
Douglas Gregor2f599792010-04-02 18:24:57 +00008805 // C++0x [class.copy]p34:
8806 // When certain criteria are met, an implementation is allowed to
8807 // omit the copy/move construction of a class object, even if the
8808 // copy/move constructor and/or destructor for the object have
8809 // side effects. [...]
8810 // - when a temporary class object that has not been bound to a
8811 // reference (12.2) would be copied/moved to a class object
8812 // with the same cv-unqualified type, the copy/move operation
8813 // can be omitted by constructing the temporary object
8814 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008815 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00008816 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008817 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008818 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008819 }
Mike Stump1eb44332009-09-09 15:08:12 +00008820
8821 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008822 Elidable, move(ExprArgs), HadMultipleCandidates,
8823 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008824}
8825
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008826/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8827/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008828ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008829Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8830 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008831 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008832 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008833 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008834 unsigned ConstructKind,
8835 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008836 unsigned NumExprs = ExprArgs.size();
8837 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008838
Nick Lewycky909a70d2011-03-25 01:44:32 +00008839 for (specific_attr_iterator<NonNullAttr>
8840 i = Constructor->specific_attr_begin<NonNullAttr>(),
8841 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8842 const NonNullAttr *NonNull = *i;
8843 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8844 }
8845
Eli Friedman5f2987c2012-02-02 03:46:19 +00008846 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008847 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008848 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008849 HadMultipleCandidates, /*FIXME*/false,
8850 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008851 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8852 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008853}
8854
Mike Stump1eb44332009-09-09 15:08:12 +00008855bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008856 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008857 MultiExprArg Exprs,
8858 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008859 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008860 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008861 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008862 move(Exprs), HadMultipleCandidates, false,
8863 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008864 if (TempResult.isInvalid())
8865 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008866
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008867 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008868 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00008869 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008870 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008871 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008872
Anders Carlssonfe2de492009-08-25 05:18:00 +00008873 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008874}
8875
John McCall68c6c9a2010-02-02 09:10:11 +00008876void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008877 if (VD->isInvalidDecl()) return;
8878
John McCall68c6c9a2010-02-02 09:10:11 +00008879 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008880 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00008881 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008882 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008883
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008884 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00008885 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008886 CheckDestructorAccess(VD->getLocation(), Destructor,
8887 PDiag(diag::err_access_dtor_var)
8888 << VD->getDeclName()
8889 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00008890 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008891
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008892 if (!VD->hasGlobalStorage()) return;
8893
8894 // Emit warning for non-trivial dtor in global scope (a real global,
8895 // class-static, function-static).
8896 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8897
8898 // TODO: this should be re-enabled for static locals by !CXAAtExit
8899 if (!VD->isStaticLocal())
8900 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008901}
8902
Douglas Gregor39da0b82009-09-09 23:08:42 +00008903/// \brief Given a constructor and the set of arguments provided for the
8904/// constructor, convert the arguments and add any required default arguments
8905/// to form a proper call to this constructor.
8906///
8907/// \returns true if an error occurred, false otherwise.
8908bool
8909Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8910 MultiExprArg ArgsPtr,
8911 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00008912 ASTOwningVector<Expr*> &ConvertedArgs,
8913 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008914 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8915 unsigned NumArgs = ArgsPtr.size();
8916 Expr **Args = (Expr **)ArgsPtr.get();
8917
8918 const FunctionProtoType *Proto
8919 = Constructor->getType()->getAs<FunctionProtoType>();
8920 assert(Proto && "Constructor without a prototype?");
8921 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008922
8923 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008924 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008925 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008926 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008927 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008928
8929 VariadicCallType CallType =
8930 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008931 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008932 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8933 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00008934 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00008935 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00008936
8937 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
8938
8939 // FIXME: Missing call to CheckFunctionCall or equivalent
8940
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008941 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008942}
8943
Anders Carlsson20d45d22009-12-12 00:32:00 +00008944static inline bool
8945CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8946 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008947 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008948 if (isa<NamespaceDecl>(DC)) {
8949 return SemaRef.Diag(FnDecl->getLocation(),
8950 diag::err_operator_new_delete_declared_in_namespace)
8951 << FnDecl->getDeclName();
8952 }
8953
8954 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008955 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008956 return SemaRef.Diag(FnDecl->getLocation(),
8957 diag::err_operator_new_delete_declared_static)
8958 << FnDecl->getDeclName();
8959 }
8960
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008961 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008962}
8963
Anders Carlsson156c78e2009-12-13 17:53:43 +00008964static inline bool
8965CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8966 CanQualType ExpectedResultType,
8967 CanQualType ExpectedFirstParamType,
8968 unsigned DependentParamTypeDiag,
8969 unsigned InvalidParamTypeDiag) {
8970 QualType ResultType =
8971 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8972
8973 // Check that the result type is not dependent.
8974 if (ResultType->isDependentType())
8975 return SemaRef.Diag(FnDecl->getLocation(),
8976 diag::err_operator_new_delete_dependent_result_type)
8977 << FnDecl->getDeclName() << ExpectedResultType;
8978
8979 // Check that the result type is what we expect.
8980 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8981 return SemaRef.Diag(FnDecl->getLocation(),
8982 diag::err_operator_new_delete_invalid_result_type)
8983 << FnDecl->getDeclName() << ExpectedResultType;
8984
8985 // A function template must have at least 2 parameters.
8986 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8987 return SemaRef.Diag(FnDecl->getLocation(),
8988 diag::err_operator_new_delete_template_too_few_parameters)
8989 << FnDecl->getDeclName();
8990
8991 // The function decl must have at least 1 parameter.
8992 if (FnDecl->getNumParams() == 0)
8993 return SemaRef.Diag(FnDecl->getLocation(),
8994 diag::err_operator_new_delete_too_few_parameters)
8995 << FnDecl->getDeclName();
8996
8997 // Check the the first parameter type is not dependent.
8998 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8999 if (FirstParamType->isDependentType())
9000 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9001 << FnDecl->getDeclName() << ExpectedFirstParamType;
9002
9003 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009004 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009005 ExpectedFirstParamType)
9006 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9007 << FnDecl->getDeclName() << ExpectedFirstParamType;
9008
9009 return false;
9010}
9011
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009012static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009013CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009014 // C++ [basic.stc.dynamic.allocation]p1:
9015 // A program is ill-formed if an allocation function is declared in a
9016 // namespace scope other than global scope or declared static in global
9017 // scope.
9018 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9019 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009020
9021 CanQualType SizeTy =
9022 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9023
9024 // C++ [basic.stc.dynamic.allocation]p1:
9025 // The return type shall be void*. The first parameter shall have type
9026 // std::size_t.
9027 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9028 SizeTy,
9029 diag::err_operator_new_dependent_param_type,
9030 diag::err_operator_new_param_type))
9031 return true;
9032
9033 // C++ [basic.stc.dynamic.allocation]p1:
9034 // The first parameter shall not have an associated default argument.
9035 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009036 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009037 diag::err_operator_new_default_arg)
9038 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9039
9040 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009041}
9042
9043static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009044CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9045 // C++ [basic.stc.dynamic.deallocation]p1:
9046 // A program is ill-formed if deallocation functions are declared in a
9047 // namespace scope other than global scope or declared static in global
9048 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009049 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9050 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009051
9052 // C++ [basic.stc.dynamic.deallocation]p2:
9053 // Each deallocation function shall return void and its first parameter
9054 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009055 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9056 SemaRef.Context.VoidPtrTy,
9057 diag::err_operator_delete_dependent_param_type,
9058 diag::err_operator_delete_param_type))
9059 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009060
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009061 return false;
9062}
9063
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009064/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9065/// of this overloaded operator is well-formed. If so, returns false;
9066/// otherwise, emits appropriate diagnostics and returns true.
9067bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009068 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009069 "Expected an overloaded operator declaration");
9070
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009071 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9072
Mike Stump1eb44332009-09-09 15:08:12 +00009073 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009074 // The allocation and deallocation functions, operator new,
9075 // operator new[], operator delete and operator delete[], are
9076 // described completely in 3.7.3. The attributes and restrictions
9077 // found in the rest of this subclause do not apply to them unless
9078 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009079 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009080 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009081
Anders Carlssona3ccda52009-12-12 00:26:23 +00009082 if (Op == OO_New || Op == OO_Array_New)
9083 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009084
9085 // C++ [over.oper]p6:
9086 // An operator function shall either be a non-static member
9087 // function or be a non-member function and have at least one
9088 // parameter whose type is a class, a reference to a class, an
9089 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009090 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9091 if (MethodDecl->isStatic())
9092 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009093 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009094 } else {
9095 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009096 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9097 ParamEnd = FnDecl->param_end();
9098 Param != ParamEnd; ++Param) {
9099 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009100 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9101 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009102 ClassOrEnumParam = true;
9103 break;
9104 }
9105 }
9106
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009107 if (!ClassOrEnumParam)
9108 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009109 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009110 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009111 }
9112
9113 // C++ [over.oper]p8:
9114 // An operator function cannot have default arguments (8.3.6),
9115 // except where explicitly stated below.
9116 //
Mike Stump1eb44332009-09-09 15:08:12 +00009117 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009118 // (C++ [over.call]p1).
9119 if (Op != OO_Call) {
9120 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9121 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009122 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009123 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009124 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009125 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009126 }
9127 }
9128
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009129 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9130 { false, false, false }
9131#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9132 , { Unary, Binary, MemberOnly }
9133#include "clang/Basic/OperatorKinds.def"
9134 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009135
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009136 bool CanBeUnaryOperator = OperatorUses[Op][0];
9137 bool CanBeBinaryOperator = OperatorUses[Op][1];
9138 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009139
9140 // C++ [over.oper]p8:
9141 // [...] Operator functions cannot have more or fewer parameters
9142 // than the number required for the corresponding operator, as
9143 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009144 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009145 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009146 if (Op != OO_Call &&
9147 ((NumParams == 1 && !CanBeUnaryOperator) ||
9148 (NumParams == 2 && !CanBeBinaryOperator) ||
9149 (NumParams < 1) || (NumParams > 2))) {
9150 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009151 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009152 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009153 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009154 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009155 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009156 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009157 assert(CanBeBinaryOperator &&
9158 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009159 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009160 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009161
Chris Lattner416e46f2008-11-21 07:57:12 +00009162 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009163 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009164 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009165
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009166 // Overloaded operators other than operator() cannot be variadic.
9167 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009168 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009169 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009170 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009171 }
9172
9173 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009174 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9175 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009176 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009177 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009178 }
9179
9180 // C++ [over.inc]p1:
9181 // The user-defined function called operator++ implements the
9182 // prefix and postfix ++ operator. If this function is a member
9183 // function with no parameters, or a non-member function with one
9184 // parameter of class or enumeration type, it defines the prefix
9185 // increment operator ++ for objects of that type. If the function
9186 // is a member function with one parameter (which shall be of type
9187 // int) or a non-member function with two parameters (the second
9188 // of which shall be of type int), it defines the postfix
9189 // increment operator ++ for objects of that type.
9190 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9191 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9192 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009193 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009194 ParamIsInt = BT->getKind() == BuiltinType::Int;
9195
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009196 if (!ParamIsInt)
9197 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009198 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009199 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009200 }
9201
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009202 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009203}
Chris Lattner5a003a42008-12-17 07:09:26 +00009204
Sean Hunta6c058d2010-01-13 09:01:02 +00009205/// CheckLiteralOperatorDeclaration - Check whether the declaration
9206/// of this literal operator function is well-formed. If so, returns
9207/// false; otherwise, emits appropriate diagnostics and returns true.
9208bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009209 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009210 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9211 << FnDecl->getDeclName();
9212 return true;
9213 }
9214
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009215 if (FnDecl->isExternC()) {
9216 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9217 return true;
9218 }
9219
Sean Hunta6c058d2010-01-13 09:01:02 +00009220 bool Valid = false;
9221
Richard Smith36f5cfe2012-03-09 08:00:36 +00009222 // This might be the definition of a literal operator template.
9223 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9224 // This might be a specialization of a literal operator template.
9225 if (!TpDecl)
9226 TpDecl = FnDecl->getPrimaryTemplate();
9227
Sean Hunt216c2782010-04-07 23:11:06 +00009228 // template <char...> type operator "" name() is the only valid template
9229 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009230 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009231 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009232 // Must have only one template parameter
9233 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9234 if (Params->size() == 1) {
9235 NonTypeTemplateParmDecl *PmDecl =
9236 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009237
Sean Hunt216c2782010-04-07 23:11:06 +00009238 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009239 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9240 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9241 Valid = true;
9242 }
9243 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009244 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009245 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009246 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9247
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009248 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009249
Sean Hunt30019c02010-04-07 22:57:35 +00009250 // unsigned long long int, long double, and any character type are allowed
9251 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009252 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9253 Context.hasSameType(T, Context.LongDoubleTy) ||
9254 Context.hasSameType(T, Context.CharTy) ||
9255 Context.hasSameType(T, Context.WCharTy) ||
9256 Context.hasSameType(T, Context.Char16Ty) ||
9257 Context.hasSameType(T, Context.Char32Ty)) {
9258 if (++Param == FnDecl->param_end())
9259 Valid = true;
9260 goto FinishedParams;
9261 }
9262
Sean Hunt30019c02010-04-07 22:57:35 +00009263 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009264 const PointerType *PT = T->getAs<PointerType>();
9265 if (!PT)
9266 goto FinishedParams;
9267 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009268 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009269 goto FinishedParams;
9270 T = T.getUnqualifiedType();
9271
9272 // Move on to the second parameter;
9273 ++Param;
9274
9275 // If there is no second parameter, the first must be a const char *
9276 if (Param == FnDecl->param_end()) {
9277 if (Context.hasSameType(T, Context.CharTy))
9278 Valid = true;
9279 goto FinishedParams;
9280 }
9281
9282 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9283 // are allowed as the first parameter to a two-parameter function
9284 if (!(Context.hasSameType(T, Context.CharTy) ||
9285 Context.hasSameType(T, Context.WCharTy) ||
9286 Context.hasSameType(T, Context.Char16Ty) ||
9287 Context.hasSameType(T, Context.Char32Ty)))
9288 goto FinishedParams;
9289
9290 // The second and final parameter must be an std::size_t
9291 T = (*Param)->getType().getUnqualifiedType();
9292 if (Context.hasSameType(T, Context.getSizeType()) &&
9293 ++Param == FnDecl->param_end())
9294 Valid = true;
9295 }
9296
9297 // FIXME: This diagnostic is absolutely terrible.
9298FinishedParams:
9299 if (!Valid) {
9300 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9301 << FnDecl->getDeclName();
9302 return true;
9303 }
9304
Richard Smitha9e88b22012-03-09 08:16:22 +00009305 // A parameter-declaration-clause containing a default argument is not
9306 // equivalent to any of the permitted forms.
9307 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9308 ParamEnd = FnDecl->param_end();
9309 Param != ParamEnd; ++Param) {
9310 if ((*Param)->hasDefaultArg()) {
9311 Diag((*Param)->getDefaultArgRange().getBegin(),
9312 diag::err_literal_operator_default_argument)
9313 << (*Param)->getDefaultArgRange();
9314 break;
9315 }
9316 }
9317
Richard Smith2fb4ae32012-03-08 02:39:21 +00009318 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009319 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9320 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009321 // C++11 [usrlit.suffix]p1:
9322 // Literal suffix identifiers that do not start with an underscore
9323 // are reserved for future standardization.
9324 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009325 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009326
Sean Hunta6c058d2010-01-13 09:01:02 +00009327 return false;
9328}
9329
Douglas Gregor074149e2009-01-05 19:45:36 +00009330/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9331/// linkage specification, including the language and (if present)
9332/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9333/// the location of the language string literal, which is provided
9334/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9335/// the '{' brace. Otherwise, this linkage specification does not
9336/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009337Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9338 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009339 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009340 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009341 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009342 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009343 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009344 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009345 Language = LinkageSpecDecl::lang_cxx;
9346 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009347 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009348 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009349 }
Mike Stump1eb44332009-09-09 15:08:12 +00009350
Chris Lattnercc98eac2008-12-17 07:13:27 +00009351 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009352
Douglas Gregor074149e2009-01-05 19:45:36 +00009353 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009354 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009355 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009356 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009357 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009358}
9359
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009360/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009361/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9362/// valid, it's the position of the closing '}' brace in a linkage
9363/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009364Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009365 Decl *LinkageSpec,
9366 SourceLocation RBraceLoc) {
9367 if (LinkageSpec) {
9368 if (RBraceLoc.isValid()) {
9369 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9370 LSDecl->setRBraceLoc(RBraceLoc);
9371 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009372 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009373 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009374 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009375}
9376
Douglas Gregord308e622009-05-18 20:51:54 +00009377/// \brief Perform semantic analysis for the variable declaration that
9378/// occurs within a C++ catch clause, returning the newly-created
9379/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009380VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009381 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009382 SourceLocation StartLoc,
9383 SourceLocation Loc,
9384 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009385 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009386 QualType ExDeclType = TInfo->getType();
9387
Sebastian Redl4b07b292008-12-22 19:15:10 +00009388 // Arrays and functions decay.
9389 if (ExDeclType->isArrayType())
9390 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9391 else if (ExDeclType->isFunctionType())
9392 ExDeclType = Context.getPointerType(ExDeclType);
9393
9394 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9395 // The exception-declaration shall not denote a pointer or reference to an
9396 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009397 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009398 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009399 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009400 Invalid = true;
9401 }
Douglas Gregord308e622009-05-18 20:51:54 +00009402
Sebastian Redl4b07b292008-12-22 19:15:10 +00009403 QualType BaseType = ExDeclType;
9404 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009405 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009406 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009407 BaseType = Ptr->getPointeeType();
9408 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009409 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009410 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009411 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009412 BaseType = Ref->getPointeeType();
9413 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009414 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009415 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009416 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009417 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009418 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009419
Mike Stump1eb44332009-09-09 15:08:12 +00009420 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009421 RequireNonAbstractType(Loc, ExDeclType,
9422 diag::err_abstract_type_in_decl,
9423 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009424 Invalid = true;
9425
John McCall5a180392010-07-24 00:37:23 +00009426 // Only the non-fragile NeXT runtime currently supports C++ catches
9427 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009428 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009429 QualType T = ExDeclType;
9430 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9431 T = RT->getPointeeType();
9432
9433 if (T->isObjCObjectType()) {
9434 Diag(Loc, diag::err_objc_object_catch);
9435 Invalid = true;
9436 } else if (T->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009437 if (!getLangOpts().ObjCNonFragileABI)
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009438 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009439 }
9440 }
9441
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009442 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9443 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009444 ExDecl->setExceptionVariable(true);
9445
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009446 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009447 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009448 Invalid = true;
9449
Douglas Gregorc41b8782011-07-06 18:14:43 +00009450 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009451 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009452 // C++ [except.handle]p16:
9453 // The object declared in an exception-declaration or, if the
9454 // exception-declaration does not specify a name, a temporary (12.2) is
9455 // copy-initialized (8.5) from the exception object. [...]
9456 // The object is destroyed when the handler exits, after the destruction
9457 // of any automatic objects initialized within the handler.
9458 //
9459 // We just pretend to initialize the object with itself, then make sure
9460 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009461 QualType initType = ExDeclType;
9462
9463 InitializedEntity entity =
9464 InitializedEntity::InitializeVariable(ExDecl);
9465 InitializationKind initKind =
9466 InitializationKind::CreateCopy(Loc, SourceLocation());
9467
9468 Expr *opaqueValue =
9469 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9470 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9471 ExprResult result = sequence.Perform(*this, entity, initKind,
9472 MultiExprArg(&opaqueValue, 1));
9473 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009474 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009475 else {
9476 // If the constructor used was non-trivial, set this as the
9477 // "initializer".
9478 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9479 if (!construct->getConstructor()->isTrivial()) {
9480 Expr *init = MaybeCreateExprWithCleanups(construct);
9481 ExDecl->setInit(init);
9482 }
9483
9484 // And make sure it's destructable.
9485 FinalizeVarWithDestructor(ExDecl, recordType);
9486 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009487 }
9488 }
9489
Douglas Gregord308e622009-05-18 20:51:54 +00009490 if (Invalid)
9491 ExDecl->setInvalidDecl();
9492
9493 return ExDecl;
9494}
9495
9496/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9497/// handler.
John McCalld226f652010-08-21 09:40:31 +00009498Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009499 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009500 bool Invalid = D.isInvalidType();
9501
9502 // Check for unexpanded parameter packs.
9503 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9504 UPPC_ExceptionType)) {
9505 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9506 D.getIdentifierLoc());
9507 Invalid = true;
9508 }
9509
Sebastian Redl4b07b292008-12-22 19:15:10 +00009510 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009511 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009512 LookupOrdinaryName,
9513 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009514 // The scope should be freshly made just for us. There is just no way
9515 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009516 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009517 if (PrevDecl->isTemplateParameter()) {
9518 // Maybe we will complain about the shadowed template parameter.
9519 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009520 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009521 }
9522 }
9523
Chris Lattnereaaebc72009-04-25 08:06:05 +00009524 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009525 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9526 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009527 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009528 }
9529
Douglas Gregor83cb9422010-09-09 17:09:21 +00009530 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009531 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009532 D.getIdentifierLoc(),
9533 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009534 if (Invalid)
9535 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009536
Sebastian Redl4b07b292008-12-22 19:15:10 +00009537 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009538 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009539 PushOnScopeChains(ExDecl, S);
9540 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009541 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009542
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009543 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009544 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009545}
Anders Carlssonfb311762009-03-14 00:25:26 +00009546
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009547Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009548 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009549 Expr *AssertMessageExpr_,
9550 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009551 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009552
Anders Carlssonc3082412009-03-14 00:33:21 +00009553 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009554 // In a static_assert-declaration, the constant-expression shall be a
9555 // constant expression that can be contextually converted to bool.
9556 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9557 if (Converted.isInvalid())
9558 return 0;
9559
Richard Smithdaaefc52011-12-14 23:32:26 +00009560 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009561 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009562 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009563 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009564 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009565
Richard Smith0cc323c2012-03-05 23:20:05 +00009566 if (!Cond) {
9567 llvm::SmallString<256> MsgBuffer;
9568 llvm::raw_svector_ostream Msg(MsgBuffer);
9569 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009570 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009571 << Msg.str() << AssertExpr->getSourceRange();
9572 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009573 }
Mike Stump1eb44332009-09-09 15:08:12 +00009574
Douglas Gregor399ad972010-12-15 23:55:21 +00009575 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9576 return 0;
9577
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009578 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9579 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009580
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009581 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009582 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009583}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009584
Douglas Gregor1d869352010-04-07 16:53:43 +00009585/// \brief Perform semantic analysis of the given friend type declaration.
9586///
9587/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009588FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9589 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009590 TypeSourceInfo *TSInfo) {
9591 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9592
9593 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009594 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009595
Richard Smith6b130222011-10-18 21:39:00 +00009596 // C++03 [class.friend]p2:
9597 // An elaborated-type-specifier shall be used in a friend declaration
9598 // for a class.*
9599 //
9600 // * The class-key of the elaborated-type-specifier is required.
9601 if (!ActiveTemplateInstantiations.empty()) {
9602 // Do not complain about the form of friend template types during
9603 // template instantiation; we will already have complained when the
9604 // template was declared.
9605 } else if (!T->isElaboratedTypeSpecifier()) {
9606 // If we evaluated the type to a record type, suggest putting
9607 // a tag in front.
9608 if (const RecordType *RT = T->getAs<RecordType>()) {
9609 RecordDecl *RD = RT->getDecl();
9610
9611 std::string InsertionText = std::string(" ") + RD->getKindName();
9612
9613 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009614 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009615 diag::warn_cxx98_compat_unelaborated_friend_type :
9616 diag::ext_unelaborated_friend_type)
9617 << (unsigned) RD->getTagKind()
9618 << T
9619 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9620 InsertionText);
9621 } else {
9622 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009623 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009624 diag::warn_cxx98_compat_nonclass_type_friend :
9625 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009626 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009627 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009628 }
Richard Smith6b130222011-10-18 21:39:00 +00009629 } else if (T->getAs<EnumType>()) {
9630 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009631 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009632 diag::warn_cxx98_compat_enum_friend :
9633 diag::ext_enum_friend)
9634 << T
9635 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009636 }
9637
Douglas Gregor06245bf2010-04-07 17:57:12 +00009638 // C++0x [class.friend]p3:
9639 // If the type specifier in a friend declaration designates a (possibly
9640 // cv-qualified) class type, that class is declared as a friend; otherwise,
9641 // the friend declaration is ignored.
9642
9643 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9644 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009645
Abramo Bagnara0216df82011-10-29 20:52:52 +00009646 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009647}
9648
John McCall9a34edb2010-10-19 01:40:49 +00009649/// Handle a friend tag declaration where the scope specifier was
9650/// templated.
9651Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9652 unsigned TagSpec, SourceLocation TagLoc,
9653 CXXScopeSpec &SS,
9654 IdentifierInfo *Name, SourceLocation NameLoc,
9655 AttributeList *Attr,
9656 MultiTemplateParamsArg TempParamLists) {
9657 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9658
9659 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009660 bool Invalid = false;
9661
9662 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009663 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009664 TempParamLists.get(),
9665 TempParamLists.size(),
9666 /*friend*/ true,
9667 isExplicitSpecialization,
9668 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009669 if (TemplateParams->size() > 0) {
9670 // This is a declaration of a class template.
9671 if (Invalid)
9672 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009673
Eric Christopher4110e132011-07-21 05:34:24 +00009674 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9675 SS, Name, NameLoc, Attr,
9676 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009677 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009678 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009679 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009680 } else {
9681 // The "template<>" header is extraneous.
9682 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9683 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9684 isExplicitSpecialization = true;
9685 }
9686 }
9687
9688 if (Invalid) return 0;
9689
John McCall9a34edb2010-10-19 01:40:49 +00009690 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009691 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009692 if (TempParamLists.get()[I]->size()) {
9693 isAllExplicitSpecializations = false;
9694 break;
9695 }
9696 }
9697
9698 // FIXME: don't ignore attributes.
9699
9700 // If it's explicit specializations all the way down, just forget
9701 // about the template header and build an appropriate non-templated
9702 // friend. TODO: for source fidelity, remember the headers.
9703 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009704 if (SS.isEmpty()) {
9705 bool Owned = false;
9706 bool IsDependent = false;
9707 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9708 Attr, AS_public,
9709 /*ModulePrivateLoc=*/SourceLocation(),
9710 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009711 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009712 /*ScopedEnumUsesClassTag=*/false,
9713 /*UnderlyingType=*/TypeResult());
9714 }
9715
Douglas Gregor2494dd02011-03-01 01:34:45 +00009716 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009717 ElaboratedTypeKeyword Keyword
9718 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009719 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009720 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009721 if (T.isNull())
9722 return 0;
9723
9724 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9725 if (isa<DependentNameType>(T)) {
9726 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009727 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009728 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009729 TL.setNameLoc(NameLoc);
9730 } else {
9731 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009732 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009733 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009734 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9735 }
9736
9737 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9738 TSI, FriendLoc);
9739 Friend->setAccess(AS_public);
9740 CurContext->addDecl(Friend);
9741 return Friend;
9742 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009743
9744 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9745
9746
John McCall9a34edb2010-10-19 01:40:49 +00009747
9748 // Handle the case of a templated-scope friend class. e.g.
9749 // template <class T> class A<T>::B;
9750 // FIXME: we don't support these right now.
9751 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9752 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9753 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9754 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009755 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009756 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009757 TL.setNameLoc(NameLoc);
9758
9759 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9760 TSI, FriendLoc);
9761 Friend->setAccess(AS_public);
9762 Friend->setUnsupportedFriend(true);
9763 CurContext->addDecl(Friend);
9764 return Friend;
9765}
9766
9767
John McCalldd4a3b02009-09-16 22:47:08 +00009768/// Handle a friend type declaration. This works in tandem with
9769/// ActOnTag.
9770///
9771/// Notes on friend class templates:
9772///
9773/// We generally treat friend class declarations as if they were
9774/// declaring a class. So, for example, the elaborated type specifier
9775/// in a friend declaration is required to obey the restrictions of a
9776/// class-head (i.e. no typedefs in the scope chain), template
9777/// parameters are required to match up with simple template-ids, &c.
9778/// However, unlike when declaring a template specialization, it's
9779/// okay to refer to a template specialization without an empty
9780/// template parameter declaration, e.g.
9781/// friend class A<T>::B<unsigned>;
9782/// We permit this as a special case; if there are any template
9783/// parameters present at all, require proper matching, i.e.
9784/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009785Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009786 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009787 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +00009788
9789 assert(DS.isFriendSpecified());
9790 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9791
John McCalldd4a3b02009-09-16 22:47:08 +00009792 // Try to convert the decl specifier to a type. This works for
9793 // friend templates because ActOnTag never produces a ClassTemplateDecl
9794 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009795 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009796 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9797 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009798 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009799 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009800
Douglas Gregor6ccab972010-12-16 01:14:37 +00009801 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9802 return 0;
9803
John McCalldd4a3b02009-09-16 22:47:08 +00009804 // This is definitely an error in C++98. It's probably meant to
9805 // be forbidden in C++0x, too, but the specification is just
9806 // poorly written.
9807 //
9808 // The problem is with declarations like the following:
9809 // template <T> friend A<T>::foo;
9810 // where deciding whether a class C is a friend or not now hinges
9811 // on whether there exists an instantiation of A that causes
9812 // 'foo' to equal C. There are restrictions on class-heads
9813 // (which we declare (by fiat) elaborated friend declarations to
9814 // be) that makes this tractable.
9815 //
9816 // FIXME: handle "template <> friend class A<T>;", which
9817 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009818 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009819 Diag(Loc, diag::err_tagless_friend_type_template)
9820 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009821 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009822 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009823
John McCall02cace72009-08-28 07:59:38 +00009824 // C++98 [class.friend]p1: A friend of a class is a function
9825 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009826 // This is fixed in DR77, which just barely didn't make the C++03
9827 // deadline. It's also a very silly restriction that seriously
9828 // affects inner classes and which nobody else seems to implement;
9829 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009830 //
9831 // But note that we could warn about it: it's always useless to
9832 // friend one of your own members (it's not, however, worthless to
9833 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009834
John McCalldd4a3b02009-09-16 22:47:08 +00009835 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009836 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009837 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009838 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009839 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009840 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009841 DS.getFriendSpecLoc());
9842 else
Abramo Bagnara0216df82011-10-29 20:52:52 +00009843 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +00009844
9845 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009846 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009847
John McCalldd4a3b02009-09-16 22:47:08 +00009848 D->setAccess(AS_public);
9849 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009850
John McCalld226f652010-08-21 09:40:31 +00009851 return D;
John McCall02cace72009-08-28 07:59:38 +00009852}
9853
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009854Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +00009855 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009856 const DeclSpec &DS = D.getDeclSpec();
9857
9858 assert(DS.isFriendSpecified());
9859 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9860
9861 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009862 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +00009863
9864 // C++ [class.friend]p1
9865 // A friend of a class is a function or class....
9866 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009867 // It *doesn't* see through dependent types, which is correct
9868 // according to [temp.arg.type]p3:
9869 // If a declaration acquires a function type through a
9870 // type dependent on a template-parameter and this causes
9871 // a declaration that does not use the syntactic form of a
9872 // function declarator to have a function type, the program
9873 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009874 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +00009875 Diag(Loc, diag::err_unexpected_friend);
9876
9877 // It might be worthwhile to try to recover by creating an
9878 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009879 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009880 }
9881
9882 // C++ [namespace.memdef]p3
9883 // - If a friend declaration in a non-local class first declares a
9884 // class or function, the friend class or function is a member
9885 // of the innermost enclosing namespace.
9886 // - The name of the friend is not found by simple name lookup
9887 // until a matching declaration is provided in that namespace
9888 // scope (either before or after the class declaration granting
9889 // friendship).
9890 // - If a friend function is called, its name may be found by the
9891 // name lookup that considers functions from namespaces and
9892 // classes associated with the types of the function arguments.
9893 // - When looking for a prior declaration of a class or a function
9894 // declared as a friend, scopes outside the innermost enclosing
9895 // namespace scope are not considered.
9896
John McCall337ec3d2010-10-12 23:13:28 +00009897 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009898 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9899 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009900 assert(Name);
9901
Douglas Gregor6ccab972010-12-16 01:14:37 +00009902 // Check for unexpanded parameter packs.
9903 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9904 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9905 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9906 return 0;
9907
John McCall67d1a672009-08-06 02:15:43 +00009908 // The context we found the declaration in, or in which we should
9909 // create the declaration.
9910 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009911 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009912 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009913 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009914
John McCall337ec3d2010-10-12 23:13:28 +00009915 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009916
John McCall337ec3d2010-10-12 23:13:28 +00009917 // There are four cases here.
9918 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009919 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009920 // there as appropriate.
9921 // Recover from invalid scope qualifiers as if they just weren't there.
9922 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009923 // C++0x [namespace.memdef]p3:
9924 // If the name in a friend declaration is neither qualified nor
9925 // a template-id and the declaration is a function or an
9926 // elaborated-type-specifier, the lookup to determine whether
9927 // the entity has been previously declared shall not consider
9928 // any scopes outside the innermost enclosing namespace.
9929 // C++0x [class.friend]p11:
9930 // If a friend declaration appears in a local class and the name
9931 // specified is an unqualified name, a prior declaration is
9932 // looked up without considering scopes that are outside the
9933 // innermost enclosing non-class scope. For a friend function
9934 // declaration, if there is no prior declaration, the program is
9935 // ill-formed.
9936 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009937 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009938
John McCall29ae6e52010-10-13 05:45:15 +00009939 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009940 DC = CurContext;
9941 while (true) {
9942 // Skip class contexts. If someone can cite chapter and verse
9943 // for this behavior, that would be nice --- it's what GCC and
9944 // EDG do, and it seems like a reasonable intent, but the spec
9945 // really only says that checks for unqualified existing
9946 // declarations should stop at the nearest enclosing namespace,
9947 // not that they should only consider the nearest enclosing
9948 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +00009949 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +00009950 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009951
John McCall68263142009-11-18 22:49:29 +00009952 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009953
9954 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009955 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009956 break;
John McCall29ae6e52010-10-13 05:45:15 +00009957
John McCall8a407372010-10-14 22:22:28 +00009958 if (isTemplateId) {
9959 if (isa<TranslationUnitDecl>(DC)) break;
9960 } else {
9961 if (DC->isFileContext()) break;
9962 }
John McCall67d1a672009-08-06 02:15:43 +00009963 DC = DC->getParent();
9964 }
9965
9966 // C++ [class.friend]p1: A friend of a class is a function or
9967 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +00009968 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +00009969 // Most C++ 98 compilers do seem to give an error here, so
9970 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +00009971 if (!Previous.empty() && DC->Equals(CurContext))
9972 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009973 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00009974 diag::warn_cxx98_compat_friend_is_member :
9975 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009976
John McCall380aaa42010-10-13 06:22:15 +00009977 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +00009978
Douglas Gregor883af832011-10-10 01:11:59 +00009979 // C++ [class.friend]p6:
9980 // A function can be defined in a friend declaration of a class if and
9981 // only if the class is a non-local class (9.8), the function name is
9982 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00009983 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +00009984 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
9985 }
9986
John McCall337ec3d2010-10-12 23:13:28 +00009987 // - There's a non-dependent scope specifier, in which case we
9988 // compute it and do a previous lookup there for a function
9989 // or function template.
9990 } else if (!SS.getScopeRep()->isDependent()) {
9991 DC = computeDeclContext(SS);
9992 if (!DC) return 0;
9993
9994 if (RequireCompleteDeclContext(SS, DC)) return 0;
9995
9996 LookupQualifiedName(Previous, DC);
9997
9998 // Ignore things found implicitly in the wrong scope.
9999 // TODO: better diagnostics for this case. Suggesting the right
10000 // qualified scope would be nice...
10001 LookupResult::Filter F = Previous.makeFilter();
10002 while (F.hasNext()) {
10003 NamedDecl *D = F.next();
10004 if (!DC->InEnclosingNamespaceSetOf(
10005 D->getDeclContext()->getRedeclContext()))
10006 F.erase();
10007 }
10008 F.done();
10009
10010 if (Previous.empty()) {
10011 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010012 Diag(Loc, diag::err_qualified_friend_not_found)
10013 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010014 return 0;
10015 }
10016
10017 // C++ [class.friend]p1: A friend of a class is a function or
10018 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010019 if (DC->Equals(CurContext))
10020 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010021 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010022 diag::warn_cxx98_compat_friend_is_member :
10023 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010024
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010025 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010026 // C++ [class.friend]p6:
10027 // A function can be defined in a friend declaration of a class if and
10028 // only if the class is a non-local class (9.8), the function name is
10029 // unqualified, and the function has namespace scope.
10030 SemaDiagnosticBuilder DB
10031 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10032
10033 DB << SS.getScopeRep();
10034 if (DC->isFileContext())
10035 DB << FixItHint::CreateRemoval(SS.getRange());
10036 SS.clear();
10037 }
John McCall337ec3d2010-10-12 23:13:28 +000010038
10039 // - There's a scope specifier that does not match any template
10040 // parameter lists, in which case we use some arbitrary context,
10041 // create a method or method template, and wait for instantiation.
10042 // - There's a scope specifier that does match some template
10043 // parameter lists, which we don't handle right now.
10044 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010045 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010046 // C++ [class.friend]p6:
10047 // A function can be defined in a friend declaration of a class if and
10048 // only if the class is a non-local class (9.8), the function name is
10049 // unqualified, and the function has namespace scope.
10050 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10051 << SS.getScopeRep();
10052 }
10053
John McCall337ec3d2010-10-12 23:13:28 +000010054 DC = CurContext;
10055 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010056 }
Douglas Gregor883af832011-10-10 01:11:59 +000010057
John McCall29ae6e52010-10-13 05:45:15 +000010058 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010059 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010060 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10061 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10062 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010063 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010064 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10065 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010066 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010067 }
John McCall67d1a672009-08-06 02:15:43 +000010068 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010069
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010070 // FIXME: This is an egregious hack to cope with cases where the scope stack
10071 // does not contain the declaration context, i.e., in an out-of-line
10072 // definition of a class.
10073 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10074 if (!DCScope) {
10075 FakeDCScope.setEntity(DC);
10076 DCScope = &FakeDCScope;
10077 }
10078
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010079 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010080 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10081 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010082 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010083
Douglas Gregor182ddf02009-09-28 00:08:27 +000010084 assert(ND->getDeclContext() == DC);
10085 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010086
John McCallab88d972009-08-31 22:39:49 +000010087 // Add the function declaration to the appropriate lookup tables,
10088 // adjusting the redeclarations list as necessary. We don't
10089 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010090 //
John McCallab88d972009-08-31 22:39:49 +000010091 // Also update the scope-based lookup if the target context's
10092 // lookup context is in lexical scope.
10093 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010094 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010095 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010096 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010097 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010098 }
John McCall02cace72009-08-28 07:59:38 +000010099
10100 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010101 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010102 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010103 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010104 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010105
John McCall337ec3d2010-10-12 23:13:28 +000010106 if (ND->isInvalidDecl())
10107 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010108 else {
10109 FunctionDecl *FD;
10110 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10111 FD = FTD->getTemplatedDecl();
10112 else
10113 FD = cast<FunctionDecl>(ND);
10114
10115 // Mark templated-scope function declarations as unsupported.
10116 if (FD->getNumTemplateParameterLists())
10117 FrD->setUnsupportedFriend(true);
10118 }
John McCall337ec3d2010-10-12 23:13:28 +000010119
John McCalld226f652010-08-21 09:40:31 +000010120 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010121}
10122
John McCalld226f652010-08-21 09:40:31 +000010123void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10124 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010125
Sebastian Redl50de12f2009-03-24 22:27:57 +000010126 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10127 if (!Fn) {
10128 Diag(DelLoc, diag::err_deleted_non_function);
10129 return;
10130 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010131 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010132 Diag(DelLoc, diag::err_deleted_decl_not_first);
10133 Diag(Prev->getLocation(), diag::note_previous_declaration);
10134 // If the declaration wasn't the first, we delete the function anyway for
10135 // recovery.
10136 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010137 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010138
10139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10140 if (!MD)
10141 return;
10142
10143 // A deleted special member function is trivial if the corresponding
10144 // implicitly-declared function would have been.
10145 switch (getSpecialMember(MD)) {
10146 case CXXInvalid:
10147 break;
10148 case CXXDefaultConstructor:
10149 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10150 break;
10151 case CXXCopyConstructor:
10152 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10153 break;
10154 case CXXMoveConstructor:
10155 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10156 break;
10157 case CXXCopyAssignment:
10158 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10159 break;
10160 case CXXMoveAssignment:
10161 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10162 break;
10163 case CXXDestructor:
10164 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10165 break;
10166 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010167}
Sebastian Redl13e88542009-04-27 21:33:24 +000010168
Sean Hunte4246a62011-05-12 06:15:49 +000010169void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10170 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10171
10172 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010173 if (MD->getParent()->isDependentType()) {
10174 MD->setDefaulted();
10175 MD->setExplicitlyDefaulted();
10176 return;
10177 }
10178
Sean Hunte4246a62011-05-12 06:15:49 +000010179 CXXSpecialMember Member = getSpecialMember(MD);
10180 if (Member == CXXInvalid) {
10181 Diag(DefaultLoc, diag::err_default_special_members);
10182 return;
10183 }
10184
10185 MD->setDefaulted();
10186 MD->setExplicitlyDefaulted();
10187
Sean Huntcd10dec2011-05-23 23:14:04 +000010188 // If this definition appears within the record, do the checking when
10189 // the record is complete.
10190 const FunctionDecl *Primary = MD;
10191 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10192 // Find the uninstantiated declaration that actually had the '= default'
10193 // on it.
10194 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10195
10196 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010197 return;
10198
10199 switch (Member) {
10200 case CXXDefaultConstructor: {
10201 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010202 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010203 if (!CD->isInvalidDecl())
10204 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10205 break;
10206 }
10207
10208 case CXXCopyConstructor: {
10209 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010210 CheckExplicitlyDefaultedSpecialMember(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010211 if (!CD->isInvalidDecl())
10212 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010213 break;
10214 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010215
Sean Hunt2b188082011-05-14 05:23:28 +000010216 case CXXCopyAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010217 CheckExplicitlyDefaultedSpecialMember(MD);
Sean Hunt2b188082011-05-14 05:23:28 +000010218 if (!MD->isInvalidDecl())
10219 DefineImplicitCopyAssignment(DefaultLoc, MD);
10220 break;
10221 }
10222
Sean Huntcb45a0f2011-05-12 22:46:25 +000010223 case CXXDestructor: {
10224 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010225 CheckExplicitlyDefaultedSpecialMember(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010226 if (!DD->isInvalidDecl())
10227 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010228 break;
10229 }
10230
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010231 case CXXMoveConstructor: {
10232 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Richard Smith3003e1d2012-05-15 04:39:51 +000010233 CheckExplicitlyDefaultedSpecialMember(CD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010234 if (!CD->isInvalidDecl())
10235 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010236 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010237 }
Sean Hunt82713172011-05-25 23:16:36 +000010238
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010239 case CXXMoveAssignment: {
Richard Smith3003e1d2012-05-15 04:39:51 +000010240 CheckExplicitlyDefaultedSpecialMember(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010241 if (!MD->isInvalidDecl())
10242 DefineImplicitMoveAssignment(DefaultLoc, MD);
10243 break;
10244 }
10245
10246 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010247 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010248 }
10249 } else {
10250 Diag(DefaultLoc, diag::err_default_special_members);
10251 }
10252}
10253
Sebastian Redl13e88542009-04-27 21:33:24 +000010254static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010255 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010256 Stmt *SubStmt = *CI;
10257 if (!SubStmt)
10258 continue;
10259 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010260 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010261 diag::err_return_in_constructor_handler);
10262 if (!isa<Expr>(SubStmt))
10263 SearchForReturnInStmt(Self, SubStmt);
10264 }
10265}
10266
10267void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10268 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10269 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10270 SearchForReturnInStmt(*this, Handler);
10271 }
10272}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010273
Mike Stump1eb44332009-09-09 15:08:12 +000010274bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010275 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010276 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10277 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010278
Chandler Carruth73857792010-02-15 11:53:20 +000010279 if (Context.hasSameType(NewTy, OldTy) ||
10280 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010281 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010282
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010283 // Check if the return types are covariant
10284 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010285
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010286 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010287 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10288 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010289 NewClassTy = NewPT->getPointeeType();
10290 OldClassTy = OldPT->getPointeeType();
10291 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010292 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10293 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10294 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10295 NewClassTy = NewRT->getPointeeType();
10296 OldClassTy = OldRT->getPointeeType();
10297 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010298 }
10299 }
Mike Stump1eb44332009-09-09 15:08:12 +000010300
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010301 // The return types aren't either both pointers or references to a class type.
10302 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010303 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010304 diag::err_different_return_type_for_overriding_virtual_function)
10305 << New->getDeclName() << NewTy << OldTy;
10306 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010307
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010308 return true;
10309 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010310
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010311 // C++ [class.virtual]p6:
10312 // If the return type of D::f differs from the return type of B::f, the
10313 // class type in the return type of D::f shall be complete at the point of
10314 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010315 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10316 if (!RT->isBeingDefined() &&
10317 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010318 diag::err_covariant_return_incomplete,
10319 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010320 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010321 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010322
Douglas Gregora4923eb2009-11-16 21:35:15 +000010323 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010324 // Check if the new class derives from the old class.
10325 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10326 Diag(New->getLocation(),
10327 diag::err_covariant_return_not_derived)
10328 << New->getDeclName() << NewTy << OldTy;
10329 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10330 return true;
10331 }
Mike Stump1eb44332009-09-09 15:08:12 +000010332
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010333 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010334 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010335 diag::err_covariant_return_inaccessible_base,
10336 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10337 // FIXME: Should this point to the return type?
10338 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010339 // FIXME: this note won't trigger for delayed access control
10340 // diagnostics, and it's impossible to get an undelayed error
10341 // here from access control during the original parse because
10342 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010343 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10344 return true;
10345 }
10346 }
Mike Stump1eb44332009-09-09 15:08:12 +000010347
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010348 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010349 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010350 Diag(New->getLocation(),
10351 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010352 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010353 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10354 return true;
10355 };
Mike Stump1eb44332009-09-09 15:08:12 +000010356
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010357
10358 // The new class type must have the same or less qualifiers as the old type.
10359 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10360 Diag(New->getLocation(),
10361 diag::err_covariant_return_type_class_type_more_qualified)
10362 << New->getDeclName() << NewTy << OldTy;
10363 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10364 return true;
10365 };
Mike Stump1eb44332009-09-09 15:08:12 +000010366
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010367 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010368}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010369
Douglas Gregor4ba31362009-12-01 17:24:26 +000010370/// \brief Mark the given method pure.
10371///
10372/// \param Method the method to be marked pure.
10373///
10374/// \param InitRange the source range that covers the "0" initializer.
10375bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010376 SourceLocation EndLoc = InitRange.getEnd();
10377 if (EndLoc.isValid())
10378 Method->setRangeEnd(EndLoc);
10379
Douglas Gregor4ba31362009-12-01 17:24:26 +000010380 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10381 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010382 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010383 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010384
10385 if (!Method->isInvalidDecl())
10386 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10387 << Method->getDeclName() << InitRange;
10388 return true;
10389}
10390
Douglas Gregor552e2992012-02-21 02:22:07 +000010391/// \brief Determine whether the given declaration is a static data member.
10392static bool isStaticDataMember(Decl *D) {
10393 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10394 if (!Var)
10395 return false;
10396
10397 return Var->isStaticDataMember();
10398}
John McCall731ad842009-12-19 09:28:58 +000010399/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10400/// an initializer for the out-of-line declaration 'Dcl'. The scope
10401/// is a fresh scope pushed for just this purpose.
10402///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010403/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10404/// static data member of class X, names should be looked up in the scope of
10405/// class X.
John McCalld226f652010-08-21 09:40:31 +000010406void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010407 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010408 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010409
John McCall731ad842009-12-19 09:28:58 +000010410 // We should only get called for declarations with scope specifiers, like:
10411 // int foo::bar;
10412 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010413 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010414
10415 // If we are parsing the initializer for a static data member, push a
10416 // new expression evaluation context that is associated with this static
10417 // data member.
10418 if (isStaticDataMember(D))
10419 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010420}
10421
10422/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010423/// initializer for the out-of-line declaration 'D'.
10424void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010425 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010426 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010427
Douglas Gregor552e2992012-02-21 02:22:07 +000010428 if (isStaticDataMember(D))
10429 PopExpressionEvaluationContext();
10430
John McCall731ad842009-12-19 09:28:58 +000010431 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010432 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010433}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010434
10435/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10436/// C++ if/switch/while/for statement.
10437/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010438DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010439 // C++ 6.4p2:
10440 // The declarator shall not specify a function or an array.
10441 // The type-specifier-seq shall not contain typedef and shall not declare a
10442 // new class or enumeration.
10443 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10444 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010445
10446 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010447 if (!Dcl)
10448 return true;
10449
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010450 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10451 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010452 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010453 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010454 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010455
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010456 return Dcl;
10457}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010458
Douglas Gregordfe65432011-07-28 19:11:31 +000010459void Sema::LoadExternalVTableUses() {
10460 if (!ExternalSource)
10461 return;
10462
10463 SmallVector<ExternalVTableUse, 4> VTables;
10464 ExternalSource->ReadUsedVTables(VTables);
10465 SmallVector<VTableUse, 4> NewUses;
10466 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10467 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10468 = VTablesUsed.find(VTables[I].Record);
10469 // Even if a definition wasn't required before, it may be required now.
10470 if (Pos != VTablesUsed.end()) {
10471 if (!Pos->second && VTables[I].DefinitionRequired)
10472 Pos->second = true;
10473 continue;
10474 }
10475
10476 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10477 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10478 }
10479
10480 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10481}
10482
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010483void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10484 bool DefinitionRequired) {
10485 // Ignore any vtable uses in unevaluated operands or for classes that do
10486 // not have a vtable.
10487 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10488 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010489 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010490 return;
10491
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010492 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010493 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010494 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10495 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10496 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10497 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010498 // If we already had an entry, check to see if we are promoting this vtable
10499 // to required a definition. If so, we need to reappend to the VTableUses
10500 // list, since we may have already processed the first entry.
10501 if (DefinitionRequired && !Pos.first->second) {
10502 Pos.first->second = true;
10503 } else {
10504 // Otherwise, we can early exit.
10505 return;
10506 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010507 }
10508
10509 // Local classes need to have their virtual members marked
10510 // immediately. For all other classes, we mark their virtual members
10511 // at the end of the translation unit.
10512 if (Class->isLocalClass())
10513 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010514 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010515 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010516}
10517
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010518bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010519 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010520 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010521 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010522
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010523 // Note: The VTableUses vector could grow as a result of marking
10524 // the members of a class as "used", so we check the size each
10525 // time through the loop and prefer indices (with are stable) to
10526 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010527 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010528 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010529 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010530 if (!Class)
10531 continue;
10532
10533 SourceLocation Loc = VTableUses[I].second;
10534
10535 // If this class has a key function, but that key function is
10536 // defined in another translation unit, we don't need to emit the
10537 // vtable even though we're using it.
10538 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010539 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010540 switch (KeyFunction->getTemplateSpecializationKind()) {
10541 case TSK_Undeclared:
10542 case TSK_ExplicitSpecialization:
10543 case TSK_ExplicitInstantiationDeclaration:
10544 // The key function is in another translation unit.
10545 continue;
10546
10547 case TSK_ExplicitInstantiationDefinition:
10548 case TSK_ImplicitInstantiation:
10549 // We will be instantiating the key function.
10550 break;
10551 }
10552 } else if (!KeyFunction) {
10553 // If we have a class with no key function that is the subject
10554 // of an explicit instantiation declaration, suppress the
10555 // vtable; it will live with the explicit instantiation
10556 // definition.
10557 bool IsExplicitInstantiationDeclaration
10558 = Class->getTemplateSpecializationKind()
10559 == TSK_ExplicitInstantiationDeclaration;
10560 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10561 REnd = Class->redecls_end();
10562 R != REnd; ++R) {
10563 TemplateSpecializationKind TSK
10564 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10565 if (TSK == TSK_ExplicitInstantiationDeclaration)
10566 IsExplicitInstantiationDeclaration = true;
10567 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10568 IsExplicitInstantiationDeclaration = false;
10569 break;
10570 }
10571 }
10572
10573 if (IsExplicitInstantiationDeclaration)
10574 continue;
10575 }
10576
10577 // Mark all of the virtual members of this class as referenced, so
10578 // that we can build a vtable. Then, tell the AST consumer that a
10579 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010580 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010581 MarkVirtualMembersReferenced(Loc, Class);
10582 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10583 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10584
10585 // Optionally warn if we're emitting a weak vtable.
10586 if (Class->getLinkage() == ExternalLinkage &&
10587 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010588 const FunctionDecl *KeyFunctionDef = 0;
10589 if (!KeyFunction ||
10590 (KeyFunction->hasBody(KeyFunctionDef) &&
10591 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010592 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10593 TSK_ExplicitInstantiationDefinition
10594 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10595 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010596 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010597 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010598 VTableUses.clear();
10599
Douglas Gregor78844032011-04-22 22:25:37 +000010600 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010601}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010602
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010603void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10604 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010605 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10606 e = RD->method_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +000010607 CXXMethodDecl *MD = &*i;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010608
10609 // C++ [basic.def.odr]p2:
10610 // [...] A virtual member function is used if it is not pure. [...]
10611 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010612 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010613 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010614
10615 // Only classes that have virtual bases need a VTT.
10616 if (RD->getNumVBases() == 0)
10617 return;
10618
10619 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10620 e = RD->bases_end(); i != e; ++i) {
10621 const CXXRecordDecl *Base =
10622 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010623 if (Base->getNumVBases() == 0)
10624 continue;
10625 MarkVirtualMembersReferenced(Loc, Base);
10626 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010627}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010628
10629/// SetIvarInitializers - This routine builds initialization ASTs for the
10630/// Objective-C implementation whose ivars need be initialized.
10631void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010632 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010633 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010634 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010635 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010636 CollectIvarsToConstructOrDestruct(OID, ivars);
10637 if (ivars.empty())
10638 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010639 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010640 for (unsigned i = 0; i < ivars.size(); i++) {
10641 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010642 if (Field->isInvalidDecl())
10643 continue;
10644
Sean Huntcbb67482011-01-08 20:30:50 +000010645 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010646 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10647 InitializationKind InitKind =
10648 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10649
10650 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010651 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010652 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010653 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010654 // Note, MemberInit could actually come back empty if no initialization
10655 // is required (e.g., because it would call a trivial default constructor)
10656 if (!MemberInit.get() || MemberInit.isInvalid())
10657 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010658
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010659 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010660 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10661 SourceLocation(),
10662 MemberInit.takeAs<Expr>(),
10663 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010664 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010665
10666 // Be sure that the destructor is accessible and is marked as referenced.
10667 if (const RecordType *RecordTy
10668 = Context.getBaseElementType(Field->getType())
10669 ->getAs<RecordType>()) {
10670 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010671 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010672 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010673 CheckDestructorAccess(Field->getLocation(), Destructor,
10674 PDiag(diag::err_access_dtor_ivar)
10675 << Context.getBaseElementType(Field->getType()));
10676 }
10677 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010678 }
10679 ObjCImplementation->setIvarInitializers(Context,
10680 AllToInit.data(), AllToInit.size());
10681 }
10682}
Sean Huntfe57eef2011-05-04 05:57:24 +000010683
Sean Huntebcbe1d2011-05-04 23:29:54 +000010684static
10685void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10686 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10687 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10688 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10689 Sema &S) {
10690 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10691 CE = Current.end();
10692 if (Ctor->isInvalidDecl())
10693 return;
10694
10695 const FunctionDecl *FNTarget = 0;
10696 CXXConstructorDecl *Target;
10697
10698 // We ignore the result here since if we don't have a body, Target will be
10699 // null below.
10700 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10701 Target
10702= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10703
10704 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10705 // Avoid dereferencing a null pointer here.
10706 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10707
10708 if (!Current.insert(Canonical))
10709 return;
10710
10711 // We know that beyond here, we aren't chaining into a cycle.
10712 if (!Target || !Target->isDelegatingConstructor() ||
10713 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10714 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10715 Valid.insert(*CI);
10716 Current.clear();
10717 // We've hit a cycle.
10718 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10719 Current.count(TCanonical)) {
10720 // If we haven't diagnosed this cycle yet, do so now.
10721 if (!Invalid.count(TCanonical)) {
10722 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010723 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010724 << Ctor;
10725
10726 // Don't add a note for a function delegating directo to itself.
10727 if (TCanonical != Canonical)
10728 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10729
10730 CXXConstructorDecl *C = Target;
10731 while (C->getCanonicalDecl() != Canonical) {
10732 (void)C->getTargetConstructor()->hasBody(FNTarget);
10733 assert(FNTarget && "Ctor cycle through bodiless function");
10734
10735 C
10736 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10737 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10738 }
10739 }
10740
10741 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10742 Invalid.insert(*CI);
10743 Current.clear();
10744 } else {
10745 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10746 }
10747}
10748
10749
Sean Huntfe57eef2011-05-04 05:57:24 +000010750void Sema::CheckDelegatingCtorCycles() {
10751 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10752
Sean Huntebcbe1d2011-05-04 23:29:54 +000010753 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10754 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010755
Douglas Gregor0129b562011-07-27 21:57:17 +000010756 for (DelegatingCtorDeclsType::iterator
10757 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010758 E = DelegatingCtorDecls.end();
10759 I != E; ++I) {
10760 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010761 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010762
10763 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10764 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010765}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010766
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010767namespace {
10768 /// \brief AST visitor that finds references to the 'this' expression.
10769 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
10770 Sema &S;
10771
10772 public:
10773 explicit FindCXXThisExpr(Sema &S) : S(S) { }
10774
10775 bool VisitCXXThisExpr(CXXThisExpr *E) {
10776 S.Diag(E->getLocation(), diag::err_this_static_member_func)
10777 << E->isImplicit();
10778 return false;
10779 }
10780 };
10781}
10782
10783bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
10784 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10785 if (!TSInfo)
10786 return false;
10787
10788 TypeLoc TL = TSInfo->getTypeLoc();
10789 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10790 if (!ProtoTL)
10791 return false;
10792
10793 // C++11 [expr.prim.general]p3:
10794 // [The expression this] shall not appear before the optional
10795 // cv-qualifier-seq and it shall not appear within the declaration of a
10796 // static member function (although its type and value category are defined
10797 // within a static member function as they are within a non-static member
10798 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000010799 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010800 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10801 FindCXXThisExpr Finder(*this);
10802
10803 // If the return type came after the cv-qualifier-seq, check it now.
10804 if (Proto->hasTrailingReturn() &&
10805 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
10806 return true;
10807
10808 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010809 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
10810 return true;
10811
10812 return checkThisInStaticMemberFunctionAttributes(Method);
10813}
10814
10815bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
10816 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10817 if (!TSInfo)
10818 return false;
10819
10820 TypeLoc TL = TSInfo->getTypeLoc();
10821 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10822 if (!ProtoTL)
10823 return false;
10824
10825 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10826 FindCXXThisExpr Finder(*this);
10827
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010828 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000010829 case EST_Uninstantiated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010830 case EST_BasicNoexcept:
10831 case EST_Delayed:
10832 case EST_DynamicNone:
10833 case EST_MSAny:
10834 case EST_None:
10835 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010836
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010837 case EST_ComputedNoexcept:
10838 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
10839 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010840
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010841 case EST_Dynamic:
10842 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010843 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010844 E != EEnd; ++E) {
10845 if (!Finder.TraverseType(*E))
10846 return true;
10847 }
10848 break;
10849 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010850
10851 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000010852}
10853
10854bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
10855 FindCXXThisExpr Finder(*this);
10856
10857 // Check attributes.
10858 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
10859 A != AEnd; ++A) {
10860 // FIXME: This should be emitted by tblgen.
10861 Expr *Arg = 0;
10862 ArrayRef<Expr *> Args;
10863 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
10864 Arg = G->getArg();
10865 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
10866 Arg = G->getArg();
10867 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
10868 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
10869 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
10870 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
10871 else if (ExclusiveLockFunctionAttr *ELF
10872 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
10873 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
10874 else if (SharedLockFunctionAttr *SLF
10875 = dyn_cast<SharedLockFunctionAttr>(*A))
10876 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
10877 else if (ExclusiveTrylockFunctionAttr *ETLF
10878 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
10879 Arg = ETLF->getSuccessValue();
10880 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
10881 } else if (SharedTrylockFunctionAttr *STLF
10882 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
10883 Arg = STLF->getSuccessValue();
10884 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
10885 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
10886 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
10887 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
10888 Arg = LR->getArg();
10889 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
10890 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
10891 else if (ExclusiveLocksRequiredAttr *ELR
10892 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
10893 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
10894 else if (SharedLocksRequiredAttr *SLR
10895 = dyn_cast<SharedLocksRequiredAttr>(*A))
10896 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
10897
10898 if (Arg && !Finder.TraverseStmt(Arg))
10899 return true;
10900
10901 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
10902 if (!Finder.TraverseStmt(Args[I]))
10903 return true;
10904 }
10905 }
10906
10907 return false;
10908}
10909
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010910void
10911Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
10912 ArrayRef<ParsedType> DynamicExceptions,
10913 ArrayRef<SourceRange> DynamicExceptionRanges,
10914 Expr *NoexceptExpr,
10915 llvm::SmallVectorImpl<QualType> &Exceptions,
10916 FunctionProtoType::ExtProtoInfo &EPI) {
10917 Exceptions.clear();
10918 EPI.ExceptionSpecType = EST;
10919 if (EST == EST_Dynamic) {
10920 Exceptions.reserve(DynamicExceptions.size());
10921 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
10922 // FIXME: Preserve type source info.
10923 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
10924
10925 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10926 collectUnexpandedParameterPacks(ET, Unexpanded);
10927 if (!Unexpanded.empty()) {
10928 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
10929 UPPC_ExceptionType,
10930 Unexpanded);
10931 continue;
10932 }
10933
10934 // Check that the type is valid for an exception spec, and
10935 // drop it if not.
10936 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
10937 Exceptions.push_back(ET);
10938 }
10939 EPI.NumExceptions = Exceptions.size();
10940 EPI.Exceptions = Exceptions.data();
10941 return;
10942 }
10943
10944 if (EST == EST_ComputedNoexcept) {
10945 // If an error occurred, there's no expression here.
10946 if (NoexceptExpr) {
10947 assert((NoexceptExpr->isTypeDependent() ||
10948 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
10949 Context.BoolTy) &&
10950 "Parser should have made sure that the expression is boolean");
10951 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
10952 EPI.ExceptionSpecType = EST_BasicNoexcept;
10953 return;
10954 }
10955
10956 if (!NoexceptExpr->isValueDependent())
10957 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010958 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000010959 /*AllowFold*/ false).take();
10960 EPI.NoexceptExpr = NoexceptExpr;
10961 }
10962 return;
10963 }
10964}
10965
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010966/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10967Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10968 // Implicitly declared functions (e.g. copy constructors) are
10969 // __host__ __device__
10970 if (D->isImplicit())
10971 return CFT_HostDevice;
10972
10973 if (D->hasAttr<CUDAGlobalAttr>())
10974 return CFT_Global;
10975
10976 if (D->hasAttr<CUDADeviceAttr>()) {
10977 if (D->hasAttr<CUDAHostAttr>())
10978 return CFT_HostDevice;
10979 else
10980 return CFT_Device;
10981 }
10982
10983 return CFT_Host;
10984}
10985
10986bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10987 CUDAFunctionTarget CalleeTarget) {
10988 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10989 // Callable from the device only."
10990 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10991 return true;
10992
10993 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10994 // Callable from the host only."
10995 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10996 // Callable from the host only."
10997 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10998 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10999 return true;
11000
11001 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11002 return true;
11003
11004 return false;
11005}