blob: b8ea85bea9614fe70429f0680bb7706ffd628aca [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000029#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000030#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000034#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000035#include "llvm/ADT/DenseSet.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.
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
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())
Mike Stump1eb44332009-09-09 15:08:12 +000098 return S->Diag(DRE->getSourceRange().getBegin(),
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.
111 return S->Diag(ThisE->getSourceRange().getBegin(),
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
Sean Hunt001cad92011-05-10 00:49:42 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000129 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
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>();
136
137 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
138
139 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000141 ClearExceptions();
142 ComputedEST = EST;
143 return;
144 }
145
Richard Smith7a614d82011-06-11 17:19:42 +0000146 // FIXME: If the call to this decl is using any of its default arguments, we
147 // need to search them for potentially-throwing calls.
148
Sean Hunt001cad92011-05-10 00:49:42 +0000149 // If this function has a basic noexcept, it doesn't affect the outcome.
150 if (EST == EST_BasicNoexcept)
151 return;
152
153 // If we have a throw-all spec at this point, ignore the function.
154 if (ComputedEST == EST_None)
155 return;
156
157 // If we're still at noexcept(true) and there's a nothrow() callee,
158 // change to that specification.
159 if (EST == EST_DynamicNone) {
160 if (ComputedEST == EST_BasicNoexcept)
161 ComputedEST = EST_DynamicNone;
162 return;
163 }
164
165 // Check out noexcept specs.
166 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000168 assert(NR != FunctionProtoType::NR_NoNoexcept &&
169 "Must have noexcept result for EST_ComputedNoexcept.");
170 assert(NR != FunctionProtoType::NR_Dependent &&
171 "Should not generate implicit declarations for dependent cases, "
172 "and don't know how to handle them anyway.");
173
174 // noexcept(false) -> no spec on the new function
175 if (NR == FunctionProtoType::NR_Throw) {
176 ClearExceptions();
177 ComputedEST = EST_None;
178 }
179 // noexcept(true) won't change anything either.
180 return;
181 }
182
183 assert(EST == EST_Dynamic && "EST case not considered earlier.");
184 assert(ComputedEST != EST_None &&
185 "Shouldn't collect exceptions when throw-all is guaranteed.");
186 ComputedEST = EST_Dynamic;
187 // Record the exceptions in this function's exception specification.
188 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
189 EEnd = Proto->exception_end();
190 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000192 Exceptions.push_back(*E);
193}
194
Richard Smith7a614d82011-06-11 17:19:42 +0000195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
196 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
197 return;
198
199 // FIXME:
200 //
201 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000202 // [An] implicit exception-specification specifies the type-id T if and
203 // only if T is allowed by the exception-specification of a function directly
204 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000205 // function it directly invokes allows all exceptions, and f shall allow no
206 // exceptions if every function it directly invokes allows no exceptions.
207 //
208 // Note in particular that if an implicit exception-specification is generated
209 // for a function containing a throw-expression, that specification can still
210 // be noexcept(true).
211 //
212 // Note also that 'directly invoked' is not defined in the standard, and there
213 // is no indication that we should only consider potentially-evaluated calls.
214 //
215 // Ultimately we should implement the intent of the standard: the exception
216 // specification should be the set of exceptions which can be thrown by the
217 // implicit definition. For now, we assume that any non-nothrow expression can
218 // throw any exception.
219
220 if (E->CanThrow(*Context))
221 ComputedEST = EST_None;
222}
223
Anders Carlssoned961f92009-08-25 02:29:20 +0000224bool
John McCall9ae2f072010-08-23 23:25:46 +0000225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000226 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000227 if (RequireCompleteType(Param->getLocation(), Param->getType(),
228 diag::err_typecheck_decl_incomplete_type)) {
229 Param->setInvalidDecl();
230 return true;
231 }
232
Anders Carlssoned961f92009-08-25 02:29:20 +0000233 // C++ [dcl.fct.default]p5
234 // A default argument expression is implicitly converted (clause
235 // 4) to the parameter type. The default argument expression has
236 // the same semantic constraints as the initializer expression in
237 // a declaration of a variable of the parameter type, using the
238 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000245 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000246 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000247 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000249
John McCallb4eb64d2010-10-08 02:01:28 +0000250 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000251 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Anders Carlssoned961f92009-08-25 02:29:20 +0000253 // Okay: add the default argument to the parameter
254 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000256 // We have already instantiated this parameter; provide each of the
257 // instantiations with the uninstantiated default argument.
258 UnparsedDefaultArgInstantiationsMap::iterator InstPos
259 = UnparsedDefaultArgInstantiations.find(Param);
260 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
261 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
262 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
263
264 // We're done tracking this parameter's instantiations.
265 UnparsedDefaultArgInstantiations.erase(InstPos);
266 }
267
Anders Carlsson9351c172009-08-25 03:18:48 +0000268 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000269}
270
Chris Lattner8123a952008-04-10 02:22:51 +0000271/// ActOnParamDefaultArgument - Check whether the default argument
272/// provided for a function parameter is well-formed. If so, attach it
273/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274void
John McCalld226f652010-08-21 09:40:31 +0000275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000276 Expr *DefaultArg) {
277 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000278 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
John McCalld226f652010-08-21 09:40:31 +0000280 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000281 UnparsedDefaultArgLocs.erase(Param);
282
Chris Lattner3d1cee32008-04-08 05:04:30 +0000283 // Default arguments are only permitted in C++
284 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 Diag(EqualLoc, diag::err_param_default_argument)
286 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000287 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 return;
289 }
290
Douglas Gregor6f526752010-12-16 08:48:57 +0000291 // Check for unexpanded parameter packs.
292 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
293 Param->setInvalidDecl();
294 return;
295 }
296
Anders Carlsson66e30672009-08-25 01:02:06 +0000297 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000300 Param->setInvalidDecl();
301 return;
302 }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCall9ae2f072010-08-23 23:25:46 +0000304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000305}
306
Douglas Gregor61366e92008-12-24 00:01:03 +0000307/// ActOnParamUnparsedDefaultArgument - We've seen a default
308/// argument for a function parameter, but we can't parse it yet
309/// because we're inside a class definition. Note that this default
310/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000312 SourceLocation EqualLoc,
313 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCalld226f652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000318 if (Param)
319 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlsson5e300d12009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000322}
323
Douglas Gregor72b505b2008-12-16 21:30:33 +0000324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000327 if (!param)
328 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCalld226f652010-08-21 09:40:31 +0000330 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlsson5e300d12009-06-12 16:51:40 +0000332 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Anders Carlsson5e300d12009-06-12 16:51:40 +0000334 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000335}
336
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337/// CheckExtraCXXDefaultArguments - Check for any extra default
338/// arguments in the declarator, which is not a function declaration
339/// or definition and therefore is not permitted to have default
340/// arguments. This routine should be invoked for every declarator
341/// that is not a function declaration or definition.
342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
343 // C++ [dcl.fct.default]p3
344 // A default argument expression shall be specified only in the
345 // parameter-declaration-clause of a function declaration or in a
346 // template-parameter (14.1). It shall not be specified for a
347 // parameter pack. If it is specified in a
348 // parameter-declaration-clause, it shall not occur within a
349 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000351 DeclaratorChunk &chunk = D.getTypeObject(i);
352 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000356 if (Param->hasUnparsedDefaultArg()) {
357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000358 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
359 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
360 delete Toks;
361 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000362 } else if (Param->getDefaultArg()) {
363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << Param->getDefaultArg()->getSourceRange();
365 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000366 }
367 }
368 }
369 }
370}
371
Chris Lattner3d1cee32008-04-08 05:04:30 +0000372// MergeCXXFunctionDecl - Merge two declarations of the same C++
373// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000374// type. Subroutine of MergeFunctionDecl. Returns true if there was an
375// error, false otherwise.
376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
377 bool Invalid = false;
378
Chris Lattner3d1cee32008-04-08 05:04:30 +0000379 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 // For non-template functions, default arguments can be added in
381 // later declarations of a function in the same
382 // scope. Declarations in different scopes have completely
383 // distinct sets of default arguments. That is, declarations in
384 // inner scopes do not acquire default arguments from
385 // declarations in outer scopes, and vice versa. In a given
386 // function declaration, all parameters subsequent to a
387 // parameter with a default argument shall have default
388 // arguments supplied in this or previous declarations. A
389 // default argument shall not be redefined by a later
390 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000391 //
392 // C++ [dcl.fct.default]p6:
393 // Except for member functions of class templates, the default arguments
394 // in a member function definition that appears outside of the class
395 // definition are added to the set of default arguments provided by the
396 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
398 ParmVarDecl *OldParam = Old->getParamDecl(p);
399 ParmVarDecl *NewParam = New->getParamDecl(p);
400
Douglas Gregor6cc15182009-09-11 18:44:32 +0000401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000402
Francois Pichet8d051e02011-04-10 03:03:52 +0000403 unsigned DiagDefaultParamID =
404 diag::err_param_default_argument_redefinition;
405
406 // MSVC accepts that default parameters be redefined for member functions
407 // of template class. The new default parameter's value is ignored.
408 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000409 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
411 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000412 // Merge the old default argument into the new parameter.
413 NewParam->setHasInheritedDefaultArg();
414 if (OldParam->hasUninstantiatedDefaultArg())
415 NewParam->setUninstantiatedDefaultArg(
416 OldParam->getUninstantiatedDefaultArg());
417 else
418 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000420 Invalid = false;
421 }
422 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000423
Francois Pichet8cf90492011-04-10 04:58:30 +0000424 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
425 // hint here. Alternatively, we could walk the type-source information
426 // for NewParam to find the last source location in the type... but it
427 // isn't worth the effort right now. This is the kind of test case that
428 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000429 // int f(int);
430 // void g(int (*fp)(int) = f);
431 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000432 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000433 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000434
435 // Look for the function declaration where the default argument was
436 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000437 for (FunctionDecl *Older = Old->getPreviousDecl();
438 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 if (!Older->getParamDecl(p)->hasDefaultArg())
440 break;
441
442 OldParam = Older->getParamDecl(p);
443 }
444
445 Diag(OldParam->getLocation(), diag::note_previous_definition)
446 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000447 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000448 // Merge the old default argument into the new parameter.
449 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000450 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000451 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000452 if (OldParam->hasUninstantiatedDefaultArg())
453 NewParam->setUninstantiatedDefaultArg(
454 OldParam->getUninstantiatedDefaultArg());
455 else
John McCall3d6c1782010-05-04 01:53:42 +0000456 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000457 } else if (NewParam->hasDefaultArg()) {
458 if (New->getDescribedFunctionTemplate()) {
459 // Paragraph 4, quoted above, only applies to non-template functions.
460 Diag(NewParam->getLocation(),
461 diag::err_param_default_argument_template_redecl)
462 << NewParam->getDefaultArgRange();
463 Diag(Old->getLocation(), diag::note_template_prev_declaration)
464 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000465 } else if (New->getTemplateSpecializationKind()
466 != TSK_ImplicitInstantiation &&
467 New->getTemplateSpecializationKind() != TSK_Undeclared) {
468 // C++ [temp.expr.spec]p21:
469 // Default function arguments shall not be specified in a declaration
470 // or a definition for one of the following explicit specializations:
471 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000472 // - the explicit specialization of a member function template;
473 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000474 // template where the class template specialization to which the
475 // member function specialization belongs is implicitly
476 // instantiated.
477 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
478 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
479 << New->getDeclName()
480 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000481 } else if (New->getDeclContext()->isDependentContext()) {
482 // C++ [dcl.fct.default]p6 (DR217):
483 // Default arguments for a member function of a class template shall
484 // be specified on the initial declaration of the member function
485 // within the class template.
486 //
487 // Reading the tea leaves a bit in DR217 and its reference to DR205
488 // leads me to the conclusion that one cannot add default function
489 // arguments for an out-of-line definition of a member function of a
490 // dependent type.
491 int WhichKind = 2;
492 if (CXXRecordDecl *Record
493 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
494 if (Record->getDescribedClassTemplate())
495 WhichKind = 0;
496 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
497 WhichKind = 1;
498 else
499 WhichKind = 2;
500 }
501
502 Diag(NewParam->getLocation(),
503 diag::err_param_default_argument_member_template_redecl)
504 << WhichKind
505 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000506 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
507 CXXSpecialMember NewSM = getSpecialMember(Ctor),
508 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
509 if (NewSM != OldSM) {
510 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
511 << NewParam->getDefaultArgRange() << NewSM;
512 Diag(Old->getLocation(), diag::note_previous_declaration_special)
513 << OldSM;
514 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000516 }
517 }
518
Richard Smith9f569cc2011-10-01 02:31:28 +0000519 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
520 // template has a constexpr specifier then all its declarations shall
521 // contain the constexpr specifier. [Note: An explicit specialization can
522 // differ from the template declaration with respect to the constexpr
523 // specifier. -- end note]
524 //
525 // FIXME: Don't reject changes in constexpr in explicit specializations.
526 if (New->isConstexpr() != Old->isConstexpr()) {
527 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
528 << New << New->isConstexpr();
529 Diag(Old->getLocation(), diag::note_previous_declaration);
530 Invalid = true;
531 }
532
Douglas Gregore13ad832010-02-12 07:32:17 +0000533 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000534 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000535
Douglas Gregorcda9c672009-02-16 17:45:42 +0000536 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000537}
538
Sebastian Redl60618fa2011-03-12 11:50:43 +0000539/// \brief Merge the exception specifications of two variable declarations.
540///
541/// This is called when there's a redeclaration of a VarDecl. The function
542/// checks if the redeclaration might have an exception specification and
543/// validates compatibility and merges the specs if necessary.
544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
545 // Shortcut if exceptions are disabled.
546 if (!getLangOptions().CXXExceptions)
547 return;
548
549 assert(Context.hasSameType(New->getType(), Old->getType()) &&
550 "Should only be called if types are otherwise the same.");
551
552 QualType NewType = New->getType();
553 QualType OldType = Old->getType();
554
555 // We're only interested in pointers and references to functions, as well
556 // as pointers to member functions.
557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
558 NewType = R->getPointeeType();
559 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
561 NewType = P->getPointeeType();
562 OldType = OldType->getAs<PointerType>()->getPointeeType();
563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
564 NewType = M->getPointeeType();
565 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
566 }
567
568 if (!NewType->isFunctionProtoType())
569 return;
570
571 // There's lots of special cases for functions. For function pointers, system
572 // libraries are hopefully not as broken so that we don't need these
573 // workarounds.
574 if (CheckEquivalentExceptionSpec(
575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
577 New->setInvalidDecl();
578 }
579}
580
Chris Lattner3d1cee32008-04-08 05:04:30 +0000581/// CheckCXXDefaultArguments - Verify that the default arguments for a
582/// function declaration are well-formed according to C++
583/// [dcl.fct.default].
584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
585 unsigned NumParams = FD->getNumParams();
586 unsigned p;
587
588 // Find first parameter with a default argument
589 for (p = 0; p < NumParams; ++p) {
590 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000591 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592 break;
593 }
594
595 // C++ [dcl.fct.default]p4:
596 // In a given function declaration, all parameters
597 // subsequent to a parameter with a default argument shall
598 // have default arguments supplied in this or previous
599 // declarations. A default argument shall not be redefined
600 // by a later declaration (not even to the same value).
601 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000602 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000604 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000605 if (Param->isInvalidDecl())
606 /* We already complained about this parameter. */;
607 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000608 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000609 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000610 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000611 else
Mike Stump1eb44332009-09-09 15:08:12 +0000612 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000613 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 LastMissingDefaultArg = p;
616 }
617 }
618
619 if (LastMissingDefaultArg > 0) {
620 // Some default arguments were missing. Clear out all of the
621 // default arguments up to (and including) the last missing
622 // default argument, so that we leave the function parameters
623 // in a semantically valid state.
624 for (p = 0; p <= LastMissingDefaultArg; ++p) {
625 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000626 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 Param->setDefaultArg(0);
628 }
629 }
630 }
631}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000632
Richard Smith9f569cc2011-10-01 02:31:28 +0000633// CheckConstexprParameterTypes - Check whether a function's parameter types
634// are all literal types. If so, return true. If not, produce a suitable
635// diagnostic depending on @p CCK and return false.
636static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
637 Sema::CheckConstexprKind CCK) {
638 unsigned ArgIndex = 0;
639 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
640 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
641 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
642 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
643 SourceLocation ParamLoc = PD->getLocation();
644 if (!(*i)->isDependentType() &&
645 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
646 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
647 << ArgIndex+1 << PD->getSourceRange()
648 << isa<CXXConstructorDecl>(FD) :
649 SemaRef.PDiag(),
650 /*AllowIncompleteType*/ true)) {
651 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
652 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
653 << ArgIndex+1 << PD->getSourceRange()
654 << isa<CXXConstructorDecl>(FD) << *i;
655 return false;
656 }
657 }
658 return true;
659}
660
661// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
662// the requirements of a constexpr function declaration or a constexpr
663// constructor declaration. Return true if it does, false if not.
664//
Richard Smith35340502012-01-13 04:54:00 +0000665// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000666//
667// \param CCK Specifies whether to produce diagnostics if the function does not
668// satisfy the requirements.
669bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
670 CheckConstexprKind CCK) {
671 assert((CCK != CCK_NoteNonConstexprInstantiation ||
672 (NewFD->getTemplateInstantiationPattern() &&
673 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
674 "only constexpr templates can be instantiated non-constexpr");
675
Richard Smith35340502012-01-13 04:54:00 +0000676 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
677 if (MD && MD->isInstance()) {
678 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000679 // In addition, either its function-body shall be = delete or = default or
680 // it shall satisfy the following constraints:
681 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000682 //
683 // We apply this to constexpr member functions too: the class cannot be a
684 // literal type, so the members are not permitted to be constexpr.
685 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000686 if (RD->getNumVBases()) {
687 // Note, this is still illegal if the body is = default, since the
688 // implicit body does not satisfy the requirements of a constexpr
689 // constructor. We also reject cases where the body is = delete, as
690 // required by N3308.
691 if (CCK != CCK_Instantiation) {
692 Diag(NewFD->getLocation(),
693 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
694 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698 E = RD->vbases_end(); I != E; ++I)
699 Diag(I->getSourceRange().getBegin(),
700 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
701 }
702 return false;
703 }
Richard Smith35340502012-01-13 04:54:00 +0000704 }
705
706 if (!isa<CXXConstructorDecl>(NewFD)) {
707 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000708 // The definition of a constexpr function shall satisfy the following
709 // constraints:
710 // - it shall not be virtual;
711 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
712 if (Method && Method->isVirtual()) {
713 if (CCK != CCK_Instantiation) {
714 Diag(NewFD->getLocation(),
715 CCK == CCK_Declaration ? diag::err_constexpr_virtual
716 : diag::note_constexpr_tmpl_virtual);
717
718 // If it's not obvious why this function is virtual, find an overridden
719 // function which uses the 'virtual' keyword.
720 const CXXMethodDecl *WrittenVirtual = Method;
721 while (!WrittenVirtual->isVirtualAsWritten())
722 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
723 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000724 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000725 diag::note_overridden_virtual_function);
726 }
727 return false;
728 }
729
730 // - its return type shall be a literal type;
731 QualType RT = NewFD->getResultType();
732 if (!RT->isDependentType() &&
733 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
734 PDiag(diag::err_constexpr_non_literal_return) :
735 PDiag(),
736 /*AllowIncompleteType*/ true)) {
737 if (CCK == CCK_NoteNonConstexprInstantiation)
738 Diag(NewFD->getLocation(),
739 diag::note_constexpr_tmpl_non_literal_return) << RT;
740 return false;
741 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 }
743
Richard Smith35340502012-01-13 04:54:00 +0000744 // - each of its parameter types shall be a literal type;
745 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
746 return false;
747
Richard Smith9f569cc2011-10-01 02:31:28 +0000748 return true;
749}
750
751/// Check the given declaration statement is legal within a constexpr function
752/// body. C++0x [dcl.constexpr]p3,p4.
753///
754/// \return true if the body is OK, false if we have diagnosed a problem.
755static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
756 DeclStmt *DS) {
757 // C++0x [dcl.constexpr]p3 and p4:
758 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
759 // contain only
760 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
761 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
762 switch ((*DclIt)->getKind()) {
763 case Decl::StaticAssert:
764 case Decl::Using:
765 case Decl::UsingShadow:
766 case Decl::UsingDirective:
767 case Decl::UnresolvedUsingTypename:
768 // - static_assert-declarations
769 // - using-declarations,
770 // - using-directives,
771 continue;
772
773 case Decl::Typedef:
774 case Decl::TypeAlias: {
775 // - typedef declarations and alias-declarations that do not define
776 // classes or enumerations,
777 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
778 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
779 // Don't allow variably-modified types in constexpr functions.
780 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
781 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
782 << TL.getSourceRange() << TL.getType()
783 << isa<CXXConstructorDecl>(Dcl);
784 return false;
785 }
786 continue;
787 }
788
789 case Decl::Enum:
790 case Decl::CXXRecord:
791 // As an extension, we allow the declaration (but not the definition) of
792 // classes and enumerations in all declarations, not just in typedef and
793 // alias declarations.
794 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 continue;
800
801 case Decl::Var:
802 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
803 << isa<CXXConstructorDecl>(Dcl);
804 return false;
805
806 default:
807 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
808 << isa<CXXConstructorDecl>(Dcl);
809 return false;
810 }
811 }
812
813 return true;
814}
815
816/// Check that the given field is initialized within a constexpr constructor.
817///
818/// \param Dcl The constexpr constructor being checked.
819/// \param Field The field being checked. This may be a member of an anonymous
820/// struct or union nested within the class being checked.
821/// \param Inits All declarations, including anonymous struct/union members and
822/// indirect members, for which any initialization was provided.
823/// \param Diagnosed Set to true if an error is produced.
824static void CheckConstexprCtorInitializer(Sema &SemaRef,
825 const FunctionDecl *Dcl,
826 FieldDecl *Field,
827 llvm::SmallSet<Decl*, 16> &Inits,
828 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000829 if (Field->isUnnamedBitfield())
830 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000831
832 if (Field->isAnonymousStructOrUnion() &&
833 Field->getType()->getAsCXXRecordDecl()->isEmpty())
834 return;
835
Richard Smith9f569cc2011-10-01 02:31:28 +0000836 if (!Inits.count(Field)) {
837 if (!Diagnosed) {
838 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
839 Diagnosed = true;
840 }
841 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
842 } else if (Field->isAnonymousStructOrUnion()) {
843 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
844 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
845 I != E; ++I)
846 // If an anonymous union contains an anonymous struct of which any member
847 // is initialized, all members must be initialized.
848 if (!RD->isUnion() || Inits.count(*I))
849 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
850 }
851}
852
853/// Check the body for the given constexpr function declaration only contains
854/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
855///
856/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smithd79093a2012-02-05 02:30:54 +0000857bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
858 bool IsInstantiation) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000859 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000860 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000861 // The definition of a constexpr function shall satisfy the following
862 // constraints: [...]
863 // - its function-body shall be = delete, = default, or a
864 // compound-statement
865 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000866 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000867 // In the definition of a constexpr constructor, [...]
868 // - its function-body shall not be a function-try-block;
869 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
870 << isa<CXXConstructorDecl>(Dcl);
871 return false;
872 }
873
874 // - its function-body shall be [...] a compound-statement that contains only
875 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
876
877 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
878 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
879 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
880 switch ((*BodyIt)->getStmtClass()) {
881 case Stmt::NullStmtClass:
882 // - null statements,
883 continue;
884
885 case Stmt::DeclStmtClass:
886 // - static_assert-declarations
887 // - using-declarations,
888 // - using-directives,
889 // - typedef declarations and alias-declarations that do not define
890 // classes or enumerations,
891 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
892 return false;
893 continue;
894
895 case Stmt::ReturnStmtClass:
896 // - and exactly one return statement;
897 if (isa<CXXConstructorDecl>(Dcl))
898 break;
899
900 ReturnStmts.push_back((*BodyIt)->getLocStart());
901 // FIXME
902 // - every constructor call and implicit conversion used in initializing
903 // the return value shall be one of those allowed in a constant
904 // expression.
905 // Deal with this as part of a general check that the function can produce
906 // a constant expression (for [dcl.constexpr]p5).
907 continue;
908
909 default:
910 break;
911 }
912
913 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917
918 if (const CXXConstructorDecl *Constructor
919 = dyn_cast<CXXConstructorDecl>(Dcl)) {
920 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000921 // DR1359:
922 // - every non-variant non-static data member and base class sub-object
923 // shall be initialized;
924 // - if the class is a non-empty union, or for each non-empty anonymous
925 // union member of a non-union class, exactly one non-static data member
926 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000927 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000928 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
930 return false;
931 }
Richard Smith6e433752011-10-10 16:38:04 +0000932 } else if (!Constructor->isDependentContext() &&
933 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000934 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
935
936 // Skip detailed checking if we have enough initializers, and we would
937 // allow at most one initializer per member.
938 bool AnyAnonStructUnionMembers = false;
939 unsigned Fields = 0;
940 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941 E = RD->field_end(); I != E; ++I, ++Fields) {
942 if ((*I)->isAnonymousStructOrUnion()) {
943 AnyAnonStructUnionMembers = true;
944 break;
945 }
946 }
947 if (AnyAnonStructUnionMembers ||
948 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
949 // Check initialization of non-static data members. Base classes are
950 // always initialized so do not need to be checked. Dependent bases
951 // might not have initializers in the member initializer list.
952 llvm::SmallSet<Decl*, 16> Inits;
953 for (CXXConstructorDecl::init_const_iterator
954 I = Constructor->init_begin(), E = Constructor->init_end();
955 I != E; ++I) {
956 if (FieldDecl *FD = (*I)->getMember())
957 Inits.insert(FD);
958 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
959 Inits.insert(ID->chain_begin(), ID->chain_end());
960 }
961
962 bool Diagnosed = false;
963 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
964 E = RD->field_end(); I != E; ++I)
965 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
966 if (Diagnosed)
967 return false;
968 }
969 }
970
971 // FIXME
972 // - every constructor involved in initializing non-static data members
973 // and base class sub-objects shall be a constexpr constructor;
974 // - every assignment-expression that is an initializer-clause appearing
975 // directly or indirectly within a brace-or-equal-initializer for
976 // a non-static data member that is not named by a mem-initializer-id
977 // shall be a constant expression; and
978 // - every implicit conversion used in converting a constructor argument
979 // to the corresponding parameter type and converting
980 // a full-expression to the corresponding member type shall be one of
981 // those allowed in a constant expression.
982 // Deal with these as part of a general check that the function can produce
983 // a constant expression (for [dcl.constexpr]p5).
984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
Richard Smith5ba73e12012-02-04 00:33:54 +0000997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +00001007 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith925d8e72012-02-08 06:14:53 +00001008 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +00001009 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
1010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
1013 return false;
1014 }
1015
Richard Smith9f569cc2011-10-01 02:31:28 +00001016 return true;
1017}
1018
Douglas Gregorb48fe382008-10-31 09:07:45 +00001019/// isCurrentClassName - Determine whether the identifier II is the
1020/// name of the class type currently being defined. In the case of
1021/// nested classes, this will only return true if II is the name of
1022/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001023bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1024 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001025 assert(getLangOptions().CPlusPlus && "No class names in C!");
1026
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001027 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001028 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001029 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001030 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1031 } else
1032 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1033
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001034 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001035 return &II == CurDecl->getIdentifier();
1036 else
1037 return false;
1038}
1039
Mike Stump1eb44332009-09-09 15:08:12 +00001040/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041///
1042/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1043/// and returns NULL otherwise.
1044CXXBaseSpecifier *
1045Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1046 SourceRange SpecifierRange,
1047 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001048 TypeSourceInfo *TInfo,
1049 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001050 QualType BaseType = TInfo->getType();
1051
Douglas Gregor2943aed2009-03-03 04:44:36 +00001052 // C++ [class.union]p1:
1053 // A union shall not have base classes.
1054 if (Class->isUnion()) {
1055 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1056 << SpecifierRange;
1057 return 0;
1058 }
1059
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001060 if (EllipsisLoc.isValid() &&
1061 !TInfo->getType()->containsUnexpandedParameterPack()) {
1062 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1063 << TInfo->getTypeLoc().getSourceRange();
1064 EllipsisLoc = SourceLocation();
1065 }
1066
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001068 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001069 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001070 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001071
1072 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001073
1074 // Base specifiers must be record types.
1075 if (!BaseType->isRecordType()) {
1076 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1077 return 0;
1078 }
1079
1080 // C++ [class.union]p1:
1081 // A union shall not be used as a base class.
1082 if (BaseType->isUnionType()) {
1083 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1084 return 0;
1085 }
1086
1087 // C++ [class.derived]p2:
1088 // The class-name in a base-specifier shall not be an incompletely
1089 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001090 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001091 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001092 << SpecifierRange)) {
1093 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001094 return 0;
John McCall572fc622010-08-17 07:23:57 +00001095 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001096
Eli Friedman1d954f62009-08-15 21:55:26 +00001097 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001098 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001099 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001100 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001101 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001102 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1103 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001104
Anders Carlsson1d209272011-03-25 14:55:14 +00001105 // C++ [class]p3:
1106 // If a class is marked final and it appears as a base-type-specifier in
1107 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001108 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001109 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1110 << CXXBaseDecl->getDeclName();
1111 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1112 << CXXBaseDecl->getDeclName();
1113 return 0;
1114 }
1115
John McCall572fc622010-08-17 07:23:57 +00001116 if (BaseDecl->isInvalidDecl())
1117 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001118
1119 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001120 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001121 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001122 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001123}
1124
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001125/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1126/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001127/// example:
1128/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001129/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001130BaseResult
John McCalld226f652010-08-21 09:40:31 +00001131Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001133 ParsedType basetype, SourceLocation BaseLoc,
1134 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001135 if (!classdecl)
1136 return true;
1137
Douglas Gregor40808ce2009-03-09 23:48:35 +00001138 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001139 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001140 if (!Class)
1141 return true;
1142
Nick Lewycky56062202010-07-26 16:56:01 +00001143 TypeSourceInfo *TInfo = 0;
1144 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001145
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001146 if (EllipsisLoc.isInvalid() &&
1147 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001148 UPPC_BaseType))
1149 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001150
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001152 Virtual, Access, TInfo,
1153 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001157}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001158
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159/// \brief Performs the actual work of attaching the given base class
1160/// specifiers to a C++ class.
1161bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1162 unsigned NumBases) {
1163 if (NumBases == 0)
1164 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001165
1166 // Used to keep track of which base types we have already seen, so
1167 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001168 // that the key is always the unqualified canonical type of the base
1169 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001170 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1171
1172 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001173 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001175 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001176 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001177 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001178 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001179 if (KnownBaseTypes[NewBaseType]) {
1180 // C++ [class.mi]p3:
1181 // A class shall not be specified as a direct base class of a
1182 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001183 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001184 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001185 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001186 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001187
1188 // Delete the duplicate base class specifier; we're going to
1189 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001190 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001191
1192 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001193 } else {
1194 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195 KnownBaseTypes[NewBaseType] = Bases[idx];
1196 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001197 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001198 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1199 if (RD->hasAttr<WeakAttr>())
1200 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001201 }
1202 }
1203
1204 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001205 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001206
1207 // Delete the remaining (good) base class specifiers, since their
1208 // data has been copied into the CXXRecordDecl.
1209 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001210 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001211
1212 return Invalid;
1213}
1214
1215/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1216/// class, after checking whether there are any duplicate base
1217/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001218void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001219 unsigned NumBases) {
1220 if (!ClassDecl || !Bases || !NumBases)
1221 return;
1222
1223 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001224 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001225 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001226}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001227
John McCall3cb0ebd2010-03-10 03:28:59 +00001228static CXXRecordDecl *GetClassForType(QualType T) {
1229 if (const RecordType *RT = T->getAs<RecordType>())
1230 return cast<CXXRecordDecl>(RT->getDecl());
1231 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1232 return ICT->getDecl();
1233 else
1234 return 0;
1235}
1236
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237/// \brief Determine whether the type \p Derived is a C++ class that is
1238/// derived from the type \p Base.
1239bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1240 if (!getLangOptions().CPlusPlus)
1241 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001242
1243 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1244 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001245 return false;
1246
John McCall3cb0ebd2010-03-10 03:28:59 +00001247 CXXRecordDecl *BaseRD = GetClassForType(Base);
1248 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001249 return false;
1250
John McCall86ff3082010-02-04 22:26:26 +00001251 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1252 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253}
1254
1255/// \brief Determine whether the type \p Derived is a C++ class that is
1256/// derived from the type \p Base.
1257bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1258 if (!getLangOptions().CPlusPlus)
1259 return false;
1260
John McCall3cb0ebd2010-03-10 03:28:59 +00001261 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1262 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001263 return false;
1264
John McCall3cb0ebd2010-03-10 03:28:59 +00001265 CXXRecordDecl *BaseRD = GetClassForType(Base);
1266 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001267 return false;
1268
Douglas Gregora8f32e02009-10-06 17:59:45 +00001269 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1270}
1271
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001272void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001273 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001274 assert(BasePathArray.empty() && "Base path array must be empty!");
1275 assert(Paths.isRecordingPaths() && "Must record paths!");
1276
1277 const CXXBasePath &Path = Paths.front();
1278
1279 // We first go backward and check if we have a virtual base.
1280 // FIXME: It would be better if CXXBasePath had the base specifier for
1281 // the nearest virtual base.
1282 unsigned Start = 0;
1283 for (unsigned I = Path.size(); I != 0; --I) {
1284 if (Path[I - 1].Base->isVirtual()) {
1285 Start = I - 1;
1286 break;
1287 }
1288 }
1289
1290 // Now add all bases.
1291 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001292 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001293}
1294
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001295/// \brief Determine whether the given base path includes a virtual
1296/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001297bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1298 for (CXXCastPath::const_iterator B = BasePath.begin(),
1299 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001300 B != BEnd; ++B)
1301 if ((*B)->isVirtual())
1302 return true;
1303
1304 return false;
1305}
1306
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1308/// conversion (where Derived and Base are class types) is
1309/// well-formed, meaning that the conversion is unambiguous (and
1310/// that all of the base classes are accessible). Returns true
1311/// and emits a diagnostic if the code is ill-formed, returns false
1312/// otherwise. Loc is the location where this routine should point to
1313/// if there is an error, and Range is the source range to highlight
1314/// if there is an error.
1315bool
1316Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001317 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001318 unsigned AmbigiousBaseConvID,
1319 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001320 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001321 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 // First, determine whether the path from Derived to Base is
1323 // ambiguous. This is slightly more expensive than checking whether
1324 // the Derived to Base conversion exists, because here we need to
1325 // explore multiple paths to determine if there is an ambiguity.
1326 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1327 /*DetectVirtual=*/false);
1328 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1329 assert(DerivationOkay &&
1330 "Can only be used with a derived-to-base conversion");
1331 (void)DerivationOkay;
1332
1333 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001334 if (InaccessibleBaseID) {
1335 // Check that the base class can be accessed.
1336 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1337 InaccessibleBaseID)) {
1338 case AR_inaccessible:
1339 return true;
1340 case AR_accessible:
1341 case AR_dependent:
1342 case AR_delayed:
1343 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001344 }
John McCall6b2accb2010-02-10 09:31:12 +00001345 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001346
1347 // Build a base path if necessary.
1348 if (BasePath)
1349 BuildBasePathArray(Paths, *BasePath);
1350 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351 }
1352
1353 // We know that the derived-to-base conversion is ambiguous, and
1354 // we're going to produce a diagnostic. Perform the derived-to-base
1355 // search just one more time to compute all of the possible paths so
1356 // that we can print them out. This is more expensive than any of
1357 // the previous derived-to-base checks we've done, but at this point
1358 // performance isn't as much of an issue.
1359 Paths.clear();
1360 Paths.setRecordingPaths(true);
1361 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1362 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1363 (void)StillOkay;
1364
1365 // Build up a textual representation of the ambiguous paths, e.g.,
1366 // D -> B -> A, that will be used to illustrate the ambiguous
1367 // conversions in the diagnostic. We only print one of the paths
1368 // to each base class subobject.
1369 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1370
1371 Diag(Loc, AmbigiousBaseConvID)
1372 << Derived << Base << PathDisplayStr << Range << Name;
1373 return true;
1374}
1375
1376bool
1377Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001378 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001379 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001380 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001381 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001382 IgnoreAccess ? 0
1383 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001384 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001385 Loc, Range, DeclarationName(),
1386 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001387}
1388
1389
1390/// @brief Builds a string representing ambiguous paths from a
1391/// specific derived class to different subobjects of the same base
1392/// class.
1393///
1394/// This function builds a string that can be used in error messages
1395/// to show the different paths that one can take through the
1396/// inheritance hierarchy to go from the derived class to different
1397/// subobjects of a base class. The result looks something like this:
1398/// @code
1399/// struct D -> struct B -> struct A
1400/// struct D -> struct C -> struct A
1401/// @endcode
1402std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1403 std::string PathDisplayStr;
1404 std::set<unsigned> DisplayedPaths;
1405 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1406 Path != Paths.end(); ++Path) {
1407 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1408 // We haven't displayed a path to this particular base
1409 // class subobject yet.
1410 PathDisplayStr += "\n ";
1411 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1412 for (CXXBasePath::const_iterator Element = Path->begin();
1413 Element != Path->end(); ++Element)
1414 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1415 }
1416 }
1417
1418 return PathDisplayStr;
1419}
1420
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001421//===----------------------------------------------------------------------===//
1422// C++ class member Handling
1423//===----------------------------------------------------------------------===//
1424
Abramo Bagnara6206d532010-06-05 05:09:32 +00001425/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001426bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1427 SourceLocation ASLoc,
1428 SourceLocation ColonLoc,
1429 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001430 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001431 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001432 ASLoc, ColonLoc);
1433 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001434 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001435}
1436
Anders Carlsson9e682d92011-01-20 05:57:14 +00001437/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001438void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001440 if (!MD || !MD->isVirtual())
1441 return;
1442
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001443 if (MD->isDependentContext())
1444 return;
1445
Anders Carlsson9e682d92011-01-20 05:57:14 +00001446 // C++0x [class.virtual]p3:
1447 // If a virtual function is marked with the virt-specifier override and does
1448 // not override a member function of a base class,
1449 // the program is ill-formed.
1450 bool HasOverriddenMethods =
1451 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001452 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001453 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001454 diag::err_function_marked_override_not_overriding)
1455 << MD->getDeclName();
1456 return;
1457 }
1458}
1459
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001460/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1461/// function overrides a virtual member function marked 'final', according to
1462/// C++0x [class.virtual]p3.
1463bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1464 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001465 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001466 return false;
1467
1468 Diag(New->getLocation(), diag::err_final_function_overridden)
1469 << New->getDeclName();
1470 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1471 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001472}
1473
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001474/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1475/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001476/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1477/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1478/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001479Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001480Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001481 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001482 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001483 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001484 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001485 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1486 DeclarationName Name = NameInfo.getName();
1487 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001488
1489 // For anonymous bitfields, the location should point to the type.
1490 if (Loc.isInvalid())
1491 Loc = D.getSourceRange().getBegin();
1492
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001493 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001494
John McCall4bde1e12010-06-04 08:34:12 +00001495 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001496 assert(!DS.isFriendSpecified());
1497
Richard Smith1ab0d902011-06-25 02:28:38 +00001498 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001499
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001500 // C++ 9.2p6: A member shall not be declared to have automatic storage
1501 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001502 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1503 // data members and cannot be applied to names declared const or static,
1504 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001505 switch (DS.getStorageClassSpec()) {
1506 case DeclSpec::SCS_unspecified:
1507 case DeclSpec::SCS_typedef:
1508 case DeclSpec::SCS_static:
1509 // FALL THROUGH.
1510 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001511 case DeclSpec::SCS_mutable:
1512 if (isFunc) {
1513 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001515 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001516 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Sebastian Redla11f42f2008-11-17 23:24:37 +00001518 // FIXME: It would be nicer if the keyword was ignored only for this
1519 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001520 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001521 }
1522 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001523 default:
1524 if (DS.getStorageClassSpecLoc().isValid())
1525 Diag(DS.getStorageClassSpecLoc(),
1526 diag::err_storageclass_invalid_for_member);
1527 else
1528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1529 D.getMutableDeclSpec().ClearStorageClassSpecs();
1530 }
1531
Sebastian Redl669d5d72008-11-14 23:42:31 +00001532 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1533 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001534 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001535
1536 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001537 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001538 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001539
1540 // Data members must have identifiers for names.
1541 if (Name.getNameKind() != DeclarationName::Identifier) {
1542 Diag(Loc, diag::err_bad_variable_name)
1543 << Name;
1544 return 0;
1545 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001546
Douglas Gregorf2503652011-09-21 14:40:46 +00001547 IdentifierInfo *II = Name.getAsIdentifierInfo();
1548
1549 // Member field could not be with "template" keyword.
1550 // So TemplateParameterLists should be empty in this case.
1551 if (TemplateParameterLists.size()) {
1552 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1553 if (TemplateParams->size()) {
1554 // There is no such thing as a member field template.
1555 Diag(D.getIdentifierLoc(), diag::err_template_member)
1556 << II
1557 << SourceRange(TemplateParams->getTemplateLoc(),
1558 TemplateParams->getRAngleLoc());
1559 } else {
1560 // There is an extraneous 'template<>' for this member.
1561 Diag(TemplateParams->getTemplateLoc(),
1562 diag::err_template_member_noparams)
1563 << II
1564 << SourceRange(TemplateParams->getTemplateLoc(),
1565 TemplateParams->getRAngleLoc());
1566 }
1567 return 0;
1568 }
1569
Douglas Gregor922fff22010-10-13 22:19:53 +00001570 if (SS.isSet() && !SS.isInvalid()) {
1571 // The user provided a superfluous scope specifier inside a class
1572 // definition:
1573 //
1574 // class X {
1575 // int X::member;
1576 // };
1577 DeclContext *DC = 0;
1578 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1579 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001580 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001581 else
1582 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1583 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001584
Douglas Gregor922fff22010-10-13 22:19:53 +00001585 SS.clear();
1586 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001587
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001588 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001589 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001590 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001591 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001592 assert(!HasDeferredInit);
1593
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001594 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001595 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001596 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001597 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001598
1599 // Non-instance-fields can't have a bitfield.
1600 if (BitWidth) {
1601 if (Member->isInvalidDecl()) {
1602 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001603 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001604 // C++ 9.6p3: A bit-field shall not be a static member.
1605 // "static member 'A' cannot be a bit-field"
1606 Diag(Loc, diag::err_static_not_bitfield)
1607 << Name << BitWidth->getSourceRange();
1608 } else if (isa<TypedefDecl>(Member)) {
1609 // "typedef member 'x' cannot be a bit-field"
1610 Diag(Loc, diag::err_typedef_not_bitfield)
1611 << Name << BitWidth->getSourceRange();
1612 } else {
1613 // A function typedef ("typedef int f(); f a;").
1614 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1615 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001616 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001617 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Chris Lattner8b963ef2009-03-05 23:01:03 +00001620 BitWidth = 0;
1621 Member->setInvalidDecl();
1622 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001623
1624 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor37b372b2009-08-20 22:52:58 +00001626 // If we have declared a member function template, set the access of the
1627 // templated declaration as well.
1628 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1629 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001630 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001631
Anders Carlssonaae5af22011-01-20 04:34:22 +00001632 if (VS.isOverrideSpecified()) {
1633 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1634 if (!MD || !MD->isVirtual()) {
1635 Diag(Member->getLocStart(),
1636 diag::override_keyword_only_allowed_on_virtual_member_functions)
1637 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001638 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001639 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001640 }
1641 if (VS.isFinalSpecified()) {
1642 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1643 if (!MD || !MD->isVirtual()) {
1644 Diag(Member->getLocStart(),
1645 diag::override_keyword_only_allowed_on_virtual_member_functions)
1646 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001647 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001648 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001649 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001650
Douglas Gregorf5251602011-03-08 17:10:18 +00001651 if (VS.getLastLocation().isValid()) {
1652 // Update the end location of a method that has a virt-specifiers.
1653 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1654 MD->setRangeEnd(VS.getLastLocation());
1655 }
1656
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001657 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001658
Douglas Gregor10bd3682008-11-17 22:58:34 +00001659 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001660
John McCallb25b2952011-02-15 07:12:36 +00001661 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001662 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001663 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001664}
1665
Richard Smith7a614d82011-06-11 17:19:42 +00001666/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001667/// in-class initializer for a non-static C++ class member, and after
1668/// instantiating an in-class initializer in a class template. Such actions
1669/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001670void
1671Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1672 Expr *InitExpr) {
1673 FieldDecl *FD = cast<FieldDecl>(D);
1674
1675 if (!InitExpr) {
1676 FD->setInvalidDecl();
1677 FD->removeInClassInitializer();
1678 return;
1679 }
1680
Peter Collingbournefef21892011-10-23 18:59:44 +00001681 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1682 FD->setInvalidDecl();
1683 FD->removeInClassInitializer();
1684 return;
1685 }
1686
Richard Smith7a614d82011-06-11 17:19:42 +00001687 ExprResult Init = InitExpr;
1688 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1689 // FIXME: if there is no EqualLoc, this is list-initialization.
1690 Init = PerformCopyInitialization(
1691 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1692 if (Init.isInvalid()) {
1693 FD->setInvalidDecl();
1694 return;
1695 }
1696
1697 CheckImplicitConversions(Init.get(), EqualLoc);
1698 }
1699
1700 // C++0x [class.base.init]p7:
1701 // The initialization of each base and member constitutes a
1702 // full-expression.
1703 Init = MaybeCreateExprWithCleanups(Init);
1704 if (Init.isInvalid()) {
1705 FD->setInvalidDecl();
1706 return;
1707 }
1708
1709 InitExpr = Init.release();
1710
1711 FD->setInClassInitializer(InitExpr);
1712}
1713
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001714/// \brief Find the direct and/or virtual base specifiers that
1715/// correspond to the given base type, for use in base initialization
1716/// within a constructor.
1717static bool FindBaseInitializer(Sema &SemaRef,
1718 CXXRecordDecl *ClassDecl,
1719 QualType BaseType,
1720 const CXXBaseSpecifier *&DirectBaseSpec,
1721 const CXXBaseSpecifier *&VirtualBaseSpec) {
1722 // First, check for a direct base class.
1723 DirectBaseSpec = 0;
1724 for (CXXRecordDecl::base_class_const_iterator Base
1725 = ClassDecl->bases_begin();
1726 Base != ClassDecl->bases_end(); ++Base) {
1727 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1728 // We found a direct base of this type. That's what we're
1729 // initializing.
1730 DirectBaseSpec = &*Base;
1731 break;
1732 }
1733 }
1734
1735 // Check for a virtual base class.
1736 // FIXME: We might be able to short-circuit this if we know in advance that
1737 // there are no virtual bases.
1738 VirtualBaseSpec = 0;
1739 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1740 // We haven't found a base yet; search the class hierarchy for a
1741 // virtual base class.
1742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1743 /*DetectVirtual=*/false);
1744 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1745 BaseType, Paths)) {
1746 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1747 Path != Paths.end(); ++Path) {
1748 if (Path->back().Base->isVirtual()) {
1749 VirtualBaseSpec = Path->back().Base;
1750 break;
1751 }
1752 }
1753 }
1754 }
1755
1756 return DirectBaseSpec || VirtualBaseSpec;
1757}
1758
Sebastian Redl6df65482011-09-24 17:48:25 +00001759/// \brief Handle a C++ member initializer using braced-init-list syntax.
1760MemInitResult
1761Sema::ActOnMemInitializer(Decl *ConstructorD,
1762 Scope *S,
1763 CXXScopeSpec &SS,
1764 IdentifierInfo *MemberOrBase,
1765 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001766 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001767 SourceLocation IdLoc,
1768 Expr *InitList,
1769 SourceLocation EllipsisLoc) {
1770 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001771 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001772 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001773}
1774
1775/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001776MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001777Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001778 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001779 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001780 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001781 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001782 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001783 SourceLocation IdLoc,
1784 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001785 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001786 SourceLocation RParenLoc,
1787 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001788 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1789 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001790 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001791 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001792}
1793
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001794namespace {
1795
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001796// Callback to only accept typo corrections that can be a valid C++ member
1797// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001798class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1799 public:
1800 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1801 : ClassDecl(ClassDecl) {}
1802
1803 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1804 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1805 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1806 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1807 else
1808 return isa<TypeDecl>(ND);
1809 }
1810 return false;
1811 }
1812
1813 private:
1814 CXXRecordDecl *ClassDecl;
1815};
1816
1817}
1818
Sebastian Redl6df65482011-09-24 17:48:25 +00001819/// \brief Handle a C++ member initializer.
1820MemInitResult
1821Sema::BuildMemInitializer(Decl *ConstructorD,
1822 Scope *S,
1823 CXXScopeSpec &SS,
1824 IdentifierInfo *MemberOrBase,
1825 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001826 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001827 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001828 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001829 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001830 if (!ConstructorD)
1831 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001833 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
1835 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001836 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001837 if (!Constructor) {
1838 // The user wrote a constructor initializer on a function that is
1839 // not a C++ constructor. Ignore the error for now, because we may
1840 // have more member initializers coming; we'll diagnose it just
1841 // once in ActOnMemInitializers.
1842 return true;
1843 }
1844
1845 CXXRecordDecl *ClassDecl = Constructor->getParent();
1846
1847 // C++ [class.base.init]p2:
1848 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001849 // constructor's class and, if not found in that scope, are looked
1850 // up in the scope containing the constructor's definition.
1851 // [Note: if the constructor's class contains a member with the
1852 // same name as a direct or virtual base class of the class, a
1853 // mem-initializer-id naming the member or base class and composed
1854 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001855 // mem-initializer-id for the hidden base class may be specified
1856 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001857 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001858 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001859 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001860 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001861 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001862 ValueDecl *Member;
1863 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1864 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001865 if (EllipsisLoc.isValid())
1866 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001867 << MemberOrBase
1868 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001869
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001870 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001871 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001872 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001873 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001874 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001875 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001876 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001877
1878 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001879 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001880 } else if (DS.getTypeSpecType() == TST_decltype) {
1881 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001882 } else {
1883 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1884 LookupParsedName(R, S, &SS);
1885
1886 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1887 if (!TyD) {
1888 if (R.isAmbiguous()) return true;
1889
John McCallfd225442010-04-09 19:01:14 +00001890 // We don't want access-control diagnostics here.
1891 R.suppressDiagnostics();
1892
Douglas Gregor7a886e12010-01-19 06:46:48 +00001893 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1894 bool NotUnknownSpecialization = false;
1895 DeclContext *DC = computeDeclContext(SS, false);
1896 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1897 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1898
1899 if (!NotUnknownSpecialization) {
1900 // When the scope specifier can refer to a member of an unknown
1901 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001902 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1903 SS.getWithLocInContext(Context),
1904 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001905 if (BaseType.isNull())
1906 return true;
1907
Douglas Gregor7a886e12010-01-19 06:46:48 +00001908 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001909 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001910 }
1911 }
1912
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001913 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001914 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001915 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001916 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001917 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001918 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001919 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1920 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1921 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001922 // We have found a non-static data member with a similar
1923 // name to what was typed; complain and initialize that
1924 // member.
1925 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1926 << MemberOrBase << true << CorrectedQuotedStr
1927 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1928 Diag(Member->getLocation(), diag::note_previous_decl)
1929 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001930
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001931 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001932 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001933 const CXXBaseSpecifier *DirectBaseSpec;
1934 const CXXBaseSpecifier *VirtualBaseSpec;
1935 if (FindBaseInitializer(*this, ClassDecl,
1936 Context.getTypeDeclType(Type),
1937 DirectBaseSpec, VirtualBaseSpec)) {
1938 // We have found a direct or virtual base class with a
1939 // similar name to what was typed; complain and initialize
1940 // that base class.
1941 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001942 << MemberOrBase << false << CorrectedQuotedStr
1943 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001944
1945 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1946 : VirtualBaseSpec;
1947 Diag(BaseSpec->getSourceRange().getBegin(),
1948 diag::note_base_class_specified_here)
1949 << BaseSpec->getType()
1950 << BaseSpec->getSourceRange();
1951
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001952 TyD = Type;
1953 }
1954 }
1955 }
1956
Douglas Gregor7a886e12010-01-19 06:46:48 +00001957 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001958 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001959 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001960 return true;
1961 }
John McCall2b194412009-12-21 10:41:20 +00001962 }
1963
Douglas Gregor7a886e12010-01-19 06:46:48 +00001964 if (BaseType.isNull()) {
1965 BaseType = Context.getTypeDeclType(TyD);
1966 if (SS.isSet()) {
1967 NestedNameSpecifier *Qualifier =
1968 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001969
Douglas Gregor7a886e12010-01-19 06:46:48 +00001970 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001971 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001972 }
John McCall2b194412009-12-21 10:41:20 +00001973 }
1974 }
Mike Stump1eb44332009-09-09 15:08:12 +00001975
John McCalla93c9342009-12-07 02:54:59 +00001976 if (!TInfo)
1977 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001978
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001979 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001980}
1981
Chandler Carruth81c64772011-09-03 01:14:15 +00001982/// Checks a member initializer expression for cases where reference (or
1983/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001984static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1985 Expr *Init,
1986 SourceLocation IdLoc) {
1987 QualType MemberTy = Member->getType();
1988
1989 // We only handle pointers and references currently.
1990 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1991 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1992 return;
1993
1994 const bool IsPointer = MemberTy->isPointerType();
1995 if (IsPointer) {
1996 if (const UnaryOperator *Op
1997 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1998 // The only case we're worried about with pointers requires taking the
1999 // address.
2000 if (Op->getOpcode() != UO_AddrOf)
2001 return;
2002
2003 Init = Op->getSubExpr();
2004 } else {
2005 // We only handle address-of expression initializers for pointers.
2006 return;
2007 }
2008 }
2009
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002010 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2011 // Taking the address of a temporary will be diagnosed as a hard error.
2012 if (IsPointer)
2013 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002014
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002015 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2016 << Member << Init->getSourceRange();
2017 } else if (const DeclRefExpr *DRE
2018 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2019 // We only warn when referring to a non-reference parameter declaration.
2020 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2021 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002022 return;
2023
2024 S.Diag(Init->getExprLoc(),
2025 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2026 : diag::warn_bind_ref_member_to_parameter)
2027 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002028 } else {
2029 // Other initializers are fine.
2030 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002031 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002032
2033 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2034 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002035}
2036
John McCallb4190042009-11-04 23:02:40 +00002037/// Checks an initializer expression for use of uninitialized fields, such as
2038/// containing the field that is being initialized. Returns true if there is an
2039/// uninitialized field was used an updates the SourceLocation parameter; false
2040/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002041static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002042 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002043 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002044 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2045
Nick Lewycky43ad1822010-06-15 07:32:55 +00002046 if (isa<CallExpr>(S)) {
2047 // Do not descend into function calls or constructors, as the use
2048 // of an uninitialized field may be valid. One would have to inspect
2049 // the contents of the function/ctor to determine if it is safe or not.
2050 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2051 // may be safe, depending on what the function/ctor does.
2052 return false;
2053 }
2054 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2055 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002056
2057 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2058 // The member expression points to a static data member.
2059 assert(VD->isStaticDataMember() &&
2060 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002061 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002062 return false;
2063 }
2064
2065 if (isa<EnumConstantDecl>(RhsField)) {
2066 // The member expression points to an enum.
2067 return false;
2068 }
2069
John McCallb4190042009-11-04 23:02:40 +00002070 if (RhsField == LhsField) {
2071 // Initializing a field with itself. Throw a warning.
2072 // But wait; there are exceptions!
2073 // Exception #1: The field may not belong to this record.
2074 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002075 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002076 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2077 // Even though the field matches, it does not belong to this record.
2078 return false;
2079 }
2080 // None of the exceptions triggered; return true to indicate an
2081 // uninitialized field was used.
2082 *L = ME->getMemberLoc();
2083 return true;
2084 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002085 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002086 // sizeof/alignof doesn't reference contents, do not warn.
2087 return false;
2088 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2089 // address-of doesn't reference contents (the pointer may be dereferenced
2090 // in the same expression but it would be rare; and weird).
2091 if (UOE->getOpcode() == UO_AddrOf)
2092 return false;
John McCallb4190042009-11-04 23:02:40 +00002093 }
John McCall7502c1d2011-02-13 04:07:26 +00002094 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002095 if (!*it) {
2096 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002097 continue;
2098 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002099 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2100 return true;
John McCallb4190042009-11-04 23:02:40 +00002101 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002102 return false;
John McCallb4190042009-11-04 23:02:40 +00002103}
2104
John McCallf312b1e2010-08-26 23:41:50 +00002105MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002106Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002107 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002108 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2109 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2110 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002111 "Member must be a FieldDecl or IndirectFieldDecl");
2112
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002113 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002114 return true;
2115
Douglas Gregor464b2f02010-11-05 22:21:31 +00002116 if (Member->isInvalidDecl())
2117 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002118
John McCallb4190042009-11-04 23:02:40 +00002119 // Diagnose value-uses of fields to initialize themselves, e.g.
2120 // foo(foo)
2121 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002122 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002123 Expr **Args;
2124 unsigned NumArgs;
2125 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2126 Args = ParenList->getExprs();
2127 NumArgs = ParenList->getNumExprs();
2128 } else {
2129 InitListExpr *InitList = cast<InitListExpr>(Init);
2130 Args = InitList->getInits();
2131 NumArgs = InitList->getNumInits();
2132 }
2133 for (unsigned i = 0; i < NumArgs; ++i) {
John McCallb4190042009-11-04 23:02:40 +00002134 SourceLocation L;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002135 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002136 // FIXME: Return true in the case when other fields are used before being
2137 // uninitialized. For example, let this field be the i'th field. When
2138 // initializing the i'th field, throw a warning if any of the >= i'th
2139 // fields are used, as they are not yet initialized.
2140 // Right now we are only handling the case where the i'th field uses
2141 // itself in its initializer.
2142 Diag(L, diag::warn_field_is_uninit);
2143 }
2144 }
2145
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002146 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002147
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002148 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002149 // Can't check initialization for a member of dependent type or when
2150 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002151 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002152 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002153 bool InitList = false;
2154 if (isa<InitListExpr>(Init)) {
2155 InitList = true;
2156 Args = &Init;
2157 NumArgs = 1;
2158 }
2159
Chandler Carruth894aed92010-12-06 09:23:57 +00002160 // Initialize the member.
2161 InitializedEntity MemberEntity =
2162 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2163 : InitializedEntity::InitializeMember(IndirectMember, 0);
2164 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002165 InitList ? InitializationKind::CreateDirectList(IdLoc)
2166 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2167 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002168
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002169 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2170 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2171 MultiExprArg(*this, Args, NumArgs),
2172 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002173 if (MemberInit.isInvalid())
2174 return true;
2175
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002176 CheckImplicitConversions(MemberInit.get(),
2177 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002178
2179 // C++0x [class.base.init]p7:
2180 // The initialization of each base and member constitutes a
2181 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002182 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002183 if (MemberInit.isInvalid())
2184 return true;
2185
2186 // If we are in a dependent context, template instantiation will
2187 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002188 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002189 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2190 // of the information that we have about the member
2191 // initializer. However, deconstructing the ASTs is a dicey process,
2192 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002193 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002194 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002195 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002196 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002197 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2198 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002199 }
2200
Chandler Carruth894aed92010-12-06 09:23:57 +00002201 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002202 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2203 InitRange.getBegin(), Init,
2204 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002205 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002206 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2207 InitRange.getBegin(), Init,
2208 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002209 }
Eli Friedman59c04372009-07-29 19:44:27 +00002210}
2211
John McCallf312b1e2010-08-26 23:41:50 +00002212MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002213Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002214 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002215 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002216 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002217 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002218 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002219 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002220
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002221 bool InitList = true;
2222 Expr **Args = &Init;
2223 unsigned NumArgs = 1;
2224 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2225 InitList = false;
2226 Args = ParenList->getExprs();
2227 NumArgs = ParenList->getNumExprs();
2228 }
2229
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002230 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002231 // Initialize the object.
2232 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2233 QualType(ClassDecl->getTypeForDecl(), 0));
2234 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002235 InitList ? InitializationKind::CreateDirectList(NameLoc)
2236 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2237 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2239 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2240 MultiExprArg(*this, Args,NumArgs),
2241 0);
Sean Hunt41717662011-02-26 19:13:13 +00002242 if (DelegationInit.isInvalid())
2243 return true;
2244
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002245 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2246 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002247
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002248 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002249
2250 // C++0x [class.base.init]p7:
2251 // The initialization of each base and member constitutes a
2252 // full-expression.
2253 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2254 if (DelegationInit.isInvalid())
2255 return true;
2256
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002258 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002259 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002260}
2261
2262MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002263Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002264 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002265 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002266 SourceLocation BaseLoc
2267 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002268
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002269 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2270 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2271 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2272
2273 // C++ [class.base.init]p2:
2274 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002275 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002276 // of that class, the mem-initializer is ill-formed. A
2277 // mem-initializer-list can initialize a base class using any
2278 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002279 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002280
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002281 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002282 if (EllipsisLoc.isValid()) {
2283 // This is a pack expansion.
2284 if (!BaseType->containsUnexpandedParameterPack()) {
2285 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002287
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002288 EllipsisLoc = SourceLocation();
2289 }
2290 } else {
2291 // Check for any unexpanded parameter packs.
2292 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2293 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002294
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002295 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002296 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002297 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002298
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002299 // Check for direct and virtual base classes.
2300 const CXXBaseSpecifier *DirectBaseSpec = 0;
2301 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2302 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002303 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2304 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002306
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002307 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2308 VirtualBaseSpec);
2309
2310 // C++ [base.class.init]p2:
2311 // Unless the mem-initializer-id names a nonstatic data member of the
2312 // constructor's class or a direct or virtual base of that class, the
2313 // mem-initializer is ill-formed.
2314 if (!DirectBaseSpec && !VirtualBaseSpec) {
2315 // If the class has any dependent bases, then it's possible that
2316 // one of those types will resolve to the same type as
2317 // BaseType. Therefore, just treat this as a dependent base
2318 // class initialization. FIXME: Should we try to check the
2319 // initialization anyway? It seems odd.
2320 if (ClassDecl->hasAnyDependentBases())
2321 Dependent = true;
2322 else
2323 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2324 << BaseType << Context.getTypeDeclType(ClassDecl)
2325 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2326 }
2327 }
2328
2329 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002330 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Sebastian Redl6df65482011-09-24 17:48:25 +00002332 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2333 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 InitRange.getBegin(), Init,
2335 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002336 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002337
2338 // C++ [base.class.init]p2:
2339 // If a mem-initializer-id is ambiguous because it designates both
2340 // a direct non-virtual base class and an inherited virtual base
2341 // class, the mem-initializer is ill-formed.
2342 if (DirectBaseSpec && VirtualBaseSpec)
2343 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002344 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002345
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002346 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002347 if (!BaseSpec)
2348 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2349
2350 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002351 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002352 Expr **Args = &Init;
2353 unsigned NumArgs = 1;
2354 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002355 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002356 Args = ParenList->getExprs();
2357 NumArgs = ParenList->getNumExprs();
2358 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002359
2360 InitializedEntity BaseEntity =
2361 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2362 InitializationKind Kind =
2363 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2364 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2365 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2367 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2368 MultiExprArg(*this, Args, NumArgs),
2369 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002370 if (BaseInit.isInvalid())
2371 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002372
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002374
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002375 // C++0x [class.base.init]p7:
2376 // The initialization of each base and member constitutes a
2377 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002378 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002379 if (BaseInit.isInvalid())
2380 return true;
2381
2382 // If we are in a dependent context, template instantiation will
2383 // perform this type-checking again. Just save the arguments that we
2384 // received in a ParenListExpr.
2385 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2386 // of the information that we have about the base
2387 // initializer. However, deconstructing the ASTs is a dicey process,
2388 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002389 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002390 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002391
Sean Huntcbb67482011-01-08 20:30:50 +00002392 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002393 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002395 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002396 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002397}
2398
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002399// Create a static_cast\<T&&>(expr).
2400static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2401 QualType ExprType = E->getType();
2402 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2403 SourceLocation ExprLoc = E->getLocStart();
2404 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2405 TargetType, ExprLoc);
2406
2407 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2408 SourceRange(ExprLoc, ExprLoc),
2409 E->getSourceRange()).take();
2410}
2411
Anders Carlssone5ef7402010-04-23 03:10:23 +00002412/// ImplicitInitializerKind - How an implicit base or member initializer should
2413/// initialize its base or member.
2414enum ImplicitInitializerKind {
2415 IIK_Default,
2416 IIK_Copy,
2417 IIK_Move
2418};
2419
Anders Carlssondefefd22010-04-23 02:00:02 +00002420static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002421BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002422 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002423 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002424 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002425 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002426 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002427 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2428 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002429
John McCall60d7b3a2010-08-24 06:29:42 +00002430 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002431
2432 switch (ImplicitInitKind) {
2433 case IIK_Default: {
2434 InitializationKind InitKind
2435 = InitializationKind::CreateDefault(Constructor->getLocation());
2436 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2437 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002438 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002439 break;
2440 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002441
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002442 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002443 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002444 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002445 ParmVarDecl *Param = Constructor->getParamDecl(0);
2446 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002447
Anders Carlssone5ef7402010-04-23 03:10:23 +00002448 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002449 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2450 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002451 Constructor->getLocation(), ParamType,
2452 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002453
Eli Friedman5f2987c2012-02-02 03:46:19 +00002454 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2455
Anders Carlssonc7957502010-04-24 22:02:54 +00002456 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002457 QualType ArgTy =
2458 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2459 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002460
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002461 if (Moving) {
2462 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2463 }
2464
John McCallf871d0c2010-08-07 06:22:56 +00002465 CXXCastPath BasePath;
2466 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002467 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2468 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002469 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002470 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002471
Anders Carlssone5ef7402010-04-23 03:10:23 +00002472 InitializationKind InitKind
2473 = InitializationKind::CreateDirect(Constructor->getLocation(),
2474 SourceLocation(), SourceLocation());
2475 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2476 &CopyCtorArg, 1);
2477 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002478 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002479 break;
2480 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002481 }
John McCall9ae2f072010-08-23 23:25:46 +00002482
Douglas Gregor53c374f2010-12-07 00:41:46 +00002483 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002484 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002485 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002486
Anders Carlssondefefd22010-04-23 02:00:02 +00002487 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002488 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002489 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2490 SourceLocation()),
2491 BaseSpec->isVirtual(),
2492 SourceLocation(),
2493 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002494 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002495 SourceLocation());
2496
Anders Carlssondefefd22010-04-23 02:00:02 +00002497 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002498}
2499
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500static bool RefersToRValueRef(Expr *MemRef) {
2501 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2502 return Referenced->getType()->isRValueReferenceType();
2503}
2504
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002505static bool
2506BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002507 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002508 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002509 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002510 if (Field->isInvalidDecl())
2511 return true;
2512
Chandler Carruthf186b542010-06-29 23:50:44 +00002513 SourceLocation Loc = Constructor->getLocation();
2514
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002515 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2516 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002517 ParmVarDecl *Param = Constructor->getParamDecl(0);
2518 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002519
2520 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002521 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2522 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002523
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002524 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002525 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2526 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002527 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002528
Eli Friedman5f2987c2012-02-02 03:46:19 +00002529 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2530
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002531 if (Moving) {
2532 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2533 }
2534
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002535 // Build a reference to this field within the parameter.
2536 CXXScopeSpec SS;
2537 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2538 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2540 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002541 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002542 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002543 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 ParamType, Loc,
2545 /*IsArrow=*/false,
2546 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002547 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 /*FirstQualifierInScope=*/0,
2549 MemberLookup,
2550 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002551 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002552 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002553
2554 // C++11 [class.copy]p15:
2555 // - if a member m has rvalue reference type T&&, it is direct-initialized
2556 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002557 if (RefersToRValueRef(CtorArg.get())) {
2558 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002559 }
2560
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002561 // When the field we are copying is an array, create index variables for
2562 // each dimension of the array. We use these index variables to subscript
2563 // the source array, and other clients (e.g., CodeGen) will perform the
2564 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 QualType BaseType = Field->getType();
2567 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002568 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002569 while (const ConstantArrayType *Array
2570 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002571 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 // Create the iteration variable for this array index.
2573 IdentifierInfo *IterationVarName = 0;
2574 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002575 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002576 llvm::raw_svector_ostream OS(Str);
2577 OS << "__i" << IndexVariables.size();
2578 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2579 }
2580 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002581 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 IterationVarName, SizeType,
2583 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002584 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002585 IndexVariables.push_back(IterationVar);
2586
2587 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002588 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002589 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 assert(!IterationVarRef.isInvalid() &&
2591 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002592 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2593 assert(!IterationVarRef.isInvalid() &&
2594 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002595
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002597 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002598 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002599 Loc);
2600 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002601 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002602
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002603 BaseType = Array->getElementType();
2604 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605
2606 // The array subscript expression is an lvalue, which is wrong for moving.
2607 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002608 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002609
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002610 // Construct the entity that we will be initializing. For an array, this
2611 // will be first element in the array, which may require several levels
2612 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002613 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002614 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002615 if (Indirect)
2616 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2617 else
2618 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002619 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2620 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2621 0,
2622 Entities.back()));
2623
2624 // Direct-initialize to use the copy constructor.
2625 InitializationKind InitKind =
2626 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2627
Sebastian Redl74e611a2011-09-04 18:14:28 +00002628 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002629 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002630 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631
John McCall60d7b3a2010-08-24 06:29:42 +00002632 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002633 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002634 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002635 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002636 if (MemberInit.isInvalid())
2637 return true;
2638
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002639 if (Indirect) {
2640 assert(IndexVariables.size() == 0 &&
2641 "Indirect field improperly initialized");
2642 CXXMemberInit
2643 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2644 Loc, Loc,
2645 MemberInit.takeAs<Expr>(),
2646 Loc);
2647 } else
2648 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2649 Loc, MemberInit.takeAs<Expr>(),
2650 Loc,
2651 IndexVariables.data(),
2652 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002653 return false;
2654 }
2655
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002656 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2657
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002658 QualType FieldBaseElementType =
2659 SemaRef.Context.getBaseElementType(Field->getType());
2660
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002661 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002662 InitializedEntity InitEntity
2663 = Indirect? InitializedEntity::InitializeMember(Indirect)
2664 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002665 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002666 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002667
2668 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002669 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002670 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002671
Douglas Gregor53c374f2010-12-07 00:41:46 +00002672 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002673 if (MemberInit.isInvalid())
2674 return true;
2675
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002676 if (Indirect)
2677 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2678 Indirect, Loc,
2679 Loc,
2680 MemberInit.get(),
2681 Loc);
2682 else
2683 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2684 Field, Loc, Loc,
2685 MemberInit.get(),
2686 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002687 return false;
2688 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002689
Sean Hunt1f2f3842011-05-17 00:19:05 +00002690 if (!Field->getParent()->isUnion()) {
2691 if (FieldBaseElementType->isReferenceType()) {
2692 SemaRef.Diag(Constructor->getLocation(),
2693 diag::err_uninitialized_member_in_ctor)
2694 << (int)Constructor->isImplicit()
2695 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2696 << 0 << Field->getDeclName();
2697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2698 return true;
2699 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002700
Sean Hunt1f2f3842011-05-17 00:19:05 +00002701 if (FieldBaseElementType.isConstQualified()) {
2702 SemaRef.Diag(Constructor->getLocation(),
2703 diag::err_uninitialized_member_in_ctor)
2704 << (int)Constructor->isImplicit()
2705 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2706 << 1 << Field->getDeclName();
2707 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2708 return true;
2709 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002710 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002711
John McCallf85e1932011-06-15 23:02:42 +00002712 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2713 FieldBaseElementType->isObjCRetainableType() &&
2714 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2715 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2716 // Instant objects:
2717 // Default-initialize Objective-C pointers to NULL.
2718 CXXMemberInit
2719 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2720 Loc, Loc,
2721 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2722 Loc);
2723 return false;
2724 }
2725
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002726 // Nothing to initialize.
2727 CXXMemberInit = 0;
2728 return false;
2729}
John McCallf1860e52010-05-20 23:23:51 +00002730
2731namespace {
2732struct BaseAndFieldInfo {
2733 Sema &S;
2734 CXXConstructorDecl *Ctor;
2735 bool AnyErrorsInInits;
2736 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002737 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002738 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002739
2740 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2741 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002742 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2743 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002744 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002745 else if (Generated && Ctor->isMoveConstructor())
2746 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002747 else
2748 IIK = IIK_Default;
2749 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002750
2751 bool isImplicitCopyOrMove() const {
2752 switch (IIK) {
2753 case IIK_Copy:
2754 case IIK_Move:
2755 return true;
2756
2757 case IIK_Default:
2758 return false;
2759 }
David Blaikie30263482012-01-20 21:50:17 +00002760
2761 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002762 }
John McCallf1860e52010-05-20 23:23:51 +00002763};
2764}
2765
Richard Smitha4950662011-09-19 13:34:43 +00002766/// \brief Determine whether the given indirect field declaration is somewhere
2767/// within an anonymous union.
2768static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2769 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2770 CEnd = F->chain_end();
2771 C != CEnd; ++C)
2772 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2773 if (Record->isUnion())
2774 return true;
2775
2776 return false;
2777}
2778
Douglas Gregorddb21472011-11-02 23:04:16 +00002779/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2780/// array type.
2781static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2782 if (T->isIncompleteArrayType())
2783 return true;
2784
2785 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2786 if (!ArrayT->getSize())
2787 return true;
2788
2789 T = ArrayT->getElementType();
2790 }
2791
2792 return false;
2793}
2794
Richard Smith7a614d82011-06-11 17:19:42 +00002795static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002796 FieldDecl *Field,
2797 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002798
Chandler Carruthe861c602010-06-30 02:59:29 +00002799 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002800 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002801 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002802 return false;
2803 }
2804
Richard Smith7a614d82011-06-11 17:19:42 +00002805 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2806 // has a brace-or-equal-initializer, the entity is initialized as specified
2807 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002808 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002809 CXXCtorInitializer *Init;
2810 if (Indirect)
2811 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2812 SourceLocation(),
2813 SourceLocation(), 0,
2814 SourceLocation());
2815 else
2816 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2817 SourceLocation(),
2818 SourceLocation(), 0,
2819 SourceLocation());
2820 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002821 return false;
2822 }
2823
Richard Smithc115f632011-09-18 11:14:50 +00002824 // Don't build an implicit initializer for union members if none was
2825 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002826 if (Field->getParent()->isUnion() ||
2827 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002828 return false;
2829
Douglas Gregorddb21472011-11-02 23:04:16 +00002830 // Don't initialize incomplete or zero-length arrays.
2831 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2832 return false;
2833
John McCallf1860e52010-05-20 23:23:51 +00002834 // Don't try to build an implicit initializer if there were semantic
2835 // errors in any of the initializers (and therefore we might be
2836 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002837 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002838 return false;
2839
Sean Huntcbb67482011-01-08 20:30:50 +00002840 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002841 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2842 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002843 return true;
John McCallf1860e52010-05-20 23:23:51 +00002844
Francois Pichet00eb3f92010-12-04 09:14:42 +00002845 if (Init)
2846 Info.AllToInit.push_back(Init);
2847
John McCallf1860e52010-05-20 23:23:51 +00002848 return false;
2849}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002850
2851bool
2852Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2853 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002854 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002855 Constructor->setNumCtorInitializers(1);
2856 CXXCtorInitializer **initializer =
2857 new (Context) CXXCtorInitializer*[1];
2858 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2859 Constructor->setCtorInitializers(initializer);
2860
Sean Huntb76af9c2011-05-03 23:05:34 +00002861 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002862 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002863 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2864 }
2865
Sean Huntc1598702011-05-05 00:05:47 +00002866 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002867
Sean Hunt059ce0d2011-05-01 07:04:31 +00002868 return false;
2869}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002870
John McCallb77115d2011-06-17 00:18:42 +00002871bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2872 CXXCtorInitializer **Initializers,
2873 unsigned NumInitializers,
2874 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002875 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002876 // Just store the initializers as written, they will be checked during
2877 // instantiation.
2878 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002879 Constructor->setNumCtorInitializers(NumInitializers);
2880 CXXCtorInitializer **baseOrMemberInitializers =
2881 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002882 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002883 NumInitializers * sizeof(CXXCtorInitializer*));
2884 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002885 }
2886
2887 return false;
2888 }
2889
John McCallf1860e52010-05-20 23:23:51 +00002890 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002891
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002892 // We need to build the initializer AST according to order of construction
2893 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002894 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002895 if (!ClassDecl)
2896 return true;
2897
Eli Friedman80c30da2009-11-09 19:20:36 +00002898 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002900 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002901 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002902
2903 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002904 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002905 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002906 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 }
2908
Anders Carlsson711f34a2010-04-21 19:52:01 +00002909 // Keep track of the direct virtual bases.
2910 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2911 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2912 E = ClassDecl->bases_end(); I != E; ++I) {
2913 if (I->isVirtual())
2914 DirectVBases.insert(I);
2915 }
2916
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002917 // Push virtual bases before others.
2918 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2919 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2920
Sean Huntcbb67482011-01-08 20:30:50 +00002921 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002922 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2923 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002924 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002925 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002926 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002928 VBase, IsInheritedVirtualBase,
2929 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002930 HadError = true;
2931 continue;
2932 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002933
John McCallf1860e52010-05-20 23:23:51 +00002934 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002935 }
2936 }
Mike Stump1eb44332009-09-09 15:08:12 +00002937
John McCallf1860e52010-05-20 23:23:51 +00002938 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002939 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2940 E = ClassDecl->bases_end(); Base != E; ++Base) {
2941 // Virtuals are in the virtual base list and already constructed.
2942 if (Base->isVirtual())
2943 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Sean Huntcbb67482011-01-08 20:30:50 +00002945 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002946 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2947 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002948 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002949 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002950 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002951 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002952 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002953 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002954 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002955 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002956
John McCallf1860e52010-05-20 23:23:51 +00002957 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002958 }
2959 }
Mike Stump1eb44332009-09-09 15:08:12 +00002960
John McCallf1860e52010-05-20 23:23:51 +00002961 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002962 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2963 MemEnd = ClassDecl->decls_end();
2964 Mem != MemEnd; ++Mem) {
2965 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002966 // C++ [class.bit]p2:
2967 // A declaration for a bit-field that omits the identifier declares an
2968 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2969 // initialized.
2970 if (F->isUnnamedBitfield())
2971 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002972
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002973 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002974 // handle anonymous struct/union fields based on their individual
2975 // indirect fields.
2976 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2977 continue;
2978
2979 if (CollectFieldInitializer(*this, Info, F))
2980 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002981 continue;
2982 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002983
2984 // Beyond this point, we only consider default initialization.
2985 if (Info.IIK != IIK_Default)
2986 continue;
2987
2988 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2989 if (F->getType()->isIncompleteArrayType()) {
2990 assert(ClassDecl->hasFlexibleArrayMember() &&
2991 "Incomplete array type is not valid");
2992 continue;
2993 }
2994
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002995 // Initialize each field of an anonymous struct individually.
2996 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2997 HadError = true;
2998
2999 continue;
3000 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003001 }
Mike Stump1eb44332009-09-09 15:08:12 +00003002
John McCallf1860e52010-05-20 23:23:51 +00003003 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003004 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003005 Constructor->setNumCtorInitializers(NumInitializers);
3006 CXXCtorInitializer **baseOrMemberInitializers =
3007 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003008 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003009 NumInitializers * sizeof(CXXCtorInitializer*));
3010 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003011
John McCallef027fe2010-03-16 21:39:52 +00003012 // Constructors implicitly reference the base and member
3013 // destructors.
3014 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3015 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003016 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003017
3018 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003019}
3020
Eli Friedman6347f422009-07-21 19:28:10 +00003021static void *GetKeyForTopLevelField(FieldDecl *Field) {
3022 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003023 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003024 if (RT->getDecl()->isAnonymousStructOrUnion())
3025 return static_cast<void *>(RT->getDecl());
3026 }
3027 return static_cast<void *>(Field);
3028}
3029
Anders Carlssonea356fb2010-04-02 05:42:15 +00003030static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003031 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003032}
3033
Anders Carlssonea356fb2010-04-02 05:42:15 +00003034static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003035 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003036 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003037 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003038
Eli Friedman6347f422009-07-21 19:28:10 +00003039 // For fields injected into the class via declaration of an anonymous union,
3040 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003041 FieldDecl *Field = Member->getAnyMember();
3042
John McCall3c3ccdb2010-04-10 09:28:51 +00003043 // If the field is a member of an anonymous struct or union, our key
3044 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003045 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003046 if (RD->isAnonymousStructOrUnion()) {
3047 while (true) {
3048 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3049 if (Parent->isAnonymousStructOrUnion())
3050 RD = Parent;
3051 else
3052 break;
3053 }
3054
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003055 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003056 }
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003058 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003059}
3060
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003061static void
3062DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003063 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003064 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003065 unsigned NumInits) {
3066 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003067 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003069 // Don't check initializers order unless the warning is enabled at the
3070 // location of at least one initializer.
3071 bool ShouldCheckOrder = false;
3072 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003073 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003074 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3075 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003076 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003077 ShouldCheckOrder = true;
3078 break;
3079 }
3080 }
3081 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003082 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003083
John McCalld6ca8da2010-04-10 07:37:23 +00003084 // Build the list of bases and members in the order that they'll
3085 // actually be initialized. The explicit initializers should be in
3086 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003087 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Anders Carlsson071d6102010-04-02 03:38:04 +00003089 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3090
John McCalld6ca8da2010-04-10 07:37:23 +00003091 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003092 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003093 ClassDecl->vbases_begin(),
3094 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003095 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003096
John McCalld6ca8da2010-04-10 07:37:23 +00003097 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003098 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003099 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003100 if (Base->isVirtual())
3101 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003103 }
Mike Stump1eb44332009-09-09 15:08:12 +00003104
John McCalld6ca8da2010-04-10 07:37:23 +00003105 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003107 E = ClassDecl->field_end(); Field != E; ++Field) {
3108 if (Field->isUnnamedBitfield())
3109 continue;
3110
John McCalld6ca8da2010-04-10 07:37:23 +00003111 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003112 }
3113
John McCalld6ca8da2010-04-10 07:37:23 +00003114 unsigned NumIdealInits = IdealInitKeys.size();
3115 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003116
Sean Huntcbb67482011-01-08 20:30:50 +00003117 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003118 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003119 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003120 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003121
3122 // Scan forward to try to find this initializer in the idealized
3123 // initializers list.
3124 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3125 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003126 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003127
3128 // If we didn't find this initializer, it must be because we
3129 // scanned past it on a previous iteration. That can only
3130 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003131 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003132 Sema::SemaDiagnosticBuilder D =
3133 SemaRef.Diag(PrevInit->getSourceLocation(),
3134 diag::warn_initializer_out_of_order);
3135
Francois Pichet00eb3f92010-12-04 09:14:42 +00003136 if (PrevInit->isAnyMemberInitializer())
3137 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003138 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003139 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003140
Francois Pichet00eb3f92010-12-04 09:14:42 +00003141 if (Init->isAnyMemberInitializer())
3142 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003143 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003144 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003145
3146 // Move back to the initializer's location in the ideal list.
3147 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3148 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003149 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003150
3151 assert(IdealIndex != NumIdealInits &&
3152 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003153 }
John McCalld6ca8da2010-04-10 07:37:23 +00003154
3155 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003156 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003157}
3158
John McCall3c3ccdb2010-04-10 09:28:51 +00003159namespace {
3160bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003161 CXXCtorInitializer *Init,
3162 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003163 if (!PrevInit) {
3164 PrevInit = Init;
3165 return false;
3166 }
3167
3168 if (FieldDecl *Field = Init->getMember())
3169 S.Diag(Init->getSourceLocation(),
3170 diag::err_multiple_mem_initialization)
3171 << Field->getDeclName()
3172 << Init->getSourceRange();
3173 else {
John McCallf4c73712011-01-19 06:33:43 +00003174 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003175 assert(BaseClass && "neither field nor base");
3176 S.Diag(Init->getSourceLocation(),
3177 diag::err_multiple_base_initialization)
3178 << QualType(BaseClass, 0)
3179 << Init->getSourceRange();
3180 }
3181 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3182 << 0 << PrevInit->getSourceRange();
3183
3184 return true;
3185}
3186
Sean Huntcbb67482011-01-08 20:30:50 +00003187typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003188typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3189
3190bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003191 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003192 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003193 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003194 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003195 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003196
3197 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003198 if (Parent->isUnion()) {
3199 UnionEntry &En = Unions[Parent];
3200 if (En.first && En.first != Child) {
3201 S.Diag(Init->getSourceLocation(),
3202 diag::err_multiple_mem_union_initialization)
3203 << Field->getDeclName()
3204 << Init->getSourceRange();
3205 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3206 << 0 << En.second->getSourceRange();
3207 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003208 }
3209 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003210 En.first = Child;
3211 En.second = Init;
3212 }
David Blaikie6fe29652011-11-17 06:01:57 +00003213 if (!Parent->isAnonymousStructOrUnion())
3214 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003215 }
3216
3217 Child = Parent;
3218 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003219 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003220
3221 return false;
3222}
3223}
3224
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003225/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003226void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003227 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003228 CXXCtorInitializer **meminits,
3229 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003230 bool AnyErrors) {
3231 if (!ConstructorDecl)
3232 return;
3233
3234 AdjustDeclIfTemplate(ConstructorDecl);
3235
3236 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003237 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003238
3239 if (!Constructor) {
3240 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3241 return;
3242 }
3243
Sean Huntcbb67482011-01-08 20:30:50 +00003244 CXXCtorInitializer **MemInits =
3245 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003246
3247 // Mapping for the duplicate initializers check.
3248 // For member initializers, this is keyed with a FieldDecl*.
3249 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003250 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003251
3252 // Mapping for the inconsistent anonymous-union initializers check.
3253 RedundantUnionMap MemberUnions;
3254
Anders Carlssonea356fb2010-04-02 05:42:15 +00003255 bool HadError = false;
3256 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003257 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003258
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003259 // Set the source order index.
3260 Init->setSourceOrder(i);
3261
Francois Pichet00eb3f92010-12-04 09:14:42 +00003262 if (Init->isAnyMemberInitializer()) {
3263 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3265 CheckRedundantUnionInit(*this, Init, MemberUnions))
3266 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003267 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003268 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3269 if (CheckRedundantInit(*this, Init, Members[Key]))
3270 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003271 } else {
3272 assert(Init->isDelegatingInitializer());
3273 // This must be the only initializer
3274 if (i != 0 || NumMemInits > 1) {
3275 Diag(MemInits[0]->getSourceLocation(),
3276 diag::err_delegating_initializer_alone)
3277 << MemInits[0]->getSourceRange();
3278 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003279 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003280 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003281 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003282 // Return immediately as the initializer is set.
3283 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003284 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003285 }
3286
Anders Carlssonea356fb2010-04-02 05:42:15 +00003287 if (HadError)
3288 return;
3289
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003290 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003291
Sean Huntcbb67482011-01-08 20:30:50 +00003292 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003293}
3294
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003295void
John McCallef027fe2010-03-16 21:39:52 +00003296Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3297 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003298 // Ignore dependent contexts. Also ignore unions, since their members never
3299 // have destructors implicitly called.
3300 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003301 return;
John McCall58e6f342010-03-16 05:22:47 +00003302
3303 // FIXME: all the access-control diagnostics are positioned on the
3304 // field/base declaration. That's probably good; that said, the
3305 // user might reasonably want to know why the destructor is being
3306 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003307
Anders Carlsson9f853df2009-11-17 04:44:12 +00003308 // Non-static data members.
3309 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3310 E = ClassDecl->field_end(); I != E; ++I) {
3311 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003312 if (Field->isInvalidDecl())
3313 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003314
3315 // Don't destroy incomplete or zero-length arrays.
3316 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3317 continue;
3318
Anders Carlsson9f853df2009-11-17 04:44:12 +00003319 QualType FieldType = Context.getBaseElementType(Field->getType());
3320
3321 const RecordType* RT = FieldType->getAs<RecordType>();
3322 if (!RT)
3323 continue;
3324
3325 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003326 if (FieldClassDecl->isInvalidDecl())
3327 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003328 if (FieldClassDecl->hasTrivialDestructor())
3329 continue;
3330
Douglas Gregordb89f282010-07-01 22:47:18 +00003331 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003332 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003333 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003334 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003335 << Field->getDeclName()
3336 << FieldType);
3337
Eli Friedman5f2987c2012-02-02 03:46:19 +00003338 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003339 }
3340
John McCall58e6f342010-03-16 05:22:47 +00003341 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3342
Anders Carlsson9f853df2009-11-17 04:44:12 +00003343 // Bases.
3344 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3345 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003346 // Bases are always records in a well-formed non-dependent class.
3347 const RecordType *RT = Base->getType()->getAs<RecordType>();
3348
3349 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003350 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003351 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003352
John McCall58e6f342010-03-16 05:22:47 +00003353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003354 // If our base class is invalid, we probably can't get its dtor anyway.
3355 if (BaseClassDecl->isInvalidDecl())
3356 continue;
3357 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003358 if (BaseClassDecl->hasTrivialDestructor())
3359 continue;
John McCall58e6f342010-03-16 05:22:47 +00003360
Douglas Gregordb89f282010-07-01 22:47:18 +00003361 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003362 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003363
3364 // FIXME: caret should be on the start of the class name
3365 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003366 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003367 << Base->getType()
3368 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003369
Eli Friedman5f2987c2012-02-02 03:46:19 +00003370 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003371 }
3372
3373 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003374 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3375 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003376
3377 // Bases are always records in a well-formed non-dependent class.
3378 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3379
3380 // Ignore direct virtual bases.
3381 if (DirectVirtualBases.count(RT))
3382 continue;
3383
John McCall58e6f342010-03-16 05:22:47 +00003384 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003385 // If our base class is invalid, we probably can't get its dtor anyway.
3386 if (BaseClassDecl->isInvalidDecl())
3387 continue;
3388 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003389 if (BaseClassDecl->hasTrivialDestructor())
3390 continue;
John McCall58e6f342010-03-16 05:22:47 +00003391
Douglas Gregordb89f282010-07-01 22:47:18 +00003392 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003393 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003394 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003395 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003396 << VBase->getType());
3397
Eli Friedman5f2987c2012-02-02 03:46:19 +00003398 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003399 }
3400}
3401
John McCalld226f652010-08-21 09:40:31 +00003402void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003403 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003404 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Mike Stump1eb44332009-09-09 15:08:12 +00003406 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003407 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003408 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003409}
3410
Mike Stump1eb44332009-09-09 15:08:12 +00003411bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003412 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003413 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003414 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003415 else
John McCall94c3b562010-08-18 09:41:07 +00003416 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003417}
3418
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003419bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003420 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003421 if (!getLangOptions().CPlusPlus)
3422 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Anders Carlsson11f21a02009-03-23 19:10:31 +00003424 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003425 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Ted Kremenek6217b802009-07-29 21:53:49 +00003427 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003428 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003429 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003430 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003432 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003433 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003434 }
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Ted Kremenek6217b802009-07-29 21:53:49 +00003436 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003437 if (!RT)
3438 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003439
John McCall86ff3082010-02-04 22:26:26 +00003440 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003441
John McCall94c3b562010-08-18 09:41:07 +00003442 // We can't answer whether something is abstract until it has a
3443 // definition. If it's currently being defined, we'll walk back
3444 // over all the declarations when we have a full definition.
3445 const CXXRecordDecl *Def = RD->getDefinition();
3446 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003447 return false;
3448
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003449 if (!RD->isAbstract())
3450 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003452 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003453 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCall94c3b562010-08-18 09:41:07 +00003455 return true;
3456}
3457
3458void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3459 // Check if we've already emitted the list of pure virtual functions
3460 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003461 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003462 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003464 CXXFinalOverriderMap FinalOverriders;
3465 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003467 // Keep a set of seen pure methods so we won't diagnose the same method
3468 // more than once.
3469 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3470
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003471 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3472 MEnd = FinalOverriders.end();
3473 M != MEnd;
3474 ++M) {
3475 for (OverridingMethods::iterator SO = M->second.begin(),
3476 SOEnd = M->second.end();
3477 SO != SOEnd; ++SO) {
3478 // C++ [class.abstract]p4:
3479 // A class is abstract if it contains or inherits at least one
3480 // pure virtual function for which the final overrider is pure
3481 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003483 //
3484 if (SO->second.size() != 1)
3485 continue;
3486
3487 if (!SO->second.front().Method->isPure())
3488 continue;
3489
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003490 if (!SeenPureMethods.insert(SO->second.front().Method))
3491 continue;
3492
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003493 Diag(SO->second.front().Method->getLocation(),
3494 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003495 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003496 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003497 }
3498
3499 if (!PureVirtualClassDiagSet)
3500 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3501 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003502}
3503
Anders Carlsson8211eff2009-03-24 01:19:16 +00003504namespace {
John McCall94c3b562010-08-18 09:41:07 +00003505struct AbstractUsageInfo {
3506 Sema &S;
3507 CXXRecordDecl *Record;
3508 CanQualType AbstractType;
3509 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
John McCall94c3b562010-08-18 09:41:07 +00003511 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3512 : S(S), Record(Record),
3513 AbstractType(S.Context.getCanonicalType(
3514 S.Context.getTypeDeclType(Record))),
3515 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003516
John McCall94c3b562010-08-18 09:41:07 +00003517 void DiagnoseAbstractType() {
3518 if (Invalid) return;
3519 S.DiagnoseAbstractType(Record);
3520 Invalid = true;
3521 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003522
John McCall94c3b562010-08-18 09:41:07 +00003523 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3524};
3525
3526struct CheckAbstractUsage {
3527 AbstractUsageInfo &Info;
3528 const NamedDecl *Ctx;
3529
3530 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3531 : Info(Info), Ctx(Ctx) {}
3532
3533 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3534 switch (TL.getTypeLocClass()) {
3535#define ABSTRACT_TYPELOC(CLASS, PARENT)
3536#define TYPELOC(CLASS, PARENT) \
3537 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3538#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003539 }
John McCall94c3b562010-08-18 09:41:07 +00003540 }
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCall94c3b562010-08-18 09:41:07 +00003542 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3543 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3544 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003545 if (!TL.getArg(I))
3546 continue;
3547
John McCall94c3b562010-08-18 09:41:07 +00003548 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3549 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003550 }
John McCall94c3b562010-08-18 09:41:07 +00003551 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003552
John McCall94c3b562010-08-18 09:41:07 +00003553 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3554 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
John McCall94c3b562010-08-18 09:41:07 +00003557 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3558 // Visit the type parameters from a permissive context.
3559 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3560 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3561 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3562 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3563 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3564 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003565 }
John McCall94c3b562010-08-18 09:41:07 +00003566 }
Mike Stump1eb44332009-09-09 15:08:12 +00003567
John McCall94c3b562010-08-18 09:41:07 +00003568 // Visit pointee types from a permissive context.
3569#define CheckPolymorphic(Type) \
3570 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3571 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3572 }
3573 CheckPolymorphic(PointerTypeLoc)
3574 CheckPolymorphic(ReferenceTypeLoc)
3575 CheckPolymorphic(MemberPointerTypeLoc)
3576 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003577 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003578
John McCall94c3b562010-08-18 09:41:07 +00003579 /// Handle all the types we haven't given a more specific
3580 /// implementation for above.
3581 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3582 // Every other kind of type that we haven't called out already
3583 // that has an inner type is either (1) sugar or (2) contains that
3584 // inner type in some way as a subobject.
3585 if (TypeLoc Next = TL.getNextTypeLoc())
3586 return Visit(Next, Sel);
3587
3588 // If there's no inner type and we're in a permissive context,
3589 // don't diagnose.
3590 if (Sel == Sema::AbstractNone) return;
3591
3592 // Check whether the type matches the abstract type.
3593 QualType T = TL.getType();
3594 if (T->isArrayType()) {
3595 Sel = Sema::AbstractArrayType;
3596 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003597 }
John McCall94c3b562010-08-18 09:41:07 +00003598 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3599 if (CT != Info.AbstractType) return;
3600
3601 // It matched; do some magic.
3602 if (Sel == Sema::AbstractArrayType) {
3603 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3604 << T << TL.getSourceRange();
3605 } else {
3606 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3607 << Sel << T << TL.getSourceRange();
3608 }
3609 Info.DiagnoseAbstractType();
3610 }
3611};
3612
3613void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3614 Sema::AbstractDiagSelID Sel) {
3615 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3616}
3617
3618}
3619
3620/// Check for invalid uses of an abstract type in a method declaration.
3621static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3622 CXXMethodDecl *MD) {
3623 // No need to do the check on definitions, which require that
3624 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003625 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003626 return;
3627
3628 // For safety's sake, just ignore it if we don't have type source
3629 // information. This should never happen for non-implicit methods,
3630 // but...
3631 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3632 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3633}
3634
3635/// Check for invalid uses of an abstract type within a class definition.
3636static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3637 CXXRecordDecl *RD) {
3638 for (CXXRecordDecl::decl_iterator
3639 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3640 Decl *D = *I;
3641 if (D->isImplicit()) continue;
3642
3643 // Methods and method templates.
3644 if (isa<CXXMethodDecl>(D)) {
3645 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3646 } else if (isa<FunctionTemplateDecl>(D)) {
3647 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3648 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3649
3650 // Fields and static variables.
3651 } else if (isa<FieldDecl>(D)) {
3652 FieldDecl *FD = cast<FieldDecl>(D);
3653 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3654 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3655 } else if (isa<VarDecl>(D)) {
3656 VarDecl *VD = cast<VarDecl>(D);
3657 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3658 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3659
3660 // Nested classes and class templates.
3661 } else if (isa<CXXRecordDecl>(D)) {
3662 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3663 } else if (isa<ClassTemplateDecl>(D)) {
3664 CheckAbstractClassUsage(Info,
3665 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3666 }
3667 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003668}
3669
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003670/// \brief Perform semantic checks on a class definition that has been
3671/// completing, introducing implicitly-declared members, checking for
3672/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003673void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003674 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003675 return;
3676
John McCall94c3b562010-08-18 09:41:07 +00003677 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3678 AbstractUsageInfo Info(*this, Record);
3679 CheckAbstractClassUsage(Info, Record);
3680 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003681
3682 // If this is not an aggregate type and has no user-declared constructor,
3683 // complain about any non-static data members of reference or const scalar
3684 // type, since they will never get initializers.
3685 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003686 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3687 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003688 bool Complained = false;
3689 for (RecordDecl::field_iterator F = Record->field_begin(),
3690 FEnd = Record->field_end();
3691 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003692 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003693 continue;
3694
Douglas Gregor325e5932010-04-15 00:00:53 +00003695 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003696 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003697 if (!Complained) {
3698 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3699 << Record->getTagKind() << Record;
3700 Complained = true;
3701 }
3702
3703 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3704 << F->getType()->isReferenceType()
3705 << F->getDeclName();
3706 }
3707 }
3708 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003709
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003710 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003711 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003712
3713 if (Record->getIdentifier()) {
3714 // C++ [class.mem]p13:
3715 // If T is the name of a class, then each of the following shall have a
3716 // name different from T:
3717 // - every member of every anonymous union that is a member of class T.
3718 //
3719 // C++ [class.mem]p14:
3720 // In addition, if class T has a user-declared constructor (12.1), every
3721 // non-static data member of class T shall have a name different from T.
3722 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003723 R.first != R.second; ++R.first) {
3724 NamedDecl *D = *R.first;
3725 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3726 isa<IndirectFieldDecl>(D)) {
3727 Diag(D->getLocation(), diag::err_member_name_of_class)
3728 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003729 break;
3730 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003731 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003732 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003733
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003734 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003735 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003736 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003737 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003738 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3739 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3740 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003741
3742 // See if a method overloads virtual methods in a base
3743 /// class without overriding any.
3744 if (!Record->isDependentType()) {
3745 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3746 MEnd = Record->method_end();
3747 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003748 if (!(*M)->isStatic())
3749 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003750 }
3751 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003752
Richard Smith9f569cc2011-10-01 02:31:28 +00003753 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3754 // function that is not a constructor declares that member function to be
3755 // const. [...] The class of which that function is a member shall be
3756 // a literal type.
3757 //
3758 // It's fine to diagnose constructors here too: such constructors cannot
3759 // produce a constant expression, so are ill-formed (no diagnostic required).
3760 //
3761 // If the class has virtual bases, any constexpr members will already have
3762 // been diagnosed by the checks performed on the member declaration, so
3763 // suppress this (less useful) diagnostic.
3764 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3765 !Record->isLiteral() && !Record->getNumVBases()) {
3766 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3767 MEnd = Record->method_end();
3768 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003769 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003770 switch (Record->getTemplateSpecializationKind()) {
3771 case TSK_ImplicitInstantiation:
3772 case TSK_ExplicitInstantiationDeclaration:
3773 case TSK_ExplicitInstantiationDefinition:
3774 // If a template instantiates to a non-literal type, but its members
3775 // instantiate to constexpr functions, the template is technically
3776 // ill-formed, but we allow it for sanity. Such members are treated as
3777 // non-constexpr.
3778 (*M)->setConstexpr(false);
3779 continue;
3780
3781 case TSK_Undeclared:
3782 case TSK_ExplicitSpecialization:
3783 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3784 PDiag(diag::err_constexpr_method_non_literal));
3785 break;
3786 }
3787
3788 // Only produce one error per class.
3789 break;
3790 }
3791 }
3792 }
3793
Sebastian Redlf677ea32011-02-05 19:23:19 +00003794 // Declare inherited constructors. We do this eagerly here because:
3795 // - The standard requires an eager diagnostic for conflicting inherited
3796 // constructors from different classes.
3797 // - The lazy declaration of the other implicit constructors is so as to not
3798 // waste space and performance on classes that are not meant to be
3799 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3800 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003801 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003802
Sean Hunteb88ae52011-05-23 21:07:59 +00003803 if (!Record->isDependentType())
3804 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003805}
3806
3807void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003808 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3809 ME = Record->method_end();
3810 MI != ME; ++MI) {
3811 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3812 switch (getSpecialMember(*MI)) {
3813 case CXXDefaultConstructor:
3814 CheckExplicitlyDefaultedDefaultConstructor(
3815 cast<CXXConstructorDecl>(*MI));
3816 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003817
Sean Huntcb45a0f2011-05-12 22:46:25 +00003818 case CXXDestructor:
3819 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3820 break;
3821
3822 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003823 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3824 break;
3825
Sean Huntcb45a0f2011-05-12 22:46:25 +00003826 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003827 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003828 break;
3829
Sean Hunt82713172011-05-25 23:16:36 +00003830 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003831 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003832 break;
3833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003834 case CXXMoveAssignment:
3835 CheckExplicitlyDefaultedMoveAssignment(*MI);
3836 break;
3837
3838 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003839 llvm_unreachable("non-special member explicitly defaulted!");
3840 }
Sean Hunt001cad92011-05-10 00:49:42 +00003841 }
3842 }
3843
Sean Hunt001cad92011-05-10 00:49:42 +00003844}
3845
3846void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3847 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3848
3849 // Whether this was the first-declared instance of the constructor.
3850 // This affects whether we implicitly add an exception spec (and, eventually,
3851 // constexpr). It is also ill-formed to explicitly default a constructor such
3852 // that it would be deleted. (C++0x [decl.fct.def.default])
3853 bool First = CD == CD->getCanonicalDecl();
3854
Sean Hunt49634cf2011-05-13 06:10:58 +00003855 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003856 if (CD->getNumParams() != 0) {
3857 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3858 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003859 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003860 }
3861
3862 ImplicitExceptionSpecification Spec
3863 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3864 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003865 if (EPI.ExceptionSpecType == EST_Delayed) {
3866 // Exception specification depends on some deferred part of the class. We'll
3867 // try again when the class's definition has been fully processed.
3868 return;
3869 }
Sean Hunt001cad92011-05-10 00:49:42 +00003870 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3871 *ExceptionType = Context.getFunctionType(
3872 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3873
Richard Smith61802452011-12-22 02:22:31 +00003874 // C++11 [dcl.fct.def.default]p2:
3875 // An explicitly-defaulted function may be declared constexpr only if it
3876 // would have been implicitly declared as constexpr,
3877 if (CD->isConstexpr()) {
3878 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3879 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3880 << CXXDefaultConstructor;
3881 HadError = true;
3882 }
3883 }
3884 // and may have an explicit exception-specification only if it is compatible
3885 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003886 if (CtorType->hasExceptionSpec()) {
3887 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003888 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003889 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003890 PDiag(),
3891 ExceptionType, SourceLocation(),
3892 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003893 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003894 }
Richard Smith61802452011-12-22 02:22:31 +00003895 }
3896
3897 // If a function is explicitly defaulted on its first declaration,
3898 if (First) {
3899 // -- it is implicitly considered to be constexpr if the implicit
3900 // definition would be,
3901 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3902
3903 // -- it is implicitly considered to have the same
3904 // exception-specification as if it had been implicitly declared
3905 //
3906 // FIXME: a compatible, but different, explicit exception specification
3907 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003908 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003909 }
Sean Huntca46d132011-05-12 03:51:48 +00003910
Sean Hunt49634cf2011-05-13 06:10:58 +00003911 if (HadError) {
3912 CD->setInvalidDecl();
3913 return;
3914 }
3915
Sean Hunte16da072011-10-10 06:18:57 +00003916 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003917 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003918 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003919 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003920 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003921 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003922 CD->setInvalidDecl();
3923 }
3924 }
3925}
3926
3927void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3928 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3929
3930 // Whether this was the first-declared instance of the constructor.
3931 bool First = CD == CD->getCanonicalDecl();
3932
3933 bool HadError = false;
3934 if (CD->getNumParams() != 1) {
3935 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3936 << CD->getSourceRange();
3937 HadError = true;
3938 }
3939
3940 ImplicitExceptionSpecification Spec(Context);
3941 bool Const;
3942 llvm::tie(Spec, Const) =
3943 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3944
3945 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3946 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3947 *ExceptionType = Context.getFunctionType(
3948 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3949
3950 // Check for parameter type matching.
3951 // This is a copy ctor so we know it's a cv-qualified reference to T.
3952 QualType ArgType = CtorType->getArgType(0);
3953 if (ArgType->getPointeeType().isVolatileQualified()) {
3954 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3955 HadError = true;
3956 }
3957 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3958 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3959 HadError = true;
3960 }
3961
Richard Smith61802452011-12-22 02:22:31 +00003962 // C++11 [dcl.fct.def.default]p2:
3963 // An explicitly-defaulted function may be declared constexpr only if it
3964 // would have been implicitly declared as constexpr,
3965 if (CD->isConstexpr()) {
3966 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3967 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3968 << CXXCopyConstructor;
3969 HadError = true;
3970 }
3971 }
3972 // and may have an explicit exception-specification only if it is compatible
3973 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003974 if (CtorType->hasExceptionSpec()) {
3975 if (CheckEquivalentExceptionSpec(
3976 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003977 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003978 PDiag(),
3979 ExceptionType, SourceLocation(),
3980 CtorType, CD->getLocation())) {
3981 HadError = true;
3982 }
Richard Smith61802452011-12-22 02:22:31 +00003983 }
3984
3985 // If a function is explicitly defaulted on its first declaration,
3986 if (First) {
3987 // -- it is implicitly considered to be constexpr if the implicit
3988 // definition would be,
3989 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3990
3991 // -- it is implicitly considered to have the same
3992 // exception-specification as if it had been implicitly declared, and
3993 //
3994 // FIXME: a compatible, but different, explicit exception specification
3995 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003996 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003997
3998 // -- [...] it shall have the same parameter type as if it had been
3999 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00004000 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4001 }
4002
4003 if (HadError) {
4004 CD->setInvalidDecl();
4005 return;
4006 }
4007
Sean Huntc32d6842011-10-11 04:55:36 +00004008 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004009 if (First) {
4010 CD->setDeletedAsWritten();
4011 } else {
4012 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004013 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004014 CD->setInvalidDecl();
4015 }
Sean Huntca46d132011-05-12 03:51:48 +00004016 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004017}
Sean Hunt001cad92011-05-10 00:49:42 +00004018
Sean Hunt2b188082011-05-14 05:23:28 +00004019void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4020 assert(MD->isExplicitlyDefaulted());
4021
4022 // Whether this was the first-declared instance of the operator
4023 bool First = MD == MD->getCanonicalDecl();
4024
4025 bool HadError = false;
4026 if (MD->getNumParams() != 1) {
4027 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4028 << MD->getSourceRange();
4029 HadError = true;
4030 }
4031
4032 QualType ReturnType =
4033 MD->getType()->getAs<FunctionType>()->getResultType();
4034 if (!ReturnType->isLValueReferenceType() ||
4035 !Context.hasSameType(
4036 Context.getCanonicalType(ReturnType->getPointeeType()),
4037 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4038 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4039 HadError = true;
4040 }
4041
4042 ImplicitExceptionSpecification Spec(Context);
4043 bool Const;
4044 llvm::tie(Spec, Const) =
4045 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4046
4047 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4048 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4049 *ExceptionType = Context.getFunctionType(
4050 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4051
Sean Hunt2b188082011-05-14 05:23:28 +00004052 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004053 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004054 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004055 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004056 } else {
4057 if (ArgType->getPointeeType().isVolatileQualified()) {
4058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4059 HadError = true;
4060 }
4061 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4062 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4063 HadError = true;
4064 }
Sean Hunt2b188082011-05-14 05:23:28 +00004065 }
Sean Huntbe631222011-05-17 20:44:43 +00004066
Sean Hunt2b188082011-05-14 05:23:28 +00004067 if (OperType->getTypeQuals()) {
4068 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4069 HadError = true;
4070 }
4071
4072 if (OperType->hasExceptionSpec()) {
4073 if (CheckEquivalentExceptionSpec(
4074 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004075 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004076 PDiag(),
4077 ExceptionType, SourceLocation(),
4078 OperType, MD->getLocation())) {
4079 HadError = true;
4080 }
Richard Smith61802452011-12-22 02:22:31 +00004081 }
4082 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004083 // We set the declaration to have the computed exception spec here.
4084 // We duplicate the one parameter type.
4085 EPI.RefQualifier = OperType->getRefQualifier();
4086 EPI.ExtInfo = OperType->getExtInfo();
4087 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4088 }
4089
4090 if (HadError) {
4091 MD->setInvalidDecl();
4092 return;
4093 }
4094
4095 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4096 if (First) {
4097 MD->setDeletedAsWritten();
4098 } else {
4099 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004100 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004101 MD->setInvalidDecl();
4102 }
4103 }
4104}
4105
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004106void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4107 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4108
4109 // Whether this was the first-declared instance of the constructor.
4110 bool First = CD == CD->getCanonicalDecl();
4111
4112 bool HadError = false;
4113 if (CD->getNumParams() != 1) {
4114 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4115 << CD->getSourceRange();
4116 HadError = true;
4117 }
4118
4119 ImplicitExceptionSpecification Spec(
4120 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4121
4122 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4123 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4124 *ExceptionType = Context.getFunctionType(
4125 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4126
4127 // Check for parameter type matching.
4128 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4129 QualType ArgType = CtorType->getArgType(0);
4130 if (ArgType->getPointeeType().isVolatileQualified()) {
4131 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4132 HadError = true;
4133 }
4134 if (ArgType->getPointeeType().isConstQualified()) {
4135 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4136 HadError = true;
4137 }
4138
Richard Smith61802452011-12-22 02:22:31 +00004139 // C++11 [dcl.fct.def.default]p2:
4140 // An explicitly-defaulted function may be declared constexpr only if it
4141 // would have been implicitly declared as constexpr,
4142 if (CD->isConstexpr()) {
4143 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4144 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4145 << CXXMoveConstructor;
4146 HadError = true;
4147 }
4148 }
4149 // and may have an explicit exception-specification only if it is compatible
4150 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004151 if (CtorType->hasExceptionSpec()) {
4152 if (CheckEquivalentExceptionSpec(
4153 PDiag(diag::err_incorrect_defaulted_exception_spec)
4154 << CXXMoveConstructor,
4155 PDiag(),
4156 ExceptionType, SourceLocation(),
4157 CtorType, CD->getLocation())) {
4158 HadError = true;
4159 }
Richard Smith61802452011-12-22 02:22:31 +00004160 }
4161
4162 // If a function is explicitly defaulted on its first declaration,
4163 if (First) {
4164 // -- it is implicitly considered to be constexpr if the implicit
4165 // definition would be,
4166 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4167
4168 // -- it is implicitly considered to have the same
4169 // exception-specification as if it had been implicitly declared, and
4170 //
4171 // FIXME: a compatible, but different, explicit exception specification
4172 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004173 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004174
4175 // -- [...] it shall have the same parameter type as if it had been
4176 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004177 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4178 }
4179
4180 if (HadError) {
4181 CD->setInvalidDecl();
4182 return;
4183 }
4184
Sean Hunt769bb2d2011-10-11 06:43:29 +00004185 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004186 if (First) {
4187 CD->setDeletedAsWritten();
4188 } else {
4189 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4190 << CXXMoveConstructor;
4191 CD->setInvalidDecl();
4192 }
4193 }
4194}
4195
4196void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4197 assert(MD->isExplicitlyDefaulted());
4198
4199 // Whether this was the first-declared instance of the operator
4200 bool First = MD == MD->getCanonicalDecl();
4201
4202 bool HadError = false;
4203 if (MD->getNumParams() != 1) {
4204 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4205 << MD->getSourceRange();
4206 HadError = true;
4207 }
4208
4209 QualType ReturnType =
4210 MD->getType()->getAs<FunctionType>()->getResultType();
4211 if (!ReturnType->isLValueReferenceType() ||
4212 !Context.hasSameType(
4213 Context.getCanonicalType(ReturnType->getPointeeType()),
4214 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4215 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4216 HadError = true;
4217 }
4218
4219 ImplicitExceptionSpecification Spec(
4220 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4221
4222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4223 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4224 *ExceptionType = Context.getFunctionType(
4225 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4226
4227 QualType ArgType = OperType->getArgType(0);
4228 if (!ArgType->isRValueReferenceType()) {
4229 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4230 HadError = true;
4231 } else {
4232 if (ArgType->getPointeeType().isVolatileQualified()) {
4233 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4234 HadError = true;
4235 }
4236 if (ArgType->getPointeeType().isConstQualified()) {
4237 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4238 HadError = true;
4239 }
4240 }
4241
4242 if (OperType->getTypeQuals()) {
4243 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4244 HadError = true;
4245 }
4246
4247 if (OperType->hasExceptionSpec()) {
4248 if (CheckEquivalentExceptionSpec(
4249 PDiag(diag::err_incorrect_defaulted_exception_spec)
4250 << CXXMoveAssignment,
4251 PDiag(),
4252 ExceptionType, SourceLocation(),
4253 OperType, MD->getLocation())) {
4254 HadError = true;
4255 }
Richard Smith61802452011-12-22 02:22:31 +00004256 }
4257 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004258 // We set the declaration to have the computed exception spec here.
4259 // We duplicate the one parameter type.
4260 EPI.RefQualifier = OperType->getRefQualifier();
4261 EPI.ExtInfo = OperType->getExtInfo();
4262 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4263 }
4264
4265 if (HadError) {
4266 MD->setInvalidDecl();
4267 return;
4268 }
4269
4270 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4271 if (First) {
4272 MD->setDeletedAsWritten();
4273 } else {
4274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4275 << CXXMoveAssignment;
4276 MD->setInvalidDecl();
4277 }
4278 }
4279}
4280
Sean Huntcb45a0f2011-05-12 22:46:25 +00004281void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4282 assert(DD->isExplicitlyDefaulted());
4283
4284 // Whether this was the first-declared instance of the destructor.
4285 bool First = DD == DD->getCanonicalDecl();
4286
4287 ImplicitExceptionSpecification Spec
4288 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4289 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4290 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4291 *ExceptionType = Context.getFunctionType(
4292 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4293
4294 if (DtorType->hasExceptionSpec()) {
4295 if (CheckEquivalentExceptionSpec(
4296 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004297 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004298 PDiag(),
4299 ExceptionType, SourceLocation(),
4300 DtorType, DD->getLocation())) {
4301 DD->setInvalidDecl();
4302 return;
4303 }
Richard Smith61802452011-12-22 02:22:31 +00004304 }
4305 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004306 // We set the declaration to have the computed exception spec here.
4307 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004308 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004309 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4310 }
4311
4312 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004313 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004314 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004315 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004316 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004317 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004318 DD->setInvalidDecl();
4319 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004320 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321}
4322
Sean Hunte16da072011-10-10 06:18:57 +00004323/// This function implements the following C++0x paragraphs:
4324/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004325/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004326bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4327 assert(!MD->isInvalidDecl());
4328 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004329 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004330 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004331 return false;
4332
Sean Hunte16da072011-10-10 06:18:57 +00004333 bool IsUnion = RD->isUnion();
4334 bool IsConstructor = false;
4335 bool IsAssignment = false;
4336 bool IsMove = false;
4337
4338 bool ConstArg = false;
4339
4340 switch (CSM) {
4341 case CXXDefaultConstructor:
4342 IsConstructor = true;
Douglas Gregor215e4e12012-02-12 17:34:23 +00004343
4344 // C++11 [expr.lambda.prim]p19:
4345 // The closure type associated with a lambda-expression has a
4346 // deleted (8.4.3) default constructor.
4347 if (RD->isLambda())
4348 return true;
4349
Sean Hunte16da072011-10-10 06:18:57 +00004350 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004351 case CXXCopyConstructor:
4352 IsConstructor = true;
4353 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4354 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004355 case CXXMoveConstructor:
4356 IsConstructor = true;
4357 IsMove = true;
4358 break;
Sean Hunte16da072011-10-10 06:18:57 +00004359 default:
4360 llvm_unreachable("function only currently implemented for default ctors");
4361 }
4362
4363 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004364
Sean Huntc32d6842011-10-11 04:55:36 +00004365 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004366 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004367
Sean Huntcdee3fe2011-05-11 22:34:38 +00004368 bool AllConst = true;
4369
Sean Huntcdee3fe2011-05-11 22:34:38 +00004370 // We do this because we should never actually use an anonymous
4371 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004372 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004373 return false;
4374
4375 // FIXME: We should put some diagnostic logic right into this function.
4376
Sean Huntcdee3fe2011-05-11 22:34:38 +00004377 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4378 BE = RD->bases_end();
4379 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004380 // We'll handle this one later
4381 if (BI->isVirtual())
4382 continue;
4383
Sean Huntcdee3fe2011-05-11 22:34:38 +00004384 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4385 assert(BaseDecl && "base isn't a CXXRecordDecl");
4386
Sean Hunte16da072011-10-10 06:18:57 +00004387 // Unless we have an assignment operator, the base's destructor must
4388 // be accessible and not deleted.
4389 if (!IsAssignment) {
4390 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4391 if (BaseDtor->isDeleted())
4392 return true;
4393 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4394 AR_accessible)
4395 return true;
4396 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004397
Sean Hunte16da072011-10-10 06:18:57 +00004398 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004399 // unique, accessible, non-deleted function. If we are doing
4400 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004401 if (CSM != CXXDestructor) {
4402 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004403 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004404 false);
4405 if (!SMOR->hasSuccess())
4406 return true;
4407 CXXMethodDecl *BaseMember = SMOR->getMethod();
4408 if (IsConstructor) {
4409 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4410 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4411 PDiag()) != AR_accessible)
4412 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004413
4414 // For a move operation, the corresponding operation must actually
4415 // be a move operation (and not a copy selected by overload
4416 // resolution) unless we are working on a trivially copyable class.
4417 if (IsMove && !BaseCtor->isMoveConstructor() &&
4418 !BaseDecl->isTriviallyCopyable())
4419 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004420 }
4421 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004422 }
4423
4424 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4425 BE = RD->vbases_end();
4426 BI != BE; ++BI) {
4427 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4428 assert(BaseDecl && "base isn't a CXXRecordDecl");
4429
Sean Hunte16da072011-10-10 06:18:57 +00004430 // Unless we have an assignment operator, the base's destructor must
4431 // be accessible and not deleted.
4432 if (!IsAssignment) {
4433 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4434 if (BaseDtor->isDeleted())
4435 return true;
4436 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4437 AR_accessible)
4438 return true;
4439 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004440
Sean Hunte16da072011-10-10 06:18:57 +00004441 // Finding the corresponding member in the base should lead to a
4442 // unique, accessible, non-deleted function.
4443 if (CSM != CXXDestructor) {
4444 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004445 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004446 false);
4447 if (!SMOR->hasSuccess())
4448 return true;
4449 CXXMethodDecl *BaseMember = SMOR->getMethod();
4450 if (IsConstructor) {
4451 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4452 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4453 PDiag()) != AR_accessible)
4454 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004455
4456 // For a move operation, the corresponding operation must actually
4457 // be a move operation (and not a copy selected by overload
4458 // resolution) unless we are working on a trivially copyable class.
4459 if (IsMove && !BaseCtor->isMoveConstructor() &&
4460 !BaseDecl->isTriviallyCopyable())
4461 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004462 }
4463 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004464 }
4465
4466 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4467 FE = RD->field_end();
4468 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004469 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004470 continue;
4471
Sean Huntcdee3fe2011-05-11 22:34:38 +00004472 QualType FieldType = Context.getBaseElementType(FI->getType());
4473 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004474
Sean Hunte16da072011-10-10 06:18:57 +00004475 // For a default constructor, all references must be initialized in-class
4476 // and, if a union, it must have a non-const member.
4477 if (CSM == CXXDefaultConstructor) {
4478 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4479 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004480
Sean Hunte16da072011-10-10 06:18:57 +00004481 if (IsUnion && !FieldType.isConstQualified())
4482 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004483 // For a copy constructor, data members must not be of rvalue reference
4484 // type.
4485 } else if (CSM == CXXCopyConstructor) {
4486 if (FieldType->isRValueReferenceType())
4487 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004488 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004489
4490 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004491 // For a default constructor, a const member must have a user-provided
4492 // default constructor or else be explicitly initialized.
4493 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004494 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004495 !FieldRecord->hasUserProvidedDefaultConstructor())
4496 return true;
4497
Sean Huntc32d6842011-10-11 04:55:36 +00004498 // Some additional restrictions exist on the variant members.
4499 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004500 FieldRecord->isAnonymousStructOrUnion()) {
4501 // We're okay to reuse AllConst here since we only care about the
4502 // value otherwise if we're in a union.
4503 AllConst = true;
4504
4505 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4506 UE = FieldRecord->field_end();
4507 UI != UE; ++UI) {
4508 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4509 CXXRecordDecl *UnionFieldRecord =
4510 UnionFieldType->getAsCXXRecordDecl();
4511
4512 if (!UnionFieldType.isConstQualified())
4513 AllConst = false;
4514
Sean Huntc32d6842011-10-11 04:55:36 +00004515 if (UnionFieldRecord) {
4516 // FIXME: Checking for accessibility and validity of this
4517 // destructor is technically going beyond the
4518 // standard, but this is believed to be a defect.
4519 if (!IsAssignment) {
4520 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4521 if (FieldDtor->isDeleted())
4522 return true;
4523 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4524 AR_accessible)
4525 return true;
4526 if (!FieldDtor->isTrivial())
4527 return true;
4528 }
4529
4530 if (CSM != CXXDestructor) {
4531 SpecialMemberOverloadResult *SMOR =
4532 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004533 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004534 // FIXME: Checking for accessibility and validity of this
4535 // corresponding member is technically going beyond the
4536 // standard, but this is believed to be a defect.
4537 if (!SMOR->hasSuccess())
4538 return true;
4539
4540 CXXMethodDecl *FieldMember = SMOR->getMethod();
4541 // A member of a union must have a trivial corresponding
4542 // constructor.
4543 if (!FieldMember->isTrivial())
4544 return true;
4545
4546 if (IsConstructor) {
4547 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4548 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4549 PDiag()) != AR_accessible)
4550 return true;
4551 }
4552 }
4553 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004554 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004555
Sean Huntc32d6842011-10-11 04:55:36 +00004556 // At least one member in each anonymous union must be non-const
4557 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004558 return true;
4559
4560 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004561 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004562 continue;
4563 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004564
Sean Huntc32d6842011-10-11 04:55:36 +00004565 // Unless we're doing assignment, the field's destructor must be
4566 // accessible and not deleted.
4567 if (!IsAssignment) {
4568 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4569 if (FieldDtor->isDeleted())
4570 return true;
4571 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4572 AR_accessible)
4573 return true;
4574 }
4575
Sean Hunte16da072011-10-10 06:18:57 +00004576 // Check that the corresponding member of the field is accessible,
4577 // unique, and non-deleted. We don't do this if it has an explicit
4578 // initialization when default-constructing.
4579 if (CSM != CXXDestructor &&
4580 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4581 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004582 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004583 false);
4584 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004585 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004586
4587 CXXMethodDecl *FieldMember = SMOR->getMethod();
4588 if (IsConstructor) {
4589 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4590 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4591 PDiag()) != AR_accessible)
4592 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004593
4594 // For a move operation, the corresponding operation must actually
4595 // be a move operation (and not a copy selected by overload
4596 // resolution) unless we are working on a trivially copyable class.
4597 if (IsMove && !FieldCtor->isMoveConstructor() &&
4598 !FieldRecord->isTriviallyCopyable())
4599 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004600 }
4601
4602 // We need the corresponding member of a union to be trivial so that
4603 // we can safely copy them all simultaneously.
4604 // FIXME: Note that performing the check here (where we rely on the lack
4605 // of an in-class initializer) is technically ill-formed. However, this
4606 // seems most obviously to be a bug in the standard.
4607 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004608 return true;
4609 }
Sean Hunte16da072011-10-10 06:18:57 +00004610 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4611 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4612 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004613 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004614 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004615 }
4616
Sean Hunte16da072011-10-10 06:18:57 +00004617 // We can't have all const members in a union when default-constructing,
4618 // or else they're all nonsensical garbage values that can't be changed.
4619 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004620 return true;
4621
4622 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004623}
4624
Sean Hunt7f410192011-05-14 05:23:24 +00004625bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4626 CXXRecordDecl *RD = MD->getParent();
4627 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004628 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004629 return false;
4630
Douglas Gregor215e4e12012-02-12 17:34:23 +00004631 // C++11 [expr.lambda.prim]p19:
4632 // The closure type associated with a lambda-expression has a
4633 // [...] deleted copy assignment operator.
4634 if (RD->isLambda())
4635 return true;
4636
Sean Hunt71a682f2011-05-18 03:41:58 +00004637 SourceLocation Loc = MD->getLocation();
4638
Sean Hunt7f410192011-05-14 05:23:24 +00004639 // Do access control from the constructor
4640 ContextRAII MethodContext(*this, MD);
4641
4642 bool Union = RD->isUnion();
4643
Sean Hunt661c67a2011-06-21 23:42:56 +00004644 unsigned ArgQuals =
4645 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4646 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004647
4648 // We do this because we should never actually use an anonymous
4649 // union's constructor.
4650 if (Union && RD->isAnonymousStructOrUnion())
4651 return false;
4652
Sean Hunt7f410192011-05-14 05:23:24 +00004653 // FIXME: We should put some diagnostic logic right into this function.
4654
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004655 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004656 // A defaulted [copy] assignment operator for class X is defined as deleted
4657 // if X has:
4658
4659 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4660 BE = RD->bases_end();
4661 BI != BE; ++BI) {
4662 // We'll handle this one later
4663 if (BI->isVirtual())
4664 continue;
4665
4666 QualType BaseType = BI->getType();
4667 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4668 assert(BaseDecl && "base isn't a CXXRecordDecl");
4669
4670 // -- a [direct base class] B that cannot be [copied] because overload
4671 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004672 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004673 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004674 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4675 0);
4676 if (!CopyOper || CopyOper->isDeleted())
4677 return true;
4678 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004679 return true;
4680 }
4681
4682 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4683 BE = RD->vbases_end();
4684 BI != BE; ++BI) {
4685 QualType BaseType = BI->getType();
4686 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4687 assert(BaseDecl && "base isn't a CXXRecordDecl");
4688
Sean Hunt7f410192011-05-14 05:23:24 +00004689 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004690 // resolution, as applied to B's [copy] assignment operator, results in
4691 // an ambiguity or a function that is deleted or inaccessible from the
4692 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004693 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4694 0);
4695 if (!CopyOper || CopyOper->isDeleted())
4696 return true;
4697 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004698 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004699 }
4700
4701 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4702 FE = RD->field_end();
4703 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004704 if (FI->isUnnamedBitfield())
4705 continue;
4706
Sean Hunt7f410192011-05-14 05:23:24 +00004707 QualType FieldType = Context.getBaseElementType(FI->getType());
4708
4709 // -- a non-static data member of reference type
4710 if (FieldType->isReferenceType())
4711 return true;
4712
4713 // -- a non-static data member of const non-class type (or array thereof)
4714 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4715 return true;
4716
4717 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4718
4719 if (FieldRecord) {
4720 // This is an anonymous union
4721 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4722 // Anonymous unions inside unions do not variant members create
4723 if (!Union) {
4724 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4725 UE = FieldRecord->field_end();
4726 UI != UE; ++UI) {
4727 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4728 CXXRecordDecl *UnionFieldRecord =
4729 UnionFieldType->getAsCXXRecordDecl();
4730
4731 // -- a variant member with a non-trivial [copy] assignment operator
4732 // and X is a union-like class
4733 if (UnionFieldRecord &&
4734 !UnionFieldRecord->hasTrivialCopyAssignment())
4735 return true;
4736 }
4737 }
4738
4739 // Don't try to initalize an anonymous union
4740 continue;
4741 // -- a variant member with a non-trivial [copy] assignment operator
4742 // and X is a union-like class
4743 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4744 return true;
4745 }
Sean Hunt7f410192011-05-14 05:23:24 +00004746
Sean Hunt661c67a2011-06-21 23:42:56 +00004747 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4748 false, 0);
4749 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004750 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004751 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004752 return true;
4753 }
4754 }
4755
4756 return false;
4757}
4758
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004759bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4760 CXXRecordDecl *RD = MD->getParent();
4761 assert(!RD->isDependentType() && "do deletion after instantiation");
4762 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4763 return false;
4764
4765 SourceLocation Loc = MD->getLocation();
4766
4767 // Do access control from the constructor
4768 ContextRAII MethodContext(*this, MD);
4769
4770 bool Union = RD->isUnion();
4771
4772 // We do this because we should never actually use an anonymous
4773 // union's constructor.
4774 if (Union && RD->isAnonymousStructOrUnion())
4775 return false;
4776
4777 // C++0x [class.copy]/20
4778 // A defaulted [move] assignment operator for class X is defined as deleted
4779 // if X has:
4780
4781 // -- for the move constructor, [...] any direct or indirect virtual base
4782 // class.
4783 if (RD->getNumVBases() != 0)
4784 return true;
4785
4786 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4787 BE = RD->bases_end();
4788 BI != BE; ++BI) {
4789
4790 QualType BaseType = BI->getType();
4791 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4792 assert(BaseDecl && "base isn't a CXXRecordDecl");
4793
4794 // -- a [direct base class] B that cannot be [moved] because overload
4795 // resolution, as applied to B's [move] assignment operator, results in
4796 // an ambiguity or a function that is deleted or inaccessible from the
4797 // assignment operator
4798 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4799 if (!MoveOper || MoveOper->isDeleted())
4800 return true;
4801 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4802 return true;
4803
4804 // -- for the move assignment operator, a [direct base class] with a type
4805 // that does not have a move assignment operator and is not trivially
4806 // copyable.
4807 if (!MoveOper->isMoveAssignmentOperator() &&
4808 !BaseDecl->isTriviallyCopyable())
4809 return true;
4810 }
4811
4812 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4813 FE = RD->field_end();
4814 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004815 if (FI->isUnnamedBitfield())
4816 continue;
4817
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004818 QualType FieldType = Context.getBaseElementType(FI->getType());
4819
4820 // -- a non-static data member of reference type
4821 if (FieldType->isReferenceType())
4822 return true;
4823
4824 // -- a non-static data member of const non-class type (or array thereof)
4825 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4826 return true;
4827
4828 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4829
4830 if (FieldRecord) {
4831 // This is an anonymous union
4832 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4833 // Anonymous unions inside unions do not variant members create
4834 if (!Union) {
4835 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4836 UE = FieldRecord->field_end();
4837 UI != UE; ++UI) {
4838 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4839 CXXRecordDecl *UnionFieldRecord =
4840 UnionFieldType->getAsCXXRecordDecl();
4841
4842 // -- a variant member with a non-trivial [move] assignment operator
4843 // and X is a union-like class
4844 if (UnionFieldRecord &&
4845 !UnionFieldRecord->hasTrivialMoveAssignment())
4846 return true;
4847 }
4848 }
4849
4850 // Don't try to initalize an anonymous union
4851 continue;
4852 // -- a variant member with a non-trivial [move] assignment operator
4853 // and X is a union-like class
4854 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4855 return true;
4856 }
4857
4858 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4859 if (!MoveOper || MoveOper->isDeleted())
4860 return true;
4861 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4862 return true;
4863
4864 // -- for the move assignment operator, a [non-static data member] with a
4865 // type that does not have a move assignment operator and is not
4866 // trivially copyable.
4867 if (!MoveOper->isMoveAssignmentOperator() &&
4868 !FieldRecord->isTriviallyCopyable())
4869 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004870 }
Sean Hunt7f410192011-05-14 05:23:24 +00004871 }
4872
4873 return false;
4874}
4875
Sean Huntcb45a0f2011-05-12 22:46:25 +00004876bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4877 CXXRecordDecl *RD = DD->getParent();
4878 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004879 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004880 return false;
4881
Sean Hunt71a682f2011-05-18 03:41:58 +00004882 SourceLocation Loc = DD->getLocation();
4883
Sean Huntcb45a0f2011-05-12 22:46:25 +00004884 // Do access control from the destructor
4885 ContextRAII CtorContext(*this, DD);
4886
4887 bool Union = RD->isUnion();
4888
Sean Hunt49634cf2011-05-13 06:10:58 +00004889 // We do this because we should never actually use an anonymous
4890 // union's destructor.
4891 if (Union && RD->isAnonymousStructOrUnion())
4892 return false;
4893
Sean Huntcb45a0f2011-05-12 22:46:25 +00004894 // C++0x [class.dtor]p5
4895 // A defaulted destructor for a class X is defined as deleted if:
4896 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4897 BE = RD->bases_end();
4898 BI != BE; ++BI) {
4899 // We'll handle this one later
4900 if (BI->isVirtual())
4901 continue;
4902
4903 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4904 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4905 assert(BaseDtor && "base has no destructor");
4906
4907 // -- any direct or virtual base class has a deleted destructor or
4908 // a destructor that is inaccessible from the defaulted destructor
4909 if (BaseDtor->isDeleted())
4910 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004911 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004912 AR_accessible)
4913 return true;
4914 }
4915
4916 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4917 BE = RD->vbases_end();
4918 BI != BE; ++BI) {
4919 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4920 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4921 assert(BaseDtor && "base has no destructor");
4922
4923 // -- any direct or virtual base class has a deleted destructor or
4924 // a destructor that is inaccessible from the defaulted destructor
4925 if (BaseDtor->isDeleted())
4926 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004927 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004928 AR_accessible)
4929 return true;
4930 }
4931
4932 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4933 FE = RD->field_end();
4934 FI != FE; ++FI) {
4935 QualType FieldType = Context.getBaseElementType(FI->getType());
4936 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4937 if (FieldRecord) {
4938 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4939 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4940 UE = FieldRecord->field_end();
4941 UI != UE; ++UI) {
4942 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4943 CXXRecordDecl *UnionFieldRecord =
4944 UnionFieldType->getAsCXXRecordDecl();
4945
4946 // -- X is a union-like class that has a variant member with a non-
4947 // trivial destructor.
4948 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4949 return true;
4950 }
4951 // Technically we are supposed to do this next check unconditionally.
4952 // But that makes absolutely no sense.
4953 } else {
4954 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4955
4956 // -- any of the non-static data members has class type M (or array
4957 // thereof) and M has a deleted destructor or a destructor that is
4958 // inaccessible from the defaulted destructor
4959 if (FieldDtor->isDeleted())
4960 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004961 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004962 AR_accessible)
4963 return true;
4964
4965 // -- X is a union-like class that has a variant member with a non-
4966 // trivial destructor.
4967 if (Union && !FieldDtor->isTrivial())
4968 return true;
4969 }
4970 }
4971 }
4972
4973 if (DD->isVirtual()) {
4974 FunctionDecl *OperatorDelete = 0;
4975 DeclarationName Name =
4976 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004977 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004978 false))
4979 return true;
4980 }
4981
4982
4983 return false;
4984}
4985
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004986/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004987namespace {
4988 struct FindHiddenVirtualMethodData {
4989 Sema *S;
4990 CXXMethodDecl *Method;
4991 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004992 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004993 };
4994}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004995
4996/// \brief Member lookup function that determines whether a given C++
4997/// method overloads virtual methods in a base class without overriding any,
4998/// to be used with CXXRecordDecl::lookupInBases().
4999static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5000 CXXBasePath &Path,
5001 void *UserData) {
5002 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5003
5004 FindHiddenVirtualMethodData &Data
5005 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5006
5007 DeclarationName Name = Data.Method->getDeclName();
5008 assert(Name.getNameKind() == DeclarationName::Identifier);
5009
5010 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005011 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005012 for (Path.Decls = BaseRecord->lookup(Name);
5013 Path.Decls.first != Path.Decls.second;
5014 ++Path.Decls.first) {
5015 NamedDecl *D = *Path.Decls.first;
5016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005017 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005018 foundSameNameMethod = true;
5019 // Interested only in hidden virtual methods.
5020 if (!MD->isVirtual())
5021 continue;
5022 // If the method we are checking overrides a method from its base
5023 // don't warn about the other overloaded methods.
5024 if (!Data.S->IsOverload(Data.Method, MD, false))
5025 return true;
5026 // Collect the overload only if its hidden.
5027 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5028 overloadedMethods.push_back(MD);
5029 }
5030 }
5031
5032 if (foundSameNameMethod)
5033 Data.OverloadedMethods.append(overloadedMethods.begin(),
5034 overloadedMethods.end());
5035 return foundSameNameMethod;
5036}
5037
5038/// \brief See if a method overloads virtual methods in a base class without
5039/// overriding any.
5040void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5041 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005042 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005043 return;
5044 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5045 return;
5046
5047 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5048 /*bool RecordPaths=*/false,
5049 /*bool DetectVirtual=*/false);
5050 FindHiddenVirtualMethodData Data;
5051 Data.Method = MD;
5052 Data.S = this;
5053
5054 // Keep the base methods that were overriden or introduced in the subclass
5055 // by 'using' in a set. A base method not in this set is hidden.
5056 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5057 res.first != res.second; ++res.first) {
5058 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5059 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5060 E = MD->end_overridden_methods();
5061 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005062 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005063 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5064 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005065 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005066 }
5067
5068 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5069 !Data.OverloadedMethods.empty()) {
5070 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5071 << MD << (Data.OverloadedMethods.size() > 1);
5072
5073 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5074 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5075 Diag(overloadedMD->getLocation(),
5076 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5077 }
5078 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005079}
5080
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005081void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005082 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005083 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005084 SourceLocation RBrac,
5085 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005086 if (!TagDecl)
5087 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005088
Douglas Gregor42af25f2009-05-11 19:58:34 +00005089 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005090
David Blaikie77b6de02011-09-22 02:58:26 +00005091 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005092 // strict aliasing violation!
5093 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005094 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005095
Douglas Gregor23c94db2010-07-02 17:43:08 +00005096 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005097 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005098}
5099
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005100/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5101/// special functions, such as the default constructor, copy
5102/// constructor, or destructor, to the given C++ class (C++
5103/// [special]p1). This routine can only be executed just before the
5104/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005105void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005106 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005107 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005108
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005109 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005110 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005111
Richard Smithb701d3d2011-12-24 21:56:24 +00005112 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5113 ++ASTContext::NumImplicitMoveConstructors;
5114
Douglas Gregora376d102010-07-02 21:50:04 +00005115 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5116 ++ASTContext::NumImplicitCopyAssignmentOperators;
5117
5118 // If we have a dynamic class, then the copy assignment operator may be
5119 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5120 // it shows up in the right place in the vtable and that we diagnose
5121 // problems with the implicit exception specification.
5122 if (ClassDecl->isDynamicClass())
5123 DeclareImplicitCopyAssignment(ClassDecl);
5124 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005125
Richard Smithb701d3d2011-12-24 21:56:24 +00005126 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5127 ++ASTContext::NumImplicitMoveAssignmentOperators;
5128
5129 // Likewise for the move assignment operator.
5130 if (ClassDecl->isDynamicClass())
5131 DeclareImplicitMoveAssignment(ClassDecl);
5132 }
5133
Douglas Gregor4923aa22010-07-02 20:37:36 +00005134 if (!ClassDecl->hasUserDeclaredDestructor()) {
5135 ++ASTContext::NumImplicitDestructors;
5136
5137 // If we have a dynamic class, then the destructor may be virtual, so we
5138 // have to declare the destructor immediately. This ensures that, e.g., it
5139 // shows up in the right place in the vtable and that we diagnose problems
5140 // with the implicit exception specification.
5141 if (ClassDecl->isDynamicClass())
5142 DeclareImplicitDestructor(ClassDecl);
5143 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005144}
5145
Francois Pichet8387e2a2011-04-22 22:18:13 +00005146void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5147 if (!D)
5148 return;
5149
5150 int NumParamList = D->getNumTemplateParameterLists();
5151 for (int i = 0; i < NumParamList; i++) {
5152 TemplateParameterList* Params = D->getTemplateParameterList(i);
5153 for (TemplateParameterList::iterator Param = Params->begin(),
5154 ParamEnd = Params->end();
5155 Param != ParamEnd; ++Param) {
5156 NamedDecl *Named = cast<NamedDecl>(*Param);
5157 if (Named->getDeclName()) {
5158 S->AddDecl(Named);
5159 IdResolver.AddDecl(Named);
5160 }
5161 }
5162 }
5163}
5164
John McCalld226f652010-08-21 09:40:31 +00005165void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005166 if (!D)
5167 return;
5168
5169 TemplateParameterList *Params = 0;
5170 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5171 Params = Template->getTemplateParameters();
5172 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5173 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5174 Params = PartialSpec->getTemplateParameters();
5175 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005176 return;
5177
Douglas Gregor6569d682009-05-27 23:11:45 +00005178 for (TemplateParameterList::iterator Param = Params->begin(),
5179 ParamEnd = Params->end();
5180 Param != ParamEnd; ++Param) {
5181 NamedDecl *Named = cast<NamedDecl>(*Param);
5182 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005183 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005184 IdResolver.AddDecl(Named);
5185 }
5186 }
5187}
5188
John McCalld226f652010-08-21 09:40:31 +00005189void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005190 if (!RecordD) return;
5191 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005192 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005193 PushDeclContext(S, Record);
5194}
5195
John McCalld226f652010-08-21 09:40:31 +00005196void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005197 if (!RecordD) return;
5198 PopDeclContext();
5199}
5200
Douglas Gregor72b505b2008-12-16 21:30:33 +00005201/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5202/// parsing a top-level (non-nested) C++ class, and we are now
5203/// parsing those parts of the given Method declaration that could
5204/// not be parsed earlier (C++ [class.mem]p2), such as default
5205/// arguments. This action should enter the scope of the given
5206/// Method declaration as if we had just parsed the qualified method
5207/// name. However, it should not bring the parameters into scope;
5208/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005209void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005210}
5211
5212/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5213/// C++ method declaration. We're (re-)introducing the given
5214/// function parameter into scope for use in parsing later parts of
5215/// the method declaration. For example, we could see an
5216/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005217void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005218 if (!ParamD)
5219 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005220
John McCalld226f652010-08-21 09:40:31 +00005221 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005222
5223 // If this parameter has an unparsed default argument, clear it out
5224 // to make way for the parsed default argument.
5225 if (Param->hasUnparsedDefaultArg())
5226 Param->setDefaultArg(0);
5227
John McCalld226f652010-08-21 09:40:31 +00005228 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005229 if (Param->getDeclName())
5230 IdResolver.AddDecl(Param);
5231}
5232
5233/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5234/// processing the delayed method declaration for Method. The method
5235/// declaration is now considered finished. There may be a separate
5236/// ActOnStartOfFunctionDef action later (not necessarily
5237/// immediately!) for this method, if it was also defined inside the
5238/// class body.
John McCalld226f652010-08-21 09:40:31 +00005239void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005240 if (!MethodD)
5241 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005243 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005244
John McCalld226f652010-08-21 09:40:31 +00005245 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005246
5247 // Now that we have our default arguments, check the constructor
5248 // again. It could produce additional diagnostics or affect whether
5249 // the class has implicitly-declared destructors, among other
5250 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005251 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5252 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005253
5254 // Check the default arguments, which we may have added.
5255 if (!Method->isInvalidDecl())
5256 CheckCXXDefaultArguments(Method);
5257}
5258
Douglas Gregor42a552f2008-11-05 20:51:48 +00005259/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005260/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005261/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005262/// emit diagnostics and set the invalid bit to true. In any case, the type
5263/// will be updated to reflect a well-formed type for the constructor and
5264/// returned.
5265QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005266 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005267 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005268
5269 // C++ [class.ctor]p3:
5270 // A constructor shall not be virtual (10.3) or static (9.4). A
5271 // constructor can be invoked for a const, volatile or const
5272 // volatile object. A constructor shall not be declared const,
5273 // volatile, or const volatile (9.3.2).
5274 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005275 if (!D.isInvalidType())
5276 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5277 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5278 << SourceRange(D.getIdentifierLoc());
5279 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005280 }
John McCalld931b082010-08-26 03:08:43 +00005281 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005282 if (!D.isInvalidType())
5283 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5284 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5285 << SourceRange(D.getIdentifierLoc());
5286 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005287 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005288 }
Mike Stump1eb44332009-09-09 15:08:12 +00005289
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005290 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005291 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005292 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005293 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5294 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005295 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005296 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5297 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005298 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005299 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5300 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005301 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Douglas Gregorc938c162011-01-26 05:01:58 +00005304 // C++0x [class.ctor]p4:
5305 // A constructor shall not be declared with a ref-qualifier.
5306 if (FTI.hasRefQualifier()) {
5307 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5308 << FTI.RefQualifierIsLValueRef
5309 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5310 D.setInvalidType();
5311 }
5312
Douglas Gregor42a552f2008-11-05 20:51:48 +00005313 // Rebuild the function type "R" without any type qualifiers (in
5314 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005315 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005316 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005317 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5318 return R;
5319
5320 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5321 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005322 EPI.RefQualifier = RQ_None;
5323
Chris Lattner65401802009-04-25 08:28:21 +00005324 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005325 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005326}
5327
Douglas Gregor72b505b2008-12-16 21:30:33 +00005328/// CheckConstructor - Checks a fully-formed constructor for
5329/// well-formedness, issuing any diagnostics required. Returns true if
5330/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005331void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005332 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005333 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5334 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005335 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005336
5337 // C++ [class.copy]p3:
5338 // A declaration of a constructor for a class X is ill-formed if
5339 // its first parameter is of type (optionally cv-qualified) X and
5340 // either there are no other parameters or else all other
5341 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005342 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005343 ((Constructor->getNumParams() == 1) ||
5344 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005345 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5346 Constructor->getTemplateSpecializationKind()
5347 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005348 QualType ParamType = Constructor->getParamDecl(0)->getType();
5349 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5350 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005351 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005352 const char *ConstRef
5353 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5354 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005355 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005356 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005357
5358 // FIXME: Rather that making the constructor invalid, we should endeavor
5359 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005360 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005361 }
5362 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005363}
5364
John McCall15442822010-08-04 01:04:25 +00005365/// CheckDestructor - Checks a fully-formed destructor definition for
5366/// well-formedness, issuing any diagnostics required. Returns true
5367/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005368bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005369 CXXRecordDecl *RD = Destructor->getParent();
5370
5371 if (Destructor->isVirtual()) {
5372 SourceLocation Loc;
5373
5374 if (!Destructor->isImplicit())
5375 Loc = Destructor->getLocation();
5376 else
5377 Loc = RD->getLocation();
5378
5379 // If we have a virtual destructor, look up the deallocation function
5380 FunctionDecl *OperatorDelete = 0;
5381 DeclarationName Name =
5382 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005383 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005384 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005385
Eli Friedman5f2987c2012-02-02 03:46:19 +00005386 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005387
5388 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005389 }
Anders Carlsson37909802009-11-30 21:24:50 +00005390
5391 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005392}
5393
Mike Stump1eb44332009-09-09 15:08:12 +00005394static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005395FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5396 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5397 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005398 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005399}
5400
Douglas Gregor42a552f2008-11-05 20:51:48 +00005401/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5402/// the well-formednes of the destructor declarator @p D with type @p
5403/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005404/// emit diagnostics and set the declarator to invalid. Even if this happens,
5405/// will be updated to reflect a well-formed type for the destructor and
5406/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005407QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005408 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005409 // C++ [class.dtor]p1:
5410 // [...] A typedef-name that names a class is a class-name
5411 // (7.1.3); however, a typedef-name that names a class shall not
5412 // be used as the identifier in the declarator for a destructor
5413 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005414 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005415 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005416 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005417 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005418 else if (const TemplateSpecializationType *TST =
5419 DeclaratorType->getAs<TemplateSpecializationType>())
5420 if (TST->isTypeAlias())
5421 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5422 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005423
5424 // C++ [class.dtor]p2:
5425 // A destructor is used to destroy objects of its class type. A
5426 // destructor takes no parameters, and no return type can be
5427 // specified for it (not even void). The address of a destructor
5428 // shall not be taken. A destructor shall not be static. A
5429 // destructor can be invoked for a const, volatile or const
5430 // volatile object. A destructor shall not be declared const,
5431 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005432 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005433 if (!D.isInvalidType())
5434 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5435 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005436 << SourceRange(D.getIdentifierLoc())
5437 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5438
John McCalld931b082010-08-26 03:08:43 +00005439 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005440 }
Chris Lattner65401802009-04-25 08:28:21 +00005441 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005442 // Destructors don't have return types, but the parser will
5443 // happily parse something like:
5444 //
5445 // class X {
5446 // float ~X();
5447 // };
5448 //
5449 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005450 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5451 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5452 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005453 }
Mike Stump1eb44332009-09-09 15:08:12 +00005454
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005455 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005456 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005457 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005458 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5459 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005460 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005461 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5462 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005463 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005464 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5465 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005466 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005467 }
5468
Douglas Gregorc938c162011-01-26 05:01:58 +00005469 // C++0x [class.dtor]p2:
5470 // A destructor shall not be declared with a ref-qualifier.
5471 if (FTI.hasRefQualifier()) {
5472 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5473 << FTI.RefQualifierIsLValueRef
5474 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5475 D.setInvalidType();
5476 }
5477
Douglas Gregor42a552f2008-11-05 20:51:48 +00005478 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005479 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005480 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5481
5482 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005483 FTI.freeArgs();
5484 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005485 }
5486
Mike Stump1eb44332009-09-09 15:08:12 +00005487 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005488 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005489 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005490 D.setInvalidType();
5491 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005492
5493 // Rebuild the function type "R" without any type qualifiers or
5494 // parameters (in case any of the errors above fired) and with
5495 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005496 // types.
John McCalle23cf432010-12-14 08:05:40 +00005497 if (!D.isInvalidType())
5498 return R;
5499
Douglas Gregord92ec472010-07-01 05:10:53 +00005500 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005501 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5502 EPI.Variadic = false;
5503 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005504 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005505 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005506}
5507
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005508/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5509/// well-formednes of the conversion function declarator @p D with
5510/// type @p R. If there are any errors in the declarator, this routine
5511/// will emit diagnostics and return true. Otherwise, it will return
5512/// false. Either way, the type @p R will be updated to reflect a
5513/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005514void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005515 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005516 // C++ [class.conv.fct]p1:
5517 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005518 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005519 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005520 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005521 if (!D.isInvalidType())
5522 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5523 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5524 << SourceRange(D.getIdentifierLoc());
5525 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005526 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005527 }
John McCalla3f81372010-04-13 00:04:31 +00005528
5529 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5530
Chris Lattner6e475012009-04-25 08:35:12 +00005531 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005532 // Conversion functions don't have return types, but the parser will
5533 // happily parse something like:
5534 //
5535 // class X {
5536 // float operator bool();
5537 // };
5538 //
5539 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005540 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5541 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5542 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005543 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005544 }
5545
John McCalla3f81372010-04-13 00:04:31 +00005546 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5547
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005548 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005549 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005550 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5551
5552 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005553 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005554 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005555 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005556 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005557 D.setInvalidType();
5558 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005559
John McCalla3f81372010-04-13 00:04:31 +00005560 // Diagnose "&operator bool()" and other such nonsense. This
5561 // is actually a gcc extension which we don't support.
5562 if (Proto->getResultType() != ConvType) {
5563 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5564 << Proto->getResultType();
5565 D.setInvalidType();
5566 ConvType = Proto->getResultType();
5567 }
5568
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005569 // C++ [class.conv.fct]p4:
5570 // The conversion-type-id shall not represent a function type nor
5571 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005572 if (ConvType->isArrayType()) {
5573 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5574 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005575 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005576 } else if (ConvType->isFunctionType()) {
5577 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5578 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005579 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005580 }
5581
5582 // Rebuild the function type "R" without any parameters (in case any
5583 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005584 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005585 if (D.isInvalidType())
5586 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005587
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005588 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005589 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005590 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005591 getLangOptions().CPlusPlus0x ?
5592 diag::warn_cxx98_compat_explicit_conversion_functions :
5593 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005594 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005595}
5596
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005597/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5598/// the declaration of the given C++ conversion function. This routine
5599/// is responsible for recording the conversion function in the C++
5600/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005601Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005602 assert(Conversion && "Expected to receive a conversion function declaration");
5603
Douglas Gregor9d350972008-12-12 08:25:50 +00005604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005605
5606 // Make sure we aren't redeclaring the conversion function.
5607 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005608
5609 // C++ [class.conv.fct]p1:
5610 // [...] A conversion function is never used to convert a
5611 // (possibly cv-qualified) object to the (possibly cv-qualified)
5612 // same object type (or a reference to it), to a (possibly
5613 // cv-qualified) base class of that type (or a reference to it),
5614 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005615 // FIXME: Suppress this warning if the conversion function ends up being a
5616 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005617 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005618 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005619 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005620 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005621 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5622 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005623 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005624 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005625 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5626 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005627 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005628 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005629 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005630 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005631 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005632 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005633 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005634 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005635 }
5636
Douglas Gregore80622f2010-09-29 04:25:11 +00005637 if (FunctionTemplateDecl *ConversionTemplate
5638 = Conversion->getDescribedFunctionTemplate())
5639 return ConversionTemplate;
5640
John McCalld226f652010-08-21 09:40:31 +00005641 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005642}
5643
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005644//===----------------------------------------------------------------------===//
5645// Namespace Handling
5646//===----------------------------------------------------------------------===//
5647
John McCallea318642010-08-26 09:15:37 +00005648
5649
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005650/// ActOnStartNamespaceDef - This is called at the start of a namespace
5651/// definition.
John McCalld226f652010-08-21 09:40:31 +00005652Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005653 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005654 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005655 SourceLocation IdentLoc,
5656 IdentifierInfo *II,
5657 SourceLocation LBrace,
5658 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005659 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5660 // For anonymous namespace, take the location of the left brace.
5661 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005662 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005663 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005664 bool IsStd = false;
5665 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005666 Scope *DeclRegionScope = NamespcScope->getParent();
5667
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005668 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005669 if (II) {
5670 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005671 // The identifier in an original-namespace-definition shall not
5672 // have been previously defined in the declarative region in
5673 // which the original-namespace-definition appears. The
5674 // identifier in an original-namespace-definition is the name of
5675 // the namespace. Subsequently in that declarative region, it is
5676 // treated as an original-namespace-name.
5677 //
5678 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005679 // look through using directives, just look for any ordinary names.
5680
5681 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005682 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5683 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005684 NamedDecl *PrevDecl = 0;
5685 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005686 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005687 R.first != R.second; ++R.first) {
5688 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5689 PrevDecl = *R.first;
5690 break;
5691 }
5692 }
5693
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005694 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5695
5696 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005697 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005698 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005699 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005700 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005701 // The user probably just forgot the 'inline', so suggest that it
5702 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005703 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005704 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5705 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005706 Diag(Loc, diag::err_inline_namespace_mismatch)
5707 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005708 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005709 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5710
5711 IsInline = PrevNS->isInline();
5712 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005713 } else if (PrevDecl) {
5714 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005715 Diag(Loc, diag::err_redefinition_different_kind)
5716 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005717 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005718 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005719 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005720 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005721 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005722 // This is the first "real" definition of the namespace "std", so update
5723 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005724 PrevNS = getStdNamespace();
5725 IsStd = true;
5726 AddToKnown = !IsInline;
5727 } else {
5728 // We've seen this namespace for the first time.
5729 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005730 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005731 } else {
John McCall9aeed322009-10-01 00:25:31 +00005732 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005733
5734 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005735 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005736 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005737 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005738 } else {
5739 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005740 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005741 }
5742
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005743 if (PrevNS && IsInline != PrevNS->isInline()) {
5744 // inline-ness must match
5745 Diag(Loc, diag::err_inline_namespace_mismatch)
5746 << IsInline;
5747 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005748
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005749 // Recover by ignoring the new namespace's inline status.
5750 IsInline = PrevNS->isInline();
5751 }
5752 }
5753
5754 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5755 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005756 if (IsInvalid)
5757 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005758
5759 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005760
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005761 // FIXME: Should we be merging attributes?
5762 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005763 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005764
5765 if (IsStd)
5766 StdNamespace = Namespc;
5767 if (AddToKnown)
5768 KnownNamespaces[Namespc] = false;
5769
5770 if (II) {
5771 PushOnScopeChains(Namespc, DeclRegionScope);
5772 } else {
5773 // Link the anonymous namespace into its parent.
5774 DeclContext *Parent = CurContext->getRedeclContext();
5775 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5776 TU->setAnonymousNamespace(Namespc);
5777 } else {
5778 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005779 }
John McCall9aeed322009-10-01 00:25:31 +00005780
Douglas Gregora4181472010-03-24 00:46:35 +00005781 CurContext->addDecl(Namespc);
5782
John McCall9aeed322009-10-01 00:25:31 +00005783 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5784 // behaves as if it were replaced by
5785 // namespace unique { /* empty body */ }
5786 // using namespace unique;
5787 // namespace unique { namespace-body }
5788 // where all occurrences of 'unique' in a translation unit are
5789 // replaced by the same identifier and this identifier differs
5790 // from all other identifiers in the entire program.
5791
5792 // We just create the namespace with an empty name and then add an
5793 // implicit using declaration, just like the standard suggests.
5794 //
5795 // CodeGen enforces the "universally unique" aspect by giving all
5796 // declarations semantically contained within an anonymous
5797 // namespace internal linkage.
5798
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005799 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005800 UsingDirectiveDecl* UD
5801 = UsingDirectiveDecl::Create(Context, CurContext,
5802 /* 'using' */ LBrace,
5803 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005804 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005805 /* identifier */ SourceLocation(),
5806 Namespc,
5807 /* Ancestor */ CurContext);
5808 UD->setImplicit();
5809 CurContext->addDecl(UD);
5810 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005811 }
5812
5813 // Although we could have an invalid decl (i.e. the namespace name is a
5814 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005815 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5816 // for the namespace has the declarations that showed up in that particular
5817 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005818 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005819 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005820}
5821
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005822/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5823/// is a namespace alias, returns the namespace it points to.
5824static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5825 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5826 return AD->getNamespace();
5827 return dyn_cast_or_null<NamespaceDecl>(D);
5828}
5829
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005830/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5831/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005832void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005833 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5834 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005835 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005836 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005837 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005838 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005839}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005840
John McCall384aff82010-08-25 07:42:41 +00005841CXXRecordDecl *Sema::getStdBadAlloc() const {
5842 return cast_or_null<CXXRecordDecl>(
5843 StdBadAlloc.get(Context.getExternalSource()));
5844}
5845
5846NamespaceDecl *Sema::getStdNamespace() const {
5847 return cast_or_null<NamespaceDecl>(
5848 StdNamespace.get(Context.getExternalSource()));
5849}
5850
Douglas Gregor66992202010-06-29 17:53:46 +00005851/// \brief Retrieve the special "std" namespace, which may require us to
5852/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005853NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005854 if (!StdNamespace) {
5855 // The "std" namespace has not yet been defined, so build one implicitly.
5856 StdNamespace = NamespaceDecl::Create(Context,
5857 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005858 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005859 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005860 &PP.getIdentifierTable().get("std"),
5861 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005862 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005863 }
5864
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005865 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005866}
5867
Sebastian Redl395e04d2012-01-17 22:49:33 +00005868bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5869 assert(getLangOptions().CPlusPlus &&
5870 "Looking for std::initializer_list outside of C++.");
5871
5872 // We're looking for implicit instantiations of
5873 // template <typename E> class std::initializer_list.
5874
5875 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5876 return false;
5877
Sebastian Redl84760e32012-01-17 22:49:58 +00005878 ClassTemplateDecl *Template = 0;
5879 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005880
Sebastian Redl84760e32012-01-17 22:49:58 +00005881 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005882
Sebastian Redl84760e32012-01-17 22:49:58 +00005883 ClassTemplateSpecializationDecl *Specialization =
5884 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5885 if (!Specialization)
5886 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005887
Sebastian Redl84760e32012-01-17 22:49:58 +00005888 Template = Specialization->getSpecializedTemplate();
5889 Arguments = Specialization->getTemplateArgs().data();
5890 } else if (const TemplateSpecializationType *TST =
5891 Ty->getAs<TemplateSpecializationType>()) {
5892 Template = dyn_cast_or_null<ClassTemplateDecl>(
5893 TST->getTemplateName().getAsTemplateDecl());
5894 Arguments = TST->getArgs();
5895 }
5896 if (!Template)
5897 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005898
5899 if (!StdInitializerList) {
5900 // Haven't recognized std::initializer_list yet, maybe this is it.
5901 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5902 if (TemplateClass->getIdentifier() !=
5903 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005904 !getStdNamespace()->InEnclosingNamespaceSetOf(
5905 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005906 return false;
5907 // This is a template called std::initializer_list, but is it the right
5908 // template?
5909 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005910 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005911 return false;
5912 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5913 return false;
5914
5915 // It's the right template.
5916 StdInitializerList = Template;
5917 }
5918
5919 if (Template != StdInitializerList)
5920 return false;
5921
5922 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005923 if (Element)
5924 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005925 return true;
5926}
5927
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005928static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5929 NamespaceDecl *Std = S.getStdNamespace();
5930 if (!Std) {
5931 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5932 return 0;
5933 }
5934
5935 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5936 Loc, Sema::LookupOrdinaryName);
5937 if (!S.LookupQualifiedName(Result, Std)) {
5938 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5939 return 0;
5940 }
5941 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5942 if (!Template) {
5943 Result.suppressDiagnostics();
5944 // We found something weird. Complain about the first thing we found.
5945 NamedDecl *Found = *Result.begin();
5946 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5947 return 0;
5948 }
5949
5950 // We found some template called std::initializer_list. Now verify that it's
5951 // correct.
5952 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005953 if (Params->getMinRequiredArguments() != 1 ||
5954 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005955 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5956 return 0;
5957 }
5958
5959 return Template;
5960}
5961
5962QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5963 if (!StdInitializerList) {
5964 StdInitializerList = LookupStdInitializerList(*this, Loc);
5965 if (!StdInitializerList)
5966 return QualType();
5967 }
5968
5969 TemplateArgumentListInfo Args(Loc, Loc);
5970 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5971 Context.getTrivialTypeSourceInfo(Element,
5972 Loc)));
5973 return Context.getCanonicalType(
5974 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5975}
5976
Sebastian Redl98d36062012-01-17 22:50:14 +00005977bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5978 // C++ [dcl.init.list]p2:
5979 // A constructor is an initializer-list constructor if its first parameter
5980 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5981 // std::initializer_list<E> for some type E, and either there are no other
5982 // parameters or else all other parameters have default arguments.
5983 if (Ctor->getNumParams() < 1 ||
5984 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5985 return false;
5986
5987 QualType ArgType = Ctor->getParamDecl(0)->getType();
5988 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5989 ArgType = RT->getPointeeType().getUnqualifiedType();
5990
5991 return isStdInitializerList(ArgType, 0);
5992}
5993
Douglas Gregor9172aa62011-03-26 22:25:30 +00005994/// \brief Determine whether a using statement is in a context where it will be
5995/// apply in all contexts.
5996static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5997 switch (CurContext->getDeclKind()) {
5998 case Decl::TranslationUnit:
5999 return true;
6000 case Decl::LinkageSpec:
6001 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6002 default:
6003 return false;
6004 }
6005}
6006
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006007namespace {
6008
6009// Callback to only accept typo corrections that are namespaces.
6010class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6011 public:
6012 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6013 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6014 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6015 }
6016 return false;
6017 }
6018};
6019
6020}
6021
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006022static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6023 CXXScopeSpec &SS,
6024 SourceLocation IdentLoc,
6025 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006026 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006027 R.clear();
6028 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006029 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006030 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006031 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
6032 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
6033 if (DeclContext *DC = S.computeDeclContext(SS, false))
6034 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6035 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6036 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6037 else
6038 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6039 << Ident << CorrectedQuotedStr
6040 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006041
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006042 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6043 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006044
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006045 Ident = Corrected.getCorrectionAsIdentifierInfo();
6046 R.addDecl(Corrected.getCorrectionDecl());
6047 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006048 }
6049 return false;
6050}
6051
John McCalld226f652010-08-21 09:40:31 +00006052Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006053 SourceLocation UsingLoc,
6054 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006055 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006056 SourceLocation IdentLoc,
6057 IdentifierInfo *NamespcName,
6058 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006059 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6060 assert(NamespcName && "Invalid NamespcName.");
6061 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006062
6063 // This can only happen along a recovery path.
6064 while (S->getFlags() & Scope::TemplateParamScope)
6065 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006066 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006067
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006068 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006069 NestedNameSpecifier *Qualifier = 0;
6070 if (SS.isSet())
6071 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6072
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006073 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006074 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6075 LookupParsedName(R, S, &SS);
6076 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006077 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006078
Douglas Gregor66992202010-06-29 17:53:46 +00006079 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006080 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006081 // Allow "using namespace std;" or "using namespace ::std;" even if
6082 // "std" hasn't been defined yet, for GCC compatibility.
6083 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6084 NamespcName->isStr("std")) {
6085 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006086 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006087 R.resolveKind();
6088 }
6089 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006090 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006091 }
6092
John McCallf36e02d2009-10-09 21:13:30 +00006093 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006094 NamedDecl *Named = R.getFoundDecl();
6095 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6096 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006097 // C++ [namespace.udir]p1:
6098 // A using-directive specifies that the names in the nominated
6099 // namespace can be used in the scope in which the
6100 // using-directive appears after the using-directive. During
6101 // unqualified name lookup (3.4.1), the names appear as if they
6102 // were declared in the nearest enclosing namespace which
6103 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006104 // namespace. [Note: in this context, "contains" means "contains
6105 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006106
6107 // Find enclosing context containing both using-directive and
6108 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006109 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006110 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6111 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6112 CommonAncestor = CommonAncestor->getParent();
6113
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006114 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006115 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006116 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006117
Douglas Gregor9172aa62011-03-26 22:25:30 +00006118 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006119 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006120 Diag(IdentLoc, diag::warn_using_directive_in_header);
6121 }
6122
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006123 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006124 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006125 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006126 }
6127
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006128 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006129 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006130}
6131
6132void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6133 // If scope has associated entity, then using directive is at namespace
6134 // or translation unit scope. We add UsingDirectiveDecls, into
6135 // it's lookup structure.
6136 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006137 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006138 else
6139 // Otherwise it is block-sope. using-directives will affect lookup
6140 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006141 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006142}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006143
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006144
John McCalld226f652010-08-21 09:40:31 +00006145Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006146 AccessSpecifier AS,
6147 bool HasUsingKeyword,
6148 SourceLocation UsingLoc,
6149 CXXScopeSpec &SS,
6150 UnqualifiedId &Name,
6151 AttributeList *AttrList,
6152 bool IsTypeName,
6153 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006154 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006155
Douglas Gregor12c118a2009-11-04 16:30:06 +00006156 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006157 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006158 case UnqualifiedId::IK_Identifier:
6159 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006160 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006161 case UnqualifiedId::IK_ConversionFunctionId:
6162 break;
6163
6164 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006165 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006166 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006167 Diag(Name.getSourceRange().getBegin(),
6168 getLangOptions().CPlusPlus0x ?
6169 diag::warn_cxx98_compat_using_decl_constructor :
6170 diag::err_using_decl_constructor)
6171 << SS.getRange();
6172
John McCall604e7f12009-12-08 07:46:18 +00006173 if (getLangOptions().CPlusPlus0x) break;
6174
John McCalld226f652010-08-21 09:40:31 +00006175 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006176
6177 case UnqualifiedId::IK_DestructorName:
6178 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6179 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006180 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006181
6182 case UnqualifiedId::IK_TemplateId:
6183 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6184 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006185 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006186 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006187
6188 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6189 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006190 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006191 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006192
John McCall60fa3cf2009-12-11 02:10:03 +00006193 // Warn about using declarations.
6194 // TODO: store that the declaration was written without 'using' and
6195 // talk about access decls instead of using decls in the
6196 // diagnostics.
6197 if (!HasUsingKeyword) {
6198 UsingLoc = Name.getSourceRange().getBegin();
6199
6200 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006201 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006202 }
6203
Douglas Gregor56c04582010-12-16 00:46:58 +00006204 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6205 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6206 return 0;
6207
John McCall9488ea12009-11-17 05:59:44 +00006208 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006209 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006210 /* IsInstantiation */ false,
6211 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006212 if (UD)
6213 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006214
John McCalld226f652010-08-21 09:40:31 +00006215 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006216}
6217
Douglas Gregor09acc982010-07-07 23:08:52 +00006218/// \brief Determine whether a using declaration considers the given
6219/// declarations as "equivalent", e.g., if they are redeclarations of
6220/// the same entity or are both typedefs of the same type.
6221static bool
6222IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6223 bool &SuppressRedeclaration) {
6224 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6225 SuppressRedeclaration = false;
6226 return true;
6227 }
6228
Richard Smith162e1c12011-04-15 14:24:37 +00006229 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6230 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006231 SuppressRedeclaration = true;
6232 return Context.hasSameType(TD1->getUnderlyingType(),
6233 TD2->getUnderlyingType());
6234 }
6235
6236 return false;
6237}
6238
6239
John McCall9f54ad42009-12-10 09:41:52 +00006240/// Determines whether to create a using shadow decl for a particular
6241/// decl, given the set of decls existing prior to this using lookup.
6242bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6243 const LookupResult &Previous) {
6244 // Diagnose finding a decl which is not from a base class of the
6245 // current class. We do this now because there are cases where this
6246 // function will silently decide not to build a shadow decl, which
6247 // will pre-empt further diagnostics.
6248 //
6249 // We don't need to do this in C++0x because we do the check once on
6250 // the qualifier.
6251 //
6252 // FIXME: diagnose the following if we care enough:
6253 // struct A { int foo; };
6254 // struct B : A { using A::foo; };
6255 // template <class T> struct C : A {};
6256 // template <class T> struct D : C<T> { using B::foo; } // <---
6257 // This is invalid (during instantiation) in C++03 because B::foo
6258 // resolves to the using decl in B, which is not a base class of D<T>.
6259 // We can't diagnose it immediately because C<T> is an unknown
6260 // specialization. The UsingShadowDecl in D<T> then points directly
6261 // to A::foo, which will look well-formed when we instantiate.
6262 // The right solution is to not collapse the shadow-decl chain.
6263 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6264 DeclContext *OrigDC = Orig->getDeclContext();
6265
6266 // Handle enums and anonymous structs.
6267 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6268 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6269 while (OrigRec->isAnonymousStructOrUnion())
6270 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6271
6272 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6273 if (OrigDC == CurContext) {
6274 Diag(Using->getLocation(),
6275 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006276 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006277 Diag(Orig->getLocation(), diag::note_using_decl_target);
6278 return true;
6279 }
6280
Douglas Gregordc355712011-02-25 00:36:19 +00006281 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006282 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006283 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006284 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006285 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006286 Diag(Orig->getLocation(), diag::note_using_decl_target);
6287 return true;
6288 }
6289 }
6290
6291 if (Previous.empty()) return false;
6292
6293 NamedDecl *Target = Orig;
6294 if (isa<UsingShadowDecl>(Target))
6295 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6296
John McCalld7533ec2009-12-11 02:33:26 +00006297 // If the target happens to be one of the previous declarations, we
6298 // don't have a conflict.
6299 //
6300 // FIXME: but we might be increasing its access, in which case we
6301 // should redeclare it.
6302 NamedDecl *NonTag = 0, *Tag = 0;
6303 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6304 I != E; ++I) {
6305 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006306 bool Result;
6307 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6308 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006309
6310 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6311 }
6312
John McCall9f54ad42009-12-10 09:41:52 +00006313 if (Target->isFunctionOrFunctionTemplate()) {
6314 FunctionDecl *FD;
6315 if (isa<FunctionTemplateDecl>(Target))
6316 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6317 else
6318 FD = cast<FunctionDecl>(Target);
6319
6320 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006321 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006322 case Ovl_Overload:
6323 return false;
6324
6325 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006326 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006327 break;
6328
6329 // We found a decl with the exact signature.
6330 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006331 // If we're in a record, we want to hide the target, so we
6332 // return true (without a diagnostic) to tell the caller not to
6333 // build a shadow decl.
6334 if (CurContext->isRecord())
6335 return true;
6336
6337 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006338 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006339 break;
6340 }
6341
6342 Diag(Target->getLocation(), diag::note_using_decl_target);
6343 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6344 return true;
6345 }
6346
6347 // Target is not a function.
6348
John McCall9f54ad42009-12-10 09:41:52 +00006349 if (isa<TagDecl>(Target)) {
6350 // No conflict between a tag and a non-tag.
6351 if (!Tag) return false;
6352
John McCall41ce66f2009-12-10 19:51:03 +00006353 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006354 Diag(Target->getLocation(), diag::note_using_decl_target);
6355 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6356 return true;
6357 }
6358
6359 // No conflict between a tag and a non-tag.
6360 if (!NonTag) return false;
6361
John McCall41ce66f2009-12-10 19:51:03 +00006362 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006363 Diag(Target->getLocation(), diag::note_using_decl_target);
6364 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6365 return true;
6366}
6367
John McCall9488ea12009-11-17 05:59:44 +00006368/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006369UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006370 UsingDecl *UD,
6371 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006372
6373 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006374 NamedDecl *Target = Orig;
6375 if (isa<UsingShadowDecl>(Target)) {
6376 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6377 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006378 }
6379
6380 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006381 = UsingShadowDecl::Create(Context, CurContext,
6382 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006383 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006384
6385 Shadow->setAccess(UD->getAccess());
6386 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6387 Shadow->setInvalidDecl();
6388
John McCall9488ea12009-11-17 05:59:44 +00006389 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006390 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006391 else
John McCall604e7f12009-12-08 07:46:18 +00006392 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006393
John McCall604e7f12009-12-08 07:46:18 +00006394
John McCall9f54ad42009-12-10 09:41:52 +00006395 return Shadow;
6396}
John McCall604e7f12009-12-08 07:46:18 +00006397
John McCall9f54ad42009-12-10 09:41:52 +00006398/// Hides a using shadow declaration. This is required by the current
6399/// using-decl implementation when a resolvable using declaration in a
6400/// class is followed by a declaration which would hide or override
6401/// one or more of the using decl's targets; for example:
6402///
6403/// struct Base { void foo(int); };
6404/// struct Derived : Base {
6405/// using Base::foo;
6406/// void foo(int);
6407/// };
6408///
6409/// The governing language is C++03 [namespace.udecl]p12:
6410///
6411/// When a using-declaration brings names from a base class into a
6412/// derived class scope, member functions in the derived class
6413/// override and/or hide member functions with the same name and
6414/// parameter types in a base class (rather than conflicting).
6415///
6416/// There are two ways to implement this:
6417/// (1) optimistically create shadow decls when they're not hidden
6418/// by existing declarations, or
6419/// (2) don't create any shadow decls (or at least don't make them
6420/// visible) until we've fully parsed/instantiated the class.
6421/// The problem with (1) is that we might have to retroactively remove
6422/// a shadow decl, which requires several O(n) operations because the
6423/// decl structures are (very reasonably) not designed for removal.
6424/// (2) avoids this but is very fiddly and phase-dependent.
6425void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006426 if (Shadow->getDeclName().getNameKind() ==
6427 DeclarationName::CXXConversionFunctionName)
6428 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6429
John McCall9f54ad42009-12-10 09:41:52 +00006430 // Remove it from the DeclContext...
6431 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006432
John McCall9f54ad42009-12-10 09:41:52 +00006433 // ...and the scope, if applicable...
6434 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006435 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006436 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006437 }
6438
John McCall9f54ad42009-12-10 09:41:52 +00006439 // ...and the using decl.
6440 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6441
6442 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006443 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006444}
6445
John McCall7ba107a2009-11-18 02:36:19 +00006446/// Builds a using declaration.
6447///
6448/// \param IsInstantiation - Whether this call arises from an
6449/// instantiation of an unresolved using declaration. We treat
6450/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006451NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6452 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006453 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006454 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006455 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006456 bool IsInstantiation,
6457 bool IsTypeName,
6458 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006459 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006460 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006461 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006462
Anders Carlsson550b14b2009-08-28 05:49:21 +00006463 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006464
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006465 if (SS.isEmpty()) {
6466 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006467 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006468 }
Mike Stump1eb44332009-09-09 15:08:12 +00006469
John McCall9f54ad42009-12-10 09:41:52 +00006470 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006471 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006472 ForRedeclaration);
6473 Previous.setHideTags(false);
6474 if (S) {
6475 LookupName(Previous, S);
6476
6477 // It is really dumb that we have to do this.
6478 LookupResult::Filter F = Previous.makeFilter();
6479 while (F.hasNext()) {
6480 NamedDecl *D = F.next();
6481 if (!isDeclInScope(D, CurContext, S))
6482 F.erase();
6483 }
6484 F.done();
6485 } else {
6486 assert(IsInstantiation && "no scope in non-instantiation");
6487 assert(CurContext->isRecord() && "scope not record in instantiation");
6488 LookupQualifiedName(Previous, CurContext);
6489 }
6490
John McCall9f54ad42009-12-10 09:41:52 +00006491 // Check for invalid redeclarations.
6492 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6493 return 0;
6494
6495 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006496 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6497 return 0;
6498
John McCallaf8e6ed2009-11-12 03:15:40 +00006499 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006500 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006501 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006502 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006503 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006504 // FIXME: not all declaration name kinds are legal here
6505 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6506 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006507 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006508 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006509 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006510 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6511 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006512 }
John McCalled976492009-12-04 22:46:56 +00006513 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006514 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6515 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006516 }
John McCalled976492009-12-04 22:46:56 +00006517 D->setAccess(AS);
6518 CurContext->addDecl(D);
6519
6520 if (!LookupContext) return D;
6521 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006522
John McCall77bb1aa2010-05-01 00:40:08 +00006523 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006524 UD->setInvalidDecl();
6525 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006526 }
6527
Sebastian Redlf677ea32011-02-05 19:23:19 +00006528 // Constructor inheriting using decls get special treatment.
6529 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006530 if (CheckInheritedConstructorUsingDecl(UD))
6531 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006532 return UD;
6533 }
6534
6535 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006536
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006537 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006538
John McCall604e7f12009-12-08 07:46:18 +00006539 // Unlike most lookups, we don't always want to hide tag
6540 // declarations: tag names are visible through the using declaration
6541 // even if hidden by ordinary names, *except* in a dependent context
6542 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006543 if (!IsInstantiation)
6544 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006545
John McCalla24dc2e2009-11-17 02:14:36 +00006546 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006547
John McCallf36e02d2009-10-09 21:13:30 +00006548 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006549 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006550 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006551 UD->setInvalidDecl();
6552 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006553 }
6554
John McCalled976492009-12-04 22:46:56 +00006555 if (R.isAmbiguous()) {
6556 UD->setInvalidDecl();
6557 return UD;
6558 }
Mike Stump1eb44332009-09-09 15:08:12 +00006559
John McCall7ba107a2009-11-18 02:36:19 +00006560 if (IsTypeName) {
6561 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006562 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006563 Diag(IdentLoc, diag::err_using_typename_non_type);
6564 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6565 Diag((*I)->getUnderlyingDecl()->getLocation(),
6566 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006567 UD->setInvalidDecl();
6568 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006569 }
6570 } else {
6571 // If we asked for a non-typename and we got a type, error out,
6572 // but only if this is an instantiation of an unresolved using
6573 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006574 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006575 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6576 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006577 UD->setInvalidDecl();
6578 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006579 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006580 }
6581
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006582 // C++0x N2914 [namespace.udecl]p6:
6583 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006584 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006585 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6586 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006587 UD->setInvalidDecl();
6588 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006589 }
Mike Stump1eb44332009-09-09 15:08:12 +00006590
John McCall9f54ad42009-12-10 09:41:52 +00006591 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6592 if (!CheckUsingShadowDecl(UD, *I, Previous))
6593 BuildUsingShadowDecl(S, UD, *I);
6594 }
John McCall9488ea12009-11-17 05:59:44 +00006595
6596 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006597}
6598
Sebastian Redlf677ea32011-02-05 19:23:19 +00006599/// Additional checks for a using declaration referring to a constructor name.
6600bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6601 if (UD->isTypeName()) {
6602 // FIXME: Cannot specify typename when specifying constructor
6603 return true;
6604 }
6605
Douglas Gregordc355712011-02-25 00:36:19 +00006606 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006607 assert(SourceType &&
6608 "Using decl naming constructor doesn't have type in scope spec.");
6609 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6610
6611 // Check whether the named type is a direct base class.
6612 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6613 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6614 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6615 BaseIt != BaseE; ++BaseIt) {
6616 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6617 if (CanonicalSourceType == BaseType)
6618 break;
6619 }
6620
6621 if (BaseIt == BaseE) {
6622 // Did not find SourceType in the bases.
6623 Diag(UD->getUsingLocation(),
6624 diag::err_using_decl_constructor_not_in_direct_base)
6625 << UD->getNameInfo().getSourceRange()
6626 << QualType(SourceType, 0) << TargetClass;
6627 return true;
6628 }
6629
6630 BaseIt->setInheritConstructors();
6631
6632 return false;
6633}
6634
John McCall9f54ad42009-12-10 09:41:52 +00006635/// Checks that the given using declaration is not an invalid
6636/// redeclaration. Note that this is checking only for the using decl
6637/// itself, not for any ill-formedness among the UsingShadowDecls.
6638bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6639 bool isTypeName,
6640 const CXXScopeSpec &SS,
6641 SourceLocation NameLoc,
6642 const LookupResult &Prev) {
6643 // C++03 [namespace.udecl]p8:
6644 // C++0x [namespace.udecl]p10:
6645 // A using-declaration is a declaration and can therefore be used
6646 // repeatedly where (and only where) multiple declarations are
6647 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006648 //
John McCall8a726212010-11-29 18:01:58 +00006649 // That's in non-member contexts.
6650 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006651 return false;
6652
6653 NestedNameSpecifier *Qual
6654 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6655
6656 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6657 NamedDecl *D = *I;
6658
6659 bool DTypename;
6660 NestedNameSpecifier *DQual;
6661 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6662 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006663 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006664 } else if (UnresolvedUsingValueDecl *UD
6665 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6666 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006667 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006668 } else if (UnresolvedUsingTypenameDecl *UD
6669 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6670 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006671 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006672 } else continue;
6673
6674 // using decls differ if one says 'typename' and the other doesn't.
6675 // FIXME: non-dependent using decls?
6676 if (isTypeName != DTypename) continue;
6677
6678 // using decls differ if they name different scopes (but note that
6679 // template instantiation can cause this check to trigger when it
6680 // didn't before instantiation).
6681 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6682 Context.getCanonicalNestedNameSpecifier(DQual))
6683 continue;
6684
6685 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006686 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006687 return true;
6688 }
6689
6690 return false;
6691}
6692
John McCall604e7f12009-12-08 07:46:18 +00006693
John McCalled976492009-12-04 22:46:56 +00006694/// Checks that the given nested-name qualifier used in a using decl
6695/// in the current context is appropriately related to the current
6696/// scope. If an error is found, diagnoses it and returns true.
6697bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6698 const CXXScopeSpec &SS,
6699 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006700 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006701
John McCall604e7f12009-12-08 07:46:18 +00006702 if (!CurContext->isRecord()) {
6703 // C++03 [namespace.udecl]p3:
6704 // C++0x [namespace.udecl]p8:
6705 // A using-declaration for a class member shall be a member-declaration.
6706
6707 // If we weren't able to compute a valid scope, it must be a
6708 // dependent class scope.
6709 if (!NamedContext || NamedContext->isRecord()) {
6710 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6711 << SS.getRange();
6712 return true;
6713 }
6714
6715 // Otherwise, everything is known to be fine.
6716 return false;
6717 }
6718
6719 // The current scope is a record.
6720
6721 // If the named context is dependent, we can't decide much.
6722 if (!NamedContext) {
6723 // FIXME: in C++0x, we can diagnose if we can prove that the
6724 // nested-name-specifier does not refer to a base class, which is
6725 // still possible in some cases.
6726
6727 // Otherwise we have to conservatively report that things might be
6728 // okay.
6729 return false;
6730 }
6731
6732 if (!NamedContext->isRecord()) {
6733 // Ideally this would point at the last name in the specifier,
6734 // but we don't have that level of source info.
6735 Diag(SS.getRange().getBegin(),
6736 diag::err_using_decl_nested_name_specifier_is_not_class)
6737 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6738 return true;
6739 }
6740
Douglas Gregor6fb07292010-12-21 07:41:49 +00006741 if (!NamedContext->isDependentContext() &&
6742 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6743 return true;
6744
John McCall604e7f12009-12-08 07:46:18 +00006745 if (getLangOptions().CPlusPlus0x) {
6746 // C++0x [namespace.udecl]p3:
6747 // In a using-declaration used as a member-declaration, the
6748 // nested-name-specifier shall name a base class of the class
6749 // being defined.
6750
6751 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6752 cast<CXXRecordDecl>(NamedContext))) {
6753 if (CurContext == NamedContext) {
6754 Diag(NameLoc,
6755 diag::err_using_decl_nested_name_specifier_is_current_class)
6756 << SS.getRange();
6757 return true;
6758 }
6759
6760 Diag(SS.getRange().getBegin(),
6761 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6762 << (NestedNameSpecifier*) SS.getScopeRep()
6763 << cast<CXXRecordDecl>(CurContext)
6764 << SS.getRange();
6765 return true;
6766 }
6767
6768 return false;
6769 }
6770
6771 // C++03 [namespace.udecl]p4:
6772 // A using-declaration used as a member-declaration shall refer
6773 // to a member of a base class of the class being defined [etc.].
6774
6775 // Salient point: SS doesn't have to name a base class as long as
6776 // lookup only finds members from base classes. Therefore we can
6777 // diagnose here only if we can prove that that can't happen,
6778 // i.e. if the class hierarchies provably don't intersect.
6779
6780 // TODO: it would be nice if "definitely valid" results were cached
6781 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6782 // need to be repeated.
6783
6784 struct UserData {
6785 llvm::DenseSet<const CXXRecordDecl*> Bases;
6786
6787 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6788 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6789 Data->Bases.insert(Base);
6790 return true;
6791 }
6792
6793 bool hasDependentBases(const CXXRecordDecl *Class) {
6794 return !Class->forallBases(collect, this);
6795 }
6796
6797 /// Returns true if the base is dependent or is one of the
6798 /// accumulated base classes.
6799 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6800 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6801 return !Data->Bases.count(Base);
6802 }
6803
6804 bool mightShareBases(const CXXRecordDecl *Class) {
6805 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6806 }
6807 };
6808
6809 UserData Data;
6810
6811 // Returns false if we find a dependent base.
6812 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6813 return false;
6814
6815 // Returns false if the class has a dependent base or if it or one
6816 // of its bases is present in the base set of the current context.
6817 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6818 return false;
6819
6820 Diag(SS.getRange().getBegin(),
6821 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6822 << (NestedNameSpecifier*) SS.getScopeRep()
6823 << cast<CXXRecordDecl>(CurContext)
6824 << SS.getRange();
6825
6826 return true;
John McCalled976492009-12-04 22:46:56 +00006827}
6828
Richard Smith162e1c12011-04-15 14:24:37 +00006829Decl *Sema::ActOnAliasDeclaration(Scope *S,
6830 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006831 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006832 SourceLocation UsingLoc,
6833 UnqualifiedId &Name,
6834 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006835 // Skip up to the relevant declaration scope.
6836 while (S->getFlags() & Scope::TemplateParamScope)
6837 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006838 assert((S->getFlags() & Scope::DeclScope) &&
6839 "got alias-declaration outside of declaration scope");
6840
6841 if (Type.isInvalid())
6842 return 0;
6843
6844 bool Invalid = false;
6845 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6846 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006847 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006848
6849 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6850 return 0;
6851
6852 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006853 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006854 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006855 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6856 TInfo->getTypeLoc().getBeginLoc());
6857 }
Richard Smith162e1c12011-04-15 14:24:37 +00006858
6859 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6860 LookupName(Previous, S);
6861
6862 // Warn about shadowing the name of a template parameter.
6863 if (Previous.isSingleResult() &&
6864 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006865 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006866 Previous.clear();
6867 }
6868
6869 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6870 "name in alias declaration must be an identifier");
6871 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6872 Name.StartLocation,
6873 Name.Identifier, TInfo);
6874
6875 NewTD->setAccess(AS);
6876
6877 if (Invalid)
6878 NewTD->setInvalidDecl();
6879
Richard Smith3e4c6c42011-05-05 21:57:07 +00006880 CheckTypedefForVariablyModifiedType(S, NewTD);
6881 Invalid |= NewTD->isInvalidDecl();
6882
Richard Smith162e1c12011-04-15 14:24:37 +00006883 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006884
6885 NamedDecl *NewND;
6886 if (TemplateParamLists.size()) {
6887 TypeAliasTemplateDecl *OldDecl = 0;
6888 TemplateParameterList *OldTemplateParams = 0;
6889
6890 if (TemplateParamLists.size() != 1) {
6891 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6892 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6893 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6894 }
6895 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6896
6897 // Only consider previous declarations in the same scope.
6898 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6899 /*ExplicitInstantiationOrSpecialization*/false);
6900 if (!Previous.empty()) {
6901 Redeclaration = true;
6902
6903 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6904 if (!OldDecl && !Invalid) {
6905 Diag(UsingLoc, diag::err_redefinition_different_kind)
6906 << Name.Identifier;
6907
6908 NamedDecl *OldD = Previous.getRepresentativeDecl();
6909 if (OldD->getLocation().isValid())
6910 Diag(OldD->getLocation(), diag::note_previous_definition);
6911
6912 Invalid = true;
6913 }
6914
6915 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6916 if (TemplateParameterListsAreEqual(TemplateParams,
6917 OldDecl->getTemplateParameters(),
6918 /*Complain=*/true,
6919 TPL_TemplateMatch))
6920 OldTemplateParams = OldDecl->getTemplateParameters();
6921 else
6922 Invalid = true;
6923
6924 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6925 if (!Invalid &&
6926 !Context.hasSameType(OldTD->getUnderlyingType(),
6927 NewTD->getUnderlyingType())) {
6928 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6929 // but we can't reasonably accept it.
6930 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6931 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6932 if (OldTD->getLocation().isValid())
6933 Diag(OldTD->getLocation(), diag::note_previous_definition);
6934 Invalid = true;
6935 }
6936 }
6937 }
6938
6939 // Merge any previous default template arguments into our parameters,
6940 // and check the parameter list.
6941 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6942 TPC_TypeAliasTemplate))
6943 return 0;
6944
6945 TypeAliasTemplateDecl *NewDecl =
6946 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6947 Name.Identifier, TemplateParams,
6948 NewTD);
6949
6950 NewDecl->setAccess(AS);
6951
6952 if (Invalid)
6953 NewDecl->setInvalidDecl();
6954 else if (OldDecl)
6955 NewDecl->setPreviousDeclaration(OldDecl);
6956
6957 NewND = NewDecl;
6958 } else {
6959 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6960 NewND = NewTD;
6961 }
Richard Smith162e1c12011-04-15 14:24:37 +00006962
6963 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006964 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006965
Richard Smith3e4c6c42011-05-05 21:57:07 +00006966 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006967}
6968
John McCalld226f652010-08-21 09:40:31 +00006969Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006970 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006971 SourceLocation AliasLoc,
6972 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006973 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006974 SourceLocation IdentLoc,
6975 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006976
Anders Carlsson81c85c42009-03-28 23:53:49 +00006977 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006978 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6979 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006980
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006981 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006982 NamedDecl *PrevDecl
6983 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6984 ForRedeclaration);
6985 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6986 PrevDecl = 0;
6987
6988 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006989 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006990 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006991 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006992 // FIXME: At some point, we'll want to create the (redundant)
6993 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006994 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006995 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006996 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006997 }
Mike Stump1eb44332009-09-09 15:08:12 +00006998
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006999 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7000 diag::err_redefinition_different_kind;
7001 Diag(AliasLoc, DiagID) << Alias;
7002 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007003 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007004 }
7005
John McCalla24dc2e2009-11-17 02:14:36 +00007006 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007007 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007008
John McCallf36e02d2009-10-09 21:13:30 +00007009 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007010 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007011 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007012 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007013 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007014 }
Mike Stump1eb44332009-09-09 15:08:12 +00007015
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007016 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007017 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007018 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007019 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007020
John McCall3dbd3d52010-02-16 06:53:13 +00007021 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007022 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007023}
7024
Douglas Gregor39957dc2010-05-01 15:04:51 +00007025namespace {
7026 /// \brief Scoped object used to handle the state changes required in Sema
7027 /// to implicitly define the body of a C++ member function;
7028 class ImplicitlyDefinedFunctionScope {
7029 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00007030 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00007031
7032 public:
7033 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00007034 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00007035 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00007036 S.PushFunctionScope();
7037 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
7038 }
7039
7040 ~ImplicitlyDefinedFunctionScope() {
7041 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00007042 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00007043 }
7044 };
7045}
7046
Sean Hunt001cad92011-05-10 00:49:42 +00007047Sema::ImplicitExceptionSpecification
7048Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007049 // C++ [except.spec]p14:
7050 // An implicitly declared special member function (Clause 12) shall have an
7051 // exception-specification. [...]
7052 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007053 if (ClassDecl->isInvalidDecl())
7054 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007055
Sebastian Redl60618fa2011-03-12 11:50:43 +00007056 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007057 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7058 BEnd = ClassDecl->bases_end();
7059 B != BEnd; ++B) {
7060 if (B->isVirtual()) // Handled below.
7061 continue;
7062
Douglas Gregor18274032010-07-03 00:47:00 +00007063 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7064 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007065 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7066 // If this is a deleted function, add it anyway. This might be conformant
7067 // with the standard. This might not. I'm not sure. It might not matter.
7068 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007069 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007070 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007071 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007072
7073 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007074 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7075 BEnd = ClassDecl->vbases_end();
7076 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007077 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7078 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007079 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7080 // If this is a deleted function, add it anyway. This might be conformant
7081 // with the standard. This might not. I'm not sure. It might not matter.
7082 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007083 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007084 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007085 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007086
7087 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007088 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7089 FEnd = ClassDecl->field_end();
7090 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007091 if (F->hasInClassInitializer()) {
7092 if (Expr *E = F->getInClassInitializer())
7093 ExceptSpec.CalledExpr(E);
7094 else if (!F->isInvalidDecl())
7095 ExceptSpec.SetDelayed();
7096 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007097 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007098 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7099 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7100 // If this is a deleted function, add it anyway. This might be conformant
7101 // with the standard. This might not. I'm not sure. It might not matter.
7102 // In particular, the problem is that this function never gets called. It
7103 // might just be ill-formed because this function attempts to refer to
7104 // a deleted function here.
7105 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007106 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007107 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007108 }
John McCalle23cf432010-12-14 08:05:40 +00007109
Sean Hunt001cad92011-05-10 00:49:42 +00007110 return ExceptSpec;
7111}
7112
7113CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7114 CXXRecordDecl *ClassDecl) {
7115 // C++ [class.ctor]p5:
7116 // A default constructor for a class X is a constructor of class X
7117 // that can be called without an argument. If there is no
7118 // user-declared constructor for class X, a default constructor is
7119 // implicitly declared. An implicitly-declared default constructor
7120 // is an inline public member of its class.
7121 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7122 "Should not build implicit default constructor!");
7123
7124 ImplicitExceptionSpecification Spec =
7125 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7126 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007127
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007128 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007129 CanQualType ClassType
7130 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007131 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007132 DeclarationName Name
7133 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007134 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007135 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7136 Context, ClassDecl, ClassLoc, NameInfo,
7137 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7138 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7139 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7140 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007141 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007142 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007143 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007144 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007145
7146 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007147 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7148
Douglas Gregor23c94db2010-07-02 17:43:08 +00007149 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007150 PushOnScopeChains(DefaultCon, S, false);
7151 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007152
Sean Hunte16da072011-10-10 06:18:57 +00007153 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007154 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007155
Douglas Gregor32df23e2010-07-01 22:02:46 +00007156 return DefaultCon;
7157}
7158
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007159void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7160 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007161 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007162 !Constructor->doesThisDeclarationHaveABody() &&
7163 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007164 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007165
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007166 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007167 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007168
Douglas Gregor39957dc2010-05-01 15:04:51 +00007169 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007170 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007171 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007172 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007173 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007174 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007175 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007176 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007177 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007178
7179 SourceLocation Loc = Constructor->getLocation();
7180 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7181
7182 Constructor->setUsed();
7183 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007184
7185 if (ASTMutationListener *L = getASTMutationListener()) {
7186 L->CompletedImplicitDefinition(Constructor);
7187 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007188}
7189
Richard Smith7a614d82011-06-11 17:19:42 +00007190/// Get any existing defaulted default constructor for the given class. Do not
7191/// implicitly define one if it does not exist.
7192static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7193 CXXRecordDecl *D) {
7194 ASTContext &Context = Self.Context;
7195 QualType ClassType = Context.getTypeDeclType(D);
7196 DeclarationName ConstructorName
7197 = Context.DeclarationNames.getCXXConstructorName(
7198 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7199
7200 DeclContext::lookup_const_iterator Con, ConEnd;
7201 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7202 Con != ConEnd; ++Con) {
7203 // A function template cannot be defaulted.
7204 if (isa<FunctionTemplateDecl>(*Con))
7205 continue;
7206
7207 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7208 if (Constructor->isDefaultConstructor())
7209 return Constructor->isDefaulted() ? Constructor : 0;
7210 }
7211 return 0;
7212}
7213
7214void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7215 if (!D) return;
7216 AdjustDeclIfTemplate(D);
7217
7218 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7219 CXXConstructorDecl *CtorDecl
7220 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7221
7222 if (!CtorDecl) return;
7223
7224 // Compute the exception specification for the default constructor.
7225 const FunctionProtoType *CtorTy =
7226 CtorDecl->getType()->castAs<FunctionProtoType>();
7227 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7228 ImplicitExceptionSpecification Spec =
7229 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7230 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7231 assert(EPI.ExceptionSpecType != EST_Delayed);
7232
7233 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7234 }
7235
7236 // If the default constructor is explicitly defaulted, checking the exception
7237 // specification is deferred until now.
7238 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7239 !ClassDecl->isDependentType())
7240 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7241}
7242
Sebastian Redlf677ea32011-02-05 19:23:19 +00007243void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7244 // We start with an initial pass over the base classes to collect those that
7245 // inherit constructors from. If there are none, we can forgo all further
7246 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007247 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007248 BasesVector BasesToInheritFrom;
7249 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7250 BaseE = ClassDecl->bases_end();
7251 BaseIt != BaseE; ++BaseIt) {
7252 if (BaseIt->getInheritConstructors()) {
7253 QualType Base = BaseIt->getType();
7254 if (Base->isDependentType()) {
7255 // If we inherit constructors from anything that is dependent, just
7256 // abort processing altogether. We'll get another chance for the
7257 // instantiations.
7258 return;
7259 }
7260 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7261 }
7262 }
7263 if (BasesToInheritFrom.empty())
7264 return;
7265
7266 // Now collect the constructors that we already have in the current class.
7267 // Those take precedence over inherited constructors.
7268 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7269 // unless there is a user-declared constructor with the same signature in
7270 // the class where the using-declaration appears.
7271 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7272 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7273 CtorE = ClassDecl->ctor_end();
7274 CtorIt != CtorE; ++CtorIt) {
7275 ExistingConstructors.insert(
7276 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7277 }
7278
7279 Scope *S = getScopeForContext(ClassDecl);
7280 DeclarationName CreatedCtorName =
7281 Context.DeclarationNames.getCXXConstructorName(
7282 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7283
7284 // Now comes the true work.
7285 // First, we keep a map from constructor types to the base that introduced
7286 // them. Needed for finding conflicting constructors. We also keep the
7287 // actually inserted declarations in there, for pretty diagnostics.
7288 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7289 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7290 ConstructorToSourceMap InheritedConstructors;
7291 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7292 BaseE = BasesToInheritFrom.end();
7293 BaseIt != BaseE; ++BaseIt) {
7294 const RecordType *Base = *BaseIt;
7295 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7296 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7297 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7298 CtorE = BaseDecl->ctor_end();
7299 CtorIt != CtorE; ++CtorIt) {
7300 // Find the using declaration for inheriting this base's constructors.
7301 DeclarationName Name =
7302 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7303 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7304 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7305 SourceLocation UsingLoc = UD ? UD->getLocation() :
7306 ClassDecl->getLocation();
7307
7308 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7309 // from the class X named in the using-declaration consists of actual
7310 // constructors and notional constructors that result from the
7311 // transformation of defaulted parameters as follows:
7312 // - all non-template default constructors of X, and
7313 // - for each non-template constructor of X that has at least one
7314 // parameter with a default argument, the set of constructors that
7315 // results from omitting any ellipsis parameter specification and
7316 // successively omitting parameters with a default argument from the
7317 // end of the parameter-type-list.
7318 CXXConstructorDecl *BaseCtor = *CtorIt;
7319 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7320 const FunctionProtoType *BaseCtorType =
7321 BaseCtor->getType()->getAs<FunctionProtoType>();
7322
7323 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7324 maxParams = BaseCtor->getNumParams();
7325 params <= maxParams; ++params) {
7326 // Skip default constructors. They're never inherited.
7327 if (params == 0)
7328 continue;
7329 // Skip copy and move constructors for the same reason.
7330 if (CanBeCopyOrMove && params == 1)
7331 continue;
7332
7333 // Build up a function type for this particular constructor.
7334 // FIXME: The working paper does not consider that the exception spec
7335 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007336 // source. This code doesn't yet, either. When it does, this code will
7337 // need to be delayed until after exception specifications and in-class
7338 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007339 const Type *NewCtorType;
7340 if (params == maxParams)
7341 NewCtorType = BaseCtorType;
7342 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007343 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007344 for (unsigned i = 0; i < params; ++i) {
7345 Args.push_back(BaseCtorType->getArgType(i));
7346 }
7347 FunctionProtoType::ExtProtoInfo ExtInfo =
7348 BaseCtorType->getExtProtoInfo();
7349 ExtInfo.Variadic = false;
7350 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7351 Args.data(), params, ExtInfo)
7352 .getTypePtr();
7353 }
7354 const Type *CanonicalNewCtorType =
7355 Context.getCanonicalType(NewCtorType);
7356
7357 // Now that we have the type, first check if the class already has a
7358 // constructor with this signature.
7359 if (ExistingConstructors.count(CanonicalNewCtorType))
7360 continue;
7361
7362 // Then we check if we have already declared an inherited constructor
7363 // with this signature.
7364 std::pair<ConstructorToSourceMap::iterator, bool> result =
7365 InheritedConstructors.insert(std::make_pair(
7366 CanonicalNewCtorType,
7367 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7368 if (!result.second) {
7369 // Already in the map. If it came from a different class, that's an
7370 // error. Not if it's from the same.
7371 CanQualType PreviousBase = result.first->second.first;
7372 if (CanonicalBase != PreviousBase) {
7373 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7374 const CXXConstructorDecl *PrevBaseCtor =
7375 PrevCtor->getInheritedConstructor();
7376 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7377
7378 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7379 Diag(BaseCtor->getLocation(),
7380 diag::note_using_decl_constructor_conflict_current_ctor);
7381 Diag(PrevBaseCtor->getLocation(),
7382 diag::note_using_decl_constructor_conflict_previous_ctor);
7383 Diag(PrevCtor->getLocation(),
7384 diag::note_using_decl_constructor_conflict_previous_using);
7385 }
7386 continue;
7387 }
7388
7389 // OK, we're there, now add the constructor.
7390 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007391 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007392 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7393 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007394 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7395 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007396 /*ImplicitlyDeclared=*/true,
7397 // FIXME: Due to a defect in the standard, we treat inherited
7398 // constructors as constexpr even if that makes them ill-formed.
7399 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007400 NewCtor->setAccess(BaseCtor->getAccess());
7401
7402 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007403 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007404 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007405 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7406 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007407 /*IdentifierInfo=*/0,
7408 BaseCtorType->getArgType(i),
7409 /*TInfo=*/0, SC_None,
7410 SC_None, /*DefaultArg=*/0));
7411 }
David Blaikie4278c652011-09-21 18:16:56 +00007412 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007413 NewCtor->setInheritedConstructor(BaseCtor);
7414
7415 PushOnScopeChains(NewCtor, S, false);
7416 ClassDecl->addDecl(NewCtor);
7417 result.first->second.second = NewCtor;
7418 }
7419 }
7420 }
7421}
7422
Sean Huntcb45a0f2011-05-12 22:46:25 +00007423Sema::ImplicitExceptionSpecification
7424Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007425 // C++ [except.spec]p14:
7426 // An implicitly declared special member function (Clause 12) shall have
7427 // an exception-specification.
7428 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007429 if (ClassDecl->isInvalidDecl())
7430 return ExceptSpec;
7431
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007432 // Direct base-class destructors.
7433 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7434 BEnd = ClassDecl->bases_end();
7435 B != BEnd; ++B) {
7436 if (B->isVirtual()) // Handled below.
7437 continue;
7438
7439 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7440 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007441 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007442 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007443
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007444 // Virtual base-class destructors.
7445 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7446 BEnd = ClassDecl->vbases_end();
7447 B != BEnd; ++B) {
7448 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7449 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007450 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007451 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007452
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007453 // Field destructors.
7454 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7455 FEnd = ClassDecl->field_end();
7456 F != FEnd; ++F) {
7457 if (const RecordType *RecordTy
7458 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7459 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007460 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007461 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007462
Sean Huntcb45a0f2011-05-12 22:46:25 +00007463 return ExceptSpec;
7464}
7465
7466CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7467 // C++ [class.dtor]p2:
7468 // If a class has no user-declared destructor, a destructor is
7469 // declared implicitly. An implicitly-declared destructor is an
7470 // inline public member of its class.
7471
7472 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007473 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007474 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7475
Douglas Gregor4923aa22010-07-02 20:37:36 +00007476 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007477 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007478
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007479 CanQualType ClassType
7480 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007481 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007482 DeclarationName Name
7483 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007484 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007485 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007486 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7487 /*isInline=*/true,
7488 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007489 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007490 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007491 Destructor->setImplicit();
7492 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007493
7494 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007495 ++ASTContext::NumImplicitDestructorsDeclared;
7496
7497 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007498 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007499 PushOnScopeChains(Destructor, S, false);
7500 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007501
7502 // This could be uniqued if it ever proves significant.
7503 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007504
7505 if (ShouldDeleteDestructor(Destructor))
7506 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007507
7508 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007509
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007510 return Destructor;
7511}
7512
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007513void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007514 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007515 assert((Destructor->isDefaulted() &&
7516 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007517 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007518 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007519 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007520
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007521 if (Destructor->isInvalidDecl())
7522 return;
7523
Douglas Gregor39957dc2010-05-01 15:04:51 +00007524 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007525
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007526 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007527 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7528 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007529
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007530 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007531 Diag(CurrentLocation, diag::note_member_synthesized_at)
7532 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7533
7534 Destructor->setInvalidDecl();
7535 return;
7536 }
7537
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007538 SourceLocation Loc = Destructor->getLocation();
7539 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007540 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007541 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007542 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007543
7544 if (ASTMutationListener *L = getASTMutationListener()) {
7545 L->CompletedImplicitDefinition(Destructor);
7546 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007547}
7548
Sebastian Redl0ee33912011-05-19 05:13:44 +00007549void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7550 CXXDestructorDecl *destructor) {
7551 // C++11 [class.dtor]p3:
7552 // A declaration of a destructor that does not have an exception-
7553 // specification is implicitly considered to have the same exception-
7554 // specification as an implicit declaration.
7555 const FunctionProtoType *dtorType = destructor->getType()->
7556 getAs<FunctionProtoType>();
7557 if (dtorType->hasExceptionSpec())
7558 return;
7559
7560 ImplicitExceptionSpecification exceptSpec =
7561 ComputeDefaultedDtorExceptionSpec(classDecl);
7562
Chandler Carruth3f224b22011-09-20 04:55:26 +00007563 // Replace the destructor's type, building off the existing one. Fortunately,
7564 // the only thing of interest in the destructor type is its extended info.
7565 // The return and arguments are fixed.
7566 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007567 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7568 epi.NumExceptions = exceptSpec.size();
7569 epi.Exceptions = exceptSpec.data();
7570 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7571
7572 destructor->setType(ty);
7573
7574 // FIXME: If the destructor has a body that could throw, and the newly created
7575 // spec doesn't allow exceptions, we should emit a warning, because this
7576 // change in behavior can break conforming C++03 programs at runtime.
7577 // However, we don't have a body yet, so it needs to be done somewhere else.
7578}
7579
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007580/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007581/// \c To.
7582///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007583/// This routine is used to copy/move the members of a class with an
7584/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007585/// copied are arrays, this routine builds for loops to copy them.
7586///
7587/// \param S The Sema object used for type-checking.
7588///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007589/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007590///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007591/// \param T The type of the expressions being copied/moved. Both expressions
7592/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007593///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007594/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007595///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007596/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007597///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007598/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007599/// Otherwise, it's a non-static member subobject.
7600///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007601/// \param Copying Whether we're copying or moving.
7602///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007603/// \param Depth Internal parameter recording the depth of the recursion.
7604///
7605/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007606static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007607BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007608 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007609 bool CopyingBaseSubobject, bool Copying,
7610 unsigned Depth = 0) {
7611 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007612 // Each subobject is assigned in the manner appropriate to its type:
7613 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007614 // - if the subobject is of class type, as if by a call to operator= with
7615 // the subobject as the object expression and the corresponding
7616 // subobject of x as a single function argument (as if by explicit
7617 // qualification; that is, ignoring any possible virtual overriding
7618 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7620 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7621
7622 // Look for operator=.
7623 DeclarationName Name
7624 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7625 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7626 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7627
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007628 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007629 LookupResult::Filter F = OpLookup.makeFilter();
7630 while (F.hasNext()) {
7631 NamedDecl *D = F.next();
7632 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007633 if (Copying ? Method->isCopyAssignmentOperator() :
7634 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007635 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007636
Douglas Gregor06a9f362010-05-01 20:49:11 +00007637 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007638 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007639 F.done();
7640
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007641 // Suppress the protected check (C++ [class.protected]) for each of the
7642 // assignment operators we found. This strange dance is required when
7643 // we're assigning via a base classes's copy-assignment operator. To
7644 // ensure that we're getting the right base class subobject (without
7645 // ambiguities), we need to cast "this" to that subobject type; to
7646 // ensure that we don't go through the virtual call mechanism, we need
7647 // to qualify the operator= name with the base class (see below). However,
7648 // this means that if the base class has a protected copy assignment
7649 // operator, the protected member access check will fail. So, we
7650 // rewrite "protected" access to "public" access in this case, since we
7651 // know by construction that we're calling from a derived class.
7652 if (CopyingBaseSubobject) {
7653 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7654 L != LEnd; ++L) {
7655 if (L.getAccess() == AS_protected)
7656 L.setAccess(AS_public);
7657 }
7658 }
7659
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660 // Create the nested-name-specifier that will be used to qualify the
7661 // reference to operator=; this is required to suppress the virtual
7662 // call mechanism.
7663 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007664 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007665 SS.MakeTrivial(S.Context,
7666 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007667 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007668 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669
7670 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007671 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007672 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007673 /*TemplateKWLoc=*/SourceLocation(),
7674 /*FirstQualifierInScope=*/0,
7675 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007676 /*TemplateArgs=*/0,
7677 /*SuppressQualifierCheck=*/true);
7678 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007679 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007680
7681 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007682
John McCall60d7b3a2010-08-24 06:29:42 +00007683 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007684 OpEqualRef.takeAs<Expr>(),
7685 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007686 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007687 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007688
7689 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007690 }
John McCallb0207482010-03-16 06:11:48 +00007691
Douglas Gregor06a9f362010-05-01 20:49:11 +00007692 // - if the subobject is of scalar type, the built-in assignment
7693 // operator is used.
7694 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7695 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007696 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007697 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007698 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007699
7700 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007701 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007702
7703 // - if the subobject is an array, each element is assigned, in the
7704 // manner appropriate to the element type;
7705
7706 // Construct a loop over the array bounds, e.g.,
7707 //
7708 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7709 //
7710 // that will copy each of the array elements.
7711 QualType SizeType = S.Context.getSizeType();
7712
7713 // Create the iteration variable.
7714 IdentifierInfo *IterationVarName = 0;
7715 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007716 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007717 llvm::raw_svector_ostream OS(Str);
7718 OS << "__i" << Depth;
7719 IterationVarName = &S.Context.Idents.get(OS.str());
7720 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007721 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007722 IterationVarName, SizeType,
7723 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007724 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007725
7726 // Initialize the iteration variable to zero.
7727 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007728 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007729
7730 // Create a reference to the iteration variable; we'll use this several
7731 // times throughout.
7732 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007733 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007734 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007735 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7736 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7737
Douglas Gregor06a9f362010-05-01 20:49:11 +00007738 // Create the DeclStmt that holds the iteration variable.
7739 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7740
7741 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007742 llvm::APInt Upper
7743 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007744 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007745 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007746 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7747 BO_NE, S.Context.BoolTy,
7748 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007749
7750 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007751 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007752 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7753 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007754
7755 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007756 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007757 IterationVarRefRVal,
7758 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007759 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007760 IterationVarRefRVal,
7761 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007762 if (!Copying) // Cast to rvalue
7763 From = CastForMoving(S, From);
7764
7765 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007766 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7767 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007768 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007769 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007770 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007771
7772 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007773 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007774 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007775 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007776 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007777}
7778
Sean Hunt30de05c2011-05-14 05:23:20 +00007779std::pair<Sema::ImplicitExceptionSpecification, bool>
7780Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7781 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007782 if (ClassDecl->isInvalidDecl())
7783 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7784
Douglas Gregord3c35902010-07-01 16:36:15 +00007785 // C++ [class.copy]p10:
7786 // If the class definition does not explicitly declare a copy
7787 // assignment operator, one is declared implicitly.
7788 // The implicitly-defined copy assignment operator for a class X
7789 // will have the form
7790 //
7791 // X& X::operator=(const X&)
7792 //
7793 // if
7794 bool HasConstCopyAssignment = true;
7795
7796 // -- each direct base class B of X has a copy assignment operator
7797 // whose parameter is of type const B&, const volatile B& or B,
7798 // and
7799 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7800 BaseEnd = ClassDecl->bases_end();
7801 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007802 // We'll handle this below
7803 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7804 continue;
7805
Douglas Gregord3c35902010-07-01 16:36:15 +00007806 assert(!Base->getType()->isDependentType() &&
7807 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007808 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7809 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7810 &HasConstCopyAssignment);
7811 }
7812
Richard Smithebaf0e62011-10-18 20:49:44 +00007813 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007814 if (LangOpts.CPlusPlus0x) {
7815 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7816 BaseEnd = ClassDecl->vbases_end();
7817 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7818 assert(!Base->getType()->isDependentType() &&
7819 "Cannot generate implicit members for class with dependent bases.");
7820 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7821 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7822 &HasConstCopyAssignment);
7823 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007824 }
7825
7826 // -- for all the nonstatic data members of X that are of a class
7827 // type M (or array thereof), each such class type has a copy
7828 // assignment operator whose parameter is of type const M&,
7829 // const volatile M& or M.
7830 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7831 FieldEnd = ClassDecl->field_end();
7832 HasConstCopyAssignment && Field != FieldEnd;
7833 ++Field) {
7834 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007835 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7836 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7837 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007838 }
7839 }
7840
7841 // Otherwise, the implicitly declared copy assignment operator will
7842 // have the form
7843 //
7844 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007845
Douglas Gregorb87786f2010-07-01 17:48:08 +00007846 // C++ [except.spec]p14:
7847 // An implicitly declared special member function (Clause 12) shall have an
7848 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007849
7850 // It is unspecified whether or not an implicit copy assignment operator
7851 // attempts to deduplicate calls to assignment operators of virtual bases are
7852 // made. As such, this exception specification is effectively unspecified.
7853 // Based on a similar decision made for constness in C++0x, we're erring on
7854 // the side of assuming such calls to be made regardless of whether they
7855 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007856 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007857 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007858 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7859 BaseEnd = ClassDecl->bases_end();
7860 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007861 if (Base->isVirtual())
7862 continue;
7863
Douglas Gregora376d102010-07-02 21:50:04 +00007864 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007865 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007866 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7867 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007868 ExceptSpec.CalledDecl(CopyAssign);
7869 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007870
7871 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7872 BaseEnd = ClassDecl->vbases_end();
7873 Base != BaseEnd; ++Base) {
7874 CXXRecordDecl *BaseClassDecl
7875 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7876 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7877 ArgQuals, false, 0))
7878 ExceptSpec.CalledDecl(CopyAssign);
7879 }
7880
Douglas Gregorb87786f2010-07-01 17:48:08 +00007881 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7882 FieldEnd = ClassDecl->field_end();
7883 Field != FieldEnd;
7884 ++Field) {
7885 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007886 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7887 if (CXXMethodDecl *CopyAssign =
7888 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7889 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007890 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007891 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007892
Sean Hunt30de05c2011-05-14 05:23:20 +00007893 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7894}
7895
7896CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7897 // Note: The following rules are largely analoguous to the copy
7898 // constructor rules. Note that virtual bases are not taken into account
7899 // for determining the argument type of the operator. Note also that
7900 // operators taking an object instead of a reference are allowed.
7901
7902 ImplicitExceptionSpecification Spec(Context);
7903 bool Const;
7904 llvm::tie(Spec, Const) =
7905 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7906
7907 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7908 QualType RetType = Context.getLValueReferenceType(ArgType);
7909 if (Const)
7910 ArgType = ArgType.withConst();
7911 ArgType = Context.getLValueReferenceType(ArgType);
7912
Douglas Gregord3c35902010-07-01 16:36:15 +00007913 // An implicitly-declared copy assignment operator is an inline public
7914 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007915 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007916 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007917 SourceLocation ClassLoc = ClassDecl->getLocation();
7918 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007919 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007920 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007921 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007922 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007923 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007924 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007925 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007926 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007927 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007928 CopyAssignment->setImplicit();
7929 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007930
7931 // Add the parameter to the operator.
7932 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007933 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007934 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007935 SC_None,
7936 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007937 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007938
Douglas Gregora376d102010-07-02 21:50:04 +00007939 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007940 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007941
Douglas Gregor23c94db2010-07-02 17:43:08 +00007942 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007943 PushOnScopeChains(CopyAssignment, S, false);
7944 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007945
Nico Weberafcc96a2012-01-23 03:19:29 +00007946 // C++0x [class.copy]p19:
7947 // .... If the class definition does not explicitly declare a copy
7948 // assignment operator, there is no user-declared move constructor, and
7949 // there is no user-declared move assignment operator, a copy assignment
7950 // operator is implicitly declared as defaulted.
7951 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007952 !getLangOptions().MicrosoftMode) ||
7953 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007954 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007955 CopyAssignment->setDeletedAsWritten();
7956
Douglas Gregord3c35902010-07-01 16:36:15 +00007957 AddOverriddenMethods(ClassDecl, CopyAssignment);
7958 return CopyAssignment;
7959}
7960
Douglas Gregor06a9f362010-05-01 20:49:11 +00007961void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7962 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007963 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007964 CopyAssignOperator->isOverloadedOperator() &&
7965 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007966 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007967 "DefineImplicitCopyAssignment called for wrong function");
7968
7969 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7970
7971 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7972 CopyAssignOperator->setInvalidDecl();
7973 return;
7974 }
7975
7976 CopyAssignOperator->setUsed();
7977
7978 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007979 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980
7981 // C++0x [class.copy]p30:
7982 // The implicitly-defined or explicitly-defaulted copy assignment operator
7983 // for a non-union class X performs memberwise copy assignment of its
7984 // subobjects. The direct base classes of X are assigned first, in the
7985 // order of their declaration in the base-specifier-list, and then the
7986 // immediate non-static data members of X are assigned, in the order in
7987 // which they were declared in the class definition.
7988
7989 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007990 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007991
7992 // The parameter for the "other" object, which we are copying from.
7993 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7994 Qualifiers OtherQuals = Other->getType().getQualifiers();
7995 QualType OtherRefType = Other->getType();
7996 if (const LValueReferenceType *OtherRef
7997 = OtherRefType->getAs<LValueReferenceType>()) {
7998 OtherRefType = OtherRef->getPointeeType();
7999 OtherQuals = OtherRefType.getQualifiers();
8000 }
8001
8002 // Our location for everything implicitly-generated.
8003 SourceLocation Loc = CopyAssignOperator->getLocation();
8004
8005 // Construct a reference to the "other" object. We'll be using this
8006 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008007 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008008 assert(OtherRef && "Reference to parameter cannot fail!");
8009
8010 // Construct the "this" pointer. We'll be using this throughout the generated
8011 // ASTs.
8012 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8013 assert(This && "Reference to this cannot fail!");
8014
8015 // Assign base classes.
8016 bool Invalid = false;
8017 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8018 E = ClassDecl->bases_end(); Base != E; ++Base) {
8019 // Form the assignment:
8020 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8021 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008022 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008023 Invalid = true;
8024 continue;
8025 }
8026
John McCallf871d0c2010-08-07 06:22:56 +00008027 CXXCastPath BasePath;
8028 BasePath.push_back(Base);
8029
Douglas Gregor06a9f362010-05-01 20:49:11 +00008030 // Construct the "from" expression, which is an implicit cast to the
8031 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008032 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008033 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8034 CK_UncheckedDerivedToBase,
8035 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008036
8037 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008038 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008039
8040 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008041 To = ImpCastExprToType(To.take(),
8042 Context.getCVRQualifiedType(BaseType,
8043 CopyAssignOperator->getTypeQualifiers()),
8044 CK_UncheckedDerivedToBase,
8045 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008046
8047 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00008048 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008049 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008050 /*CopyingBaseSubobject=*/true,
8051 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008052 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008053 Diag(CurrentLocation, diag::note_member_synthesized_at)
8054 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8055 CopyAssignOperator->setInvalidDecl();
8056 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008057 }
8058
8059 // Success! Record the copy.
8060 Statements.push_back(Copy.takeAs<Expr>());
8061 }
8062
8063 // \brief Reference to the __builtin_memcpy function.
8064 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008065 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008066 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008067
8068 // Assign non-static members.
8069 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8070 FieldEnd = ClassDecl->field_end();
8071 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008072 if (Field->isUnnamedBitfield())
8073 continue;
8074
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 // Check for members of reference type; we can't copy those.
8076 if (Field->getType()->isReferenceType()) {
8077 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8078 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8079 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008080 Diag(CurrentLocation, diag::note_member_synthesized_at)
8081 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008082 Invalid = true;
8083 continue;
8084 }
8085
8086 // Check for members of const-qualified, non-class type.
8087 QualType BaseType = Context.getBaseElementType(Field->getType());
8088 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8089 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8090 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8091 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008092 Diag(CurrentLocation, diag::note_member_synthesized_at)
8093 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008094 Invalid = true;
8095 continue;
8096 }
John McCallb77115d2011-06-17 00:18:42 +00008097
8098 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008099 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8100 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008101
8102 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008103 if (FieldType->isIncompleteArrayType()) {
8104 assert(ClassDecl->hasFlexibleArrayMember() &&
8105 "Incomplete array type is not valid");
8106 continue;
8107 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008108
8109 // Build references to the field in the object we're copying from and to.
8110 CXXScopeSpec SS; // Intentionally empty
8111 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8112 LookupMemberName);
8113 MemberLookup.addDecl(*Field);
8114 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008115 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008116 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008117 SS, SourceLocation(), 0,
8118 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008119 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008120 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008121 SS, SourceLocation(), 0,
8122 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008123 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8124 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8125
8126 // If the field should be copied with __builtin_memcpy rather than via
8127 // explicit assignments, do so. This optimization only applies for arrays
8128 // of scalars and arrays of class type with trivial copy-assignment
8129 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008130 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008131 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132 // Compute the size of the memory buffer to be copied.
8133 QualType SizeType = Context.getSizeType();
8134 llvm::APInt Size(Context.getTypeSize(SizeType),
8135 Context.getTypeSizeInChars(BaseType).getQuantity());
8136 for (const ConstantArrayType *Array
8137 = Context.getAsConstantArrayType(FieldType);
8138 Array;
8139 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008140 llvm::APInt ArraySize
8141 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142 Size *= ArraySize;
8143 }
8144
8145 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008146 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8147 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008148
8149 bool NeedsCollectableMemCpy =
8150 (BaseType->isRecordType() &&
8151 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8152
8153 if (NeedsCollectableMemCpy) {
8154 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008155 // Create a reference to the __builtin_objc_memmove_collectable function.
8156 LookupResult R(*this,
8157 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008158 Loc, LookupOrdinaryName);
8159 LookupName(R, TUScope, true);
8160
8161 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8162 if (!CollectableMemCpy) {
8163 // Something went horribly wrong earlier, and we will have
8164 // complained about it.
8165 Invalid = true;
8166 continue;
8167 }
8168
8169 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8170 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008171 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008172 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8173 }
8174 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008175 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008176 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008177 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8178 LookupOrdinaryName);
8179 LookupName(R, TUScope, true);
8180
8181 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8182 if (!BuiltinMemCpy) {
8183 // Something went horribly wrong earlier, and we will have complained
8184 // about it.
8185 Invalid = true;
8186 continue;
8187 }
8188
8189 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8190 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008191 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008192 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8193 }
8194
John McCallca0408f2010-08-23 06:44:23 +00008195 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008196 CallArgs.push_back(To.takeAs<Expr>());
8197 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008198 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008199 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008200 if (NeedsCollectableMemCpy)
8201 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008202 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008203 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008204 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008205 else
8206 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008207 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008208 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008209 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008210
Douglas Gregor06a9f362010-05-01 20:49:11 +00008211 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8212 Statements.push_back(Call.takeAs<Expr>());
8213 continue;
8214 }
8215
8216 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008217 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008218 To.get(), From.get(),
8219 /*CopyingBaseSubobject=*/false,
8220 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008221 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008222 Diag(CurrentLocation, diag::note_member_synthesized_at)
8223 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8224 CopyAssignOperator->setInvalidDecl();
8225 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008226 }
8227
8228 // Success! Record the copy.
8229 Statements.push_back(Copy.takeAs<Stmt>());
8230 }
8231
8232 if (!Invalid) {
8233 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008234 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008235
John McCall60d7b3a2010-08-24 06:29:42 +00008236 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008237 if (Return.isInvalid())
8238 Invalid = true;
8239 else {
8240 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008241
8242 if (Trap.hasErrorOccurred()) {
8243 Diag(CurrentLocation, diag::note_member_synthesized_at)
8244 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8245 Invalid = true;
8246 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008247 }
8248 }
8249
8250 if (Invalid) {
8251 CopyAssignOperator->setInvalidDecl();
8252 return;
8253 }
8254
John McCall60d7b3a2010-08-24 06:29:42 +00008255 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008256 /*isStmtExpr=*/false);
8257 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8258 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008259
8260 if (ASTMutationListener *L = getASTMutationListener()) {
8261 L->CompletedImplicitDefinition(CopyAssignOperator);
8262 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008263}
8264
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008265Sema::ImplicitExceptionSpecification
8266Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8267 ImplicitExceptionSpecification ExceptSpec(Context);
8268
8269 if (ClassDecl->isInvalidDecl())
8270 return ExceptSpec;
8271
8272 // C++0x [except.spec]p14:
8273 // An implicitly declared special member function (Clause 12) shall have an
8274 // exception-specification. [...]
8275
8276 // It is unspecified whether or not an implicit move assignment operator
8277 // attempts to deduplicate calls to assignment operators of virtual bases are
8278 // made. As such, this exception specification is effectively unspecified.
8279 // Based on a similar decision made for constness in C++0x, we're erring on
8280 // the side of assuming such calls to be made regardless of whether they
8281 // actually happen.
8282 // Note that a move constructor is not implicitly declared when there are
8283 // virtual bases, but it can still be user-declared and explicitly defaulted.
8284 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8285 BaseEnd = ClassDecl->bases_end();
8286 Base != BaseEnd; ++Base) {
8287 if (Base->isVirtual())
8288 continue;
8289
8290 CXXRecordDecl *BaseClassDecl
8291 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8292 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8293 false, 0))
8294 ExceptSpec.CalledDecl(MoveAssign);
8295 }
8296
8297 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8298 BaseEnd = ClassDecl->vbases_end();
8299 Base != BaseEnd; ++Base) {
8300 CXXRecordDecl *BaseClassDecl
8301 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8302 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8303 false, 0))
8304 ExceptSpec.CalledDecl(MoveAssign);
8305 }
8306
8307 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8308 FieldEnd = ClassDecl->field_end();
8309 Field != FieldEnd;
8310 ++Field) {
8311 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8312 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8313 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8314 false, 0))
8315 ExceptSpec.CalledDecl(MoveAssign);
8316 }
8317 }
8318
8319 return ExceptSpec;
8320}
8321
8322CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8323 // Note: The following rules are largely analoguous to the move
8324 // constructor rules.
8325
8326 ImplicitExceptionSpecification Spec(
8327 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8328
8329 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8330 QualType RetType = Context.getLValueReferenceType(ArgType);
8331 ArgType = Context.getRValueReferenceType(ArgType);
8332
8333 // An implicitly-declared move assignment operator is an inline public
8334 // member of its class.
8335 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8336 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8337 SourceLocation ClassLoc = ClassDecl->getLocation();
8338 DeclarationNameInfo NameInfo(Name, ClassLoc);
8339 CXXMethodDecl *MoveAssignment
8340 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8341 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8342 /*TInfo=*/0, /*isStatic=*/false,
8343 /*StorageClassAsWritten=*/SC_None,
8344 /*isInline=*/true,
8345 /*isConstexpr=*/false,
8346 SourceLocation());
8347 MoveAssignment->setAccess(AS_public);
8348 MoveAssignment->setDefaulted();
8349 MoveAssignment->setImplicit();
8350 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8351
8352 // Add the parameter to the operator.
8353 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8354 ClassLoc, ClassLoc, /*Id=*/0,
8355 ArgType, /*TInfo=*/0,
8356 SC_None,
8357 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008358 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008359
8360 // Note that we have added this copy-assignment operator.
8361 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8362
8363 // C++0x [class.copy]p9:
8364 // If the definition of a class X does not explicitly declare a move
8365 // assignment operator, one will be implicitly declared as defaulted if and
8366 // only if:
8367 // [...]
8368 // - the move assignment operator would not be implicitly defined as
8369 // deleted.
8370 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8371 // Cache this result so that we don't try to generate this over and over
8372 // on every lookup, leaking memory and wasting time.
8373 ClassDecl->setFailedImplicitMoveAssignment();
8374 return 0;
8375 }
8376
8377 if (Scope *S = getScopeForContext(ClassDecl))
8378 PushOnScopeChains(MoveAssignment, S, false);
8379 ClassDecl->addDecl(MoveAssignment);
8380
8381 AddOverriddenMethods(ClassDecl, MoveAssignment);
8382 return MoveAssignment;
8383}
8384
8385void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8386 CXXMethodDecl *MoveAssignOperator) {
8387 assert((MoveAssignOperator->isDefaulted() &&
8388 MoveAssignOperator->isOverloadedOperator() &&
8389 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8390 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8391 "DefineImplicitMoveAssignment called for wrong function");
8392
8393 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8394
8395 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8396 MoveAssignOperator->setInvalidDecl();
8397 return;
8398 }
8399
8400 MoveAssignOperator->setUsed();
8401
8402 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8403 DiagnosticErrorTrap Trap(Diags);
8404
8405 // C++0x [class.copy]p28:
8406 // The implicitly-defined or move assignment operator for a non-union class
8407 // X performs memberwise move assignment of its subobjects. The direct base
8408 // classes of X are assigned first, in the order of their declaration in the
8409 // base-specifier-list, and then the immediate non-static data members of X
8410 // are assigned, in the order in which they were declared in the class
8411 // definition.
8412
8413 // The statements that form the synthesized function body.
8414 ASTOwningVector<Stmt*> Statements(*this);
8415
8416 // The parameter for the "other" object, which we are move from.
8417 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8418 QualType OtherRefType = Other->getType()->
8419 getAs<RValueReferenceType>()->getPointeeType();
8420 assert(OtherRefType.getQualifiers() == 0 &&
8421 "Bad argument type of defaulted move assignment");
8422
8423 // Our location for everything implicitly-generated.
8424 SourceLocation Loc = MoveAssignOperator->getLocation();
8425
8426 // Construct a reference to the "other" object. We'll be using this
8427 // throughout the generated ASTs.
8428 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8429 assert(OtherRef && "Reference to parameter cannot fail!");
8430 // Cast to rvalue.
8431 OtherRef = CastForMoving(*this, OtherRef);
8432
8433 // Construct the "this" pointer. We'll be using this throughout the generated
8434 // ASTs.
8435 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8436 assert(This && "Reference to this cannot fail!");
8437
8438 // Assign base classes.
8439 bool Invalid = false;
8440 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8441 E = ClassDecl->bases_end(); Base != E; ++Base) {
8442 // Form the assignment:
8443 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8444 QualType BaseType = Base->getType().getUnqualifiedType();
8445 if (!BaseType->isRecordType()) {
8446 Invalid = true;
8447 continue;
8448 }
8449
8450 CXXCastPath BasePath;
8451 BasePath.push_back(Base);
8452
8453 // Construct the "from" expression, which is an implicit cast to the
8454 // appropriately-qualified base type.
8455 Expr *From = OtherRef;
8456 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008457 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458
8459 // Dereference "this".
8460 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8461
8462 // Implicitly cast "this" to the appropriately-qualified base type.
8463 To = ImpCastExprToType(To.take(),
8464 Context.getCVRQualifiedType(BaseType,
8465 MoveAssignOperator->getTypeQualifiers()),
8466 CK_UncheckedDerivedToBase,
8467 VK_LValue, &BasePath);
8468
8469 // Build the move.
8470 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8471 To.get(), From,
8472 /*CopyingBaseSubobject=*/true,
8473 /*Copying=*/false);
8474 if (Move.isInvalid()) {
8475 Diag(CurrentLocation, diag::note_member_synthesized_at)
8476 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8477 MoveAssignOperator->setInvalidDecl();
8478 return;
8479 }
8480
8481 // Success! Record the move.
8482 Statements.push_back(Move.takeAs<Expr>());
8483 }
8484
8485 // \brief Reference to the __builtin_memcpy function.
8486 Expr *BuiltinMemCpyRef = 0;
8487 // \brief Reference to the __builtin_objc_memmove_collectable function.
8488 Expr *CollectableMemCpyRef = 0;
8489
8490 // Assign non-static members.
8491 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8492 FieldEnd = ClassDecl->field_end();
8493 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008494 if (Field->isUnnamedBitfield())
8495 continue;
8496
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008497 // Check for members of reference type; we can't move those.
8498 if (Field->getType()->isReferenceType()) {
8499 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8500 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8501 Diag(Field->getLocation(), diag::note_declared_at);
8502 Diag(CurrentLocation, diag::note_member_synthesized_at)
8503 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8504 Invalid = true;
8505 continue;
8506 }
8507
8508 // Check for members of const-qualified, non-class type.
8509 QualType BaseType = Context.getBaseElementType(Field->getType());
8510 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8511 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8512 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8513 Diag(Field->getLocation(), diag::note_declared_at);
8514 Diag(CurrentLocation, diag::note_member_synthesized_at)
8515 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8516 Invalid = true;
8517 continue;
8518 }
8519
8520 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008521 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8522 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008523
8524 QualType FieldType = Field->getType().getNonReferenceType();
8525 if (FieldType->isIncompleteArrayType()) {
8526 assert(ClassDecl->hasFlexibleArrayMember() &&
8527 "Incomplete array type is not valid");
8528 continue;
8529 }
8530
8531 // Build references to the field in the object we're copying from and to.
8532 CXXScopeSpec SS; // Intentionally empty
8533 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8534 LookupMemberName);
8535 MemberLookup.addDecl(*Field);
8536 MemberLookup.resolveKind();
8537 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8538 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008539 SS, SourceLocation(), 0,
8540 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008541 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8542 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008543 SS, SourceLocation(), 0,
8544 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008545 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8546 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8547
8548 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8549 "Member reference with rvalue base must be rvalue except for reference "
8550 "members, which aren't allowed for move assignment.");
8551
8552 // If the field should be copied with __builtin_memcpy rather than via
8553 // explicit assignments, do so. This optimization only applies for arrays
8554 // of scalars and arrays of class type with trivial move-assignment
8555 // operators.
8556 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8557 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8558 // Compute the size of the memory buffer to be copied.
8559 QualType SizeType = Context.getSizeType();
8560 llvm::APInt Size(Context.getTypeSize(SizeType),
8561 Context.getTypeSizeInChars(BaseType).getQuantity());
8562 for (const ConstantArrayType *Array
8563 = Context.getAsConstantArrayType(FieldType);
8564 Array;
8565 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8566 llvm::APInt ArraySize
8567 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8568 Size *= ArraySize;
8569 }
8570
Douglas Gregor45d3d712011-09-01 02:09:07 +00008571 // Take the address of the field references for "from" and "to". We
8572 // directly construct UnaryOperators here because semantic analysis
8573 // does not permit us to take the address of an xvalue.
8574 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8575 Context.getPointerType(From.get()->getType()),
8576 VK_RValue, OK_Ordinary, Loc);
8577 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8578 Context.getPointerType(To.get()->getType()),
8579 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008580
8581 bool NeedsCollectableMemCpy =
8582 (BaseType->isRecordType() &&
8583 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8584
8585 if (NeedsCollectableMemCpy) {
8586 if (!CollectableMemCpyRef) {
8587 // Create a reference to the __builtin_objc_memmove_collectable function.
8588 LookupResult R(*this,
8589 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8590 Loc, LookupOrdinaryName);
8591 LookupName(R, TUScope, true);
8592
8593 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8594 if (!CollectableMemCpy) {
8595 // Something went horribly wrong earlier, and we will have
8596 // complained about it.
8597 Invalid = true;
8598 continue;
8599 }
8600
8601 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8602 CollectableMemCpy->getType(),
8603 VK_LValue, Loc, 0).take();
8604 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8605 }
8606 }
8607 // Create a reference to the __builtin_memcpy builtin function.
8608 else if (!BuiltinMemCpyRef) {
8609 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8610 LookupOrdinaryName);
8611 LookupName(R, TUScope, true);
8612
8613 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8614 if (!BuiltinMemCpy) {
8615 // Something went horribly wrong earlier, and we will have complained
8616 // about it.
8617 Invalid = true;
8618 continue;
8619 }
8620
8621 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8622 BuiltinMemCpy->getType(),
8623 VK_LValue, Loc, 0).take();
8624 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8625 }
8626
8627 ASTOwningVector<Expr*> CallArgs(*this);
8628 CallArgs.push_back(To.takeAs<Expr>());
8629 CallArgs.push_back(From.takeAs<Expr>());
8630 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8631 ExprResult Call = ExprError();
8632 if (NeedsCollectableMemCpy)
8633 Call = ActOnCallExpr(/*Scope=*/0,
8634 CollectableMemCpyRef,
8635 Loc, move_arg(CallArgs),
8636 Loc);
8637 else
8638 Call = ActOnCallExpr(/*Scope=*/0,
8639 BuiltinMemCpyRef,
8640 Loc, move_arg(CallArgs),
8641 Loc);
8642
8643 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8644 Statements.push_back(Call.takeAs<Expr>());
8645 continue;
8646 }
8647
8648 // Build the move of this field.
8649 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8650 To.get(), From.get(),
8651 /*CopyingBaseSubobject=*/false,
8652 /*Copying=*/false);
8653 if (Move.isInvalid()) {
8654 Diag(CurrentLocation, diag::note_member_synthesized_at)
8655 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8656 MoveAssignOperator->setInvalidDecl();
8657 return;
8658 }
8659
8660 // Success! Record the copy.
8661 Statements.push_back(Move.takeAs<Stmt>());
8662 }
8663
8664 if (!Invalid) {
8665 // Add a "return *this;"
8666 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8667
8668 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8669 if (Return.isInvalid())
8670 Invalid = true;
8671 else {
8672 Statements.push_back(Return.takeAs<Stmt>());
8673
8674 if (Trap.hasErrorOccurred()) {
8675 Diag(CurrentLocation, diag::note_member_synthesized_at)
8676 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8677 Invalid = true;
8678 }
8679 }
8680 }
8681
8682 if (Invalid) {
8683 MoveAssignOperator->setInvalidDecl();
8684 return;
8685 }
8686
8687 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8688 /*isStmtExpr=*/false);
8689 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8690 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8691
8692 if (ASTMutationListener *L = getASTMutationListener()) {
8693 L->CompletedImplicitDefinition(MoveAssignOperator);
8694 }
8695}
8696
Sean Hunt49634cf2011-05-13 06:10:58 +00008697std::pair<Sema::ImplicitExceptionSpecification, bool>
8698Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008699 if (ClassDecl->isInvalidDecl())
8700 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8701
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008702 // C++ [class.copy]p5:
8703 // The implicitly-declared copy constructor for a class X will
8704 // have the form
8705 //
8706 // X::X(const X&)
8707 //
8708 // if
Sean Huntc530d172011-06-10 04:44:37 +00008709 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008710 bool HasConstCopyConstructor = true;
8711
8712 // -- each direct or virtual base class B of X has a copy
8713 // constructor whose first parameter is of type const B& or
8714 // const volatile B&, and
8715 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8716 BaseEnd = ClassDecl->bases_end();
8717 HasConstCopyConstructor && Base != BaseEnd;
8718 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008719 // Virtual bases are handled below.
8720 if (Base->isVirtual())
8721 continue;
8722
Douglas Gregor22584312010-07-02 23:41:54 +00008723 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008724 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008725 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8726 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008727 }
8728
8729 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8730 BaseEnd = ClassDecl->vbases_end();
8731 HasConstCopyConstructor && Base != BaseEnd;
8732 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008733 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008734 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008735 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8736 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008737 }
8738
8739 // -- for all the nonstatic data members of X that are of a
8740 // class type M (or array thereof), each such class type
8741 // has a copy constructor whose first parameter is of type
8742 // const M& or const volatile M&.
8743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8744 FieldEnd = ClassDecl->field_end();
8745 HasConstCopyConstructor && Field != FieldEnd;
8746 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008747 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008748 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008749 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8750 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008751 }
8752 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008753 // Otherwise, the implicitly declared copy constructor will have
8754 // the form
8755 //
8756 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008757
Douglas Gregor0d405db2010-07-01 20:59:04 +00008758 // C++ [except.spec]p14:
8759 // An implicitly declared special member function (Clause 12) shall have an
8760 // exception-specification. [...]
8761 ImplicitExceptionSpecification ExceptSpec(Context);
8762 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8763 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8764 BaseEnd = ClassDecl->bases_end();
8765 Base != BaseEnd;
8766 ++Base) {
8767 // Virtual bases are handled below.
8768 if (Base->isVirtual())
8769 continue;
8770
Douglas Gregor22584312010-07-02 23:41:54 +00008771 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008772 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008773 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008774 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008775 ExceptSpec.CalledDecl(CopyConstructor);
8776 }
8777 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8778 BaseEnd = ClassDecl->vbases_end();
8779 Base != BaseEnd;
8780 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008781 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008782 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008783 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008784 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008785 ExceptSpec.CalledDecl(CopyConstructor);
8786 }
8787 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8788 FieldEnd = ClassDecl->field_end();
8789 Field != FieldEnd;
8790 ++Field) {
8791 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008792 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8793 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008794 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008795 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008796 }
8797 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008798
Sean Hunt49634cf2011-05-13 06:10:58 +00008799 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8800}
8801
8802CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8803 CXXRecordDecl *ClassDecl) {
8804 // C++ [class.copy]p4:
8805 // If the class definition does not explicitly declare a copy
8806 // constructor, one is declared implicitly.
8807
8808 ImplicitExceptionSpecification Spec(Context);
8809 bool Const;
8810 llvm::tie(Spec, Const) =
8811 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8812
8813 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8814 QualType ArgType = ClassType;
8815 if (Const)
8816 ArgType = ArgType.withConst();
8817 ArgType = Context.getLValueReferenceType(ArgType);
8818
8819 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8820
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008821 DeclarationName Name
8822 = Context.DeclarationNames.getCXXConstructorName(
8823 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008824 SourceLocation ClassLoc = ClassDecl->getLocation();
8825 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008826
8827 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008828 // member of its class.
8829 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8830 Context, ClassDecl, ClassLoc, NameInfo,
8831 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8832 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8833 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8834 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008835 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008836 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008837 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008838
Douglas Gregor22584312010-07-02 23:41:54 +00008839 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008840 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8841
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008842 // Add the parameter to the constructor.
8843 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008844 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008845 /*IdentifierInfo=*/0,
8846 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008847 SC_None,
8848 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008849 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008850
Douglas Gregor23c94db2010-07-02 17:43:08 +00008851 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008852 PushOnScopeChains(CopyConstructor, S, false);
8853 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008854
Nico Weberafcc96a2012-01-23 03:19:29 +00008855 // C++11 [class.copy]p8:
8856 // ... If the class definition does not explicitly declare a copy
8857 // constructor, there is no user-declared move constructor, and there is no
8858 // user-declared move assignment operator, a copy constructor is implicitly
8859 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008860 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008861 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008862 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008863 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008864 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008865
8866 return CopyConstructor;
8867}
8868
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008869void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008870 CXXConstructorDecl *CopyConstructor) {
8871 assert((CopyConstructor->isDefaulted() &&
8872 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008873 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008874 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008875
Anders Carlsson63010a72010-04-23 16:24:12 +00008876 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008877 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008878
Douglas Gregor39957dc2010-05-01 15:04:51 +00008879 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008880 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008881
Sean Huntcbb67482011-01-08 20:30:50 +00008882 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008883 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008884 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008885 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008886 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008887 } else {
8888 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8889 CopyConstructor->getLocation(),
8890 MultiStmtArg(*this, 0, 0),
8891 /*isStmtExpr=*/false)
8892 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008893 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008894 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008895
8896 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008897 if (ASTMutationListener *L = getASTMutationListener()) {
8898 L->CompletedImplicitDefinition(CopyConstructor);
8899 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008900}
8901
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008902Sema::ImplicitExceptionSpecification
8903Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8904 // C++ [except.spec]p14:
8905 // An implicitly declared special member function (Clause 12) shall have an
8906 // exception-specification. [...]
8907 ImplicitExceptionSpecification ExceptSpec(Context);
8908 if (ClassDecl->isInvalidDecl())
8909 return ExceptSpec;
8910
8911 // Direct base-class constructors.
8912 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8913 BEnd = ClassDecl->bases_end();
8914 B != BEnd; ++B) {
8915 if (B->isVirtual()) // Handled below.
8916 continue;
8917
8918 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8919 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8920 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8921 // If this is a deleted function, add it anyway. This might be conformant
8922 // with the standard. This might not. I'm not sure. It might not matter.
8923 if (Constructor)
8924 ExceptSpec.CalledDecl(Constructor);
8925 }
8926 }
8927
8928 // Virtual base-class constructors.
8929 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8930 BEnd = ClassDecl->vbases_end();
8931 B != BEnd; ++B) {
8932 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8933 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8934 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8935 // If this is a deleted function, add it anyway. This might be conformant
8936 // with the standard. This might not. I'm not sure. It might not matter.
8937 if (Constructor)
8938 ExceptSpec.CalledDecl(Constructor);
8939 }
8940 }
8941
8942 // Field constructors.
8943 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8944 FEnd = ClassDecl->field_end();
8945 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008946 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008947 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8948 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8949 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8950 // If this is a deleted function, add it anyway. This might be conformant
8951 // with the standard. This might not. I'm not sure. It might not matter.
8952 // In particular, the problem is that this function never gets called. It
8953 // might just be ill-formed because this function attempts to refer to
8954 // a deleted function here.
8955 if (Constructor)
8956 ExceptSpec.CalledDecl(Constructor);
8957 }
8958 }
8959
8960 return ExceptSpec;
8961}
8962
8963CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8964 CXXRecordDecl *ClassDecl) {
8965 ImplicitExceptionSpecification Spec(
8966 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8967
8968 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8969 QualType ArgType = Context.getRValueReferenceType(ClassType);
8970
8971 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8972
8973 DeclarationName Name
8974 = Context.DeclarationNames.getCXXConstructorName(
8975 Context.getCanonicalType(ClassType));
8976 SourceLocation ClassLoc = ClassDecl->getLocation();
8977 DeclarationNameInfo NameInfo(Name, ClassLoc);
8978
8979 // C++0x [class.copy]p11:
8980 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008981 // member of its class.
8982 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8983 Context, ClassDecl, ClassLoc, NameInfo,
8984 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8985 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8986 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8987 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008988 MoveConstructor->setAccess(AS_public);
8989 MoveConstructor->setDefaulted();
8990 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008991
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008992 // Add the parameter to the constructor.
8993 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8994 ClassLoc, ClassLoc,
8995 /*IdentifierInfo=*/0,
8996 ArgType, /*TInfo=*/0,
8997 SC_None,
8998 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008999 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009000
9001 // C++0x [class.copy]p9:
9002 // If the definition of a class X does not explicitly declare a move
9003 // constructor, one will be implicitly declared as defaulted if and only if:
9004 // [...]
9005 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009006 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009007 // Cache this result so that we don't try to generate this over and over
9008 // on every lookup, leaking memory and wasting time.
9009 ClassDecl->setFailedImplicitMoveConstructor();
9010 return 0;
9011 }
9012
9013 // Note that we have declared this constructor.
9014 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9015
9016 if (Scope *S = getScopeForContext(ClassDecl))
9017 PushOnScopeChains(MoveConstructor, S, false);
9018 ClassDecl->addDecl(MoveConstructor);
9019
9020 return MoveConstructor;
9021}
9022
9023void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9024 CXXConstructorDecl *MoveConstructor) {
9025 assert((MoveConstructor->isDefaulted() &&
9026 MoveConstructor->isMoveConstructor() &&
9027 !MoveConstructor->doesThisDeclarationHaveABody()) &&
9028 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9029
9030 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9031 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9032
9033 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
9034 DiagnosticErrorTrap Trap(Diags);
9035
9036 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9037 Trap.hasErrorOccurred()) {
9038 Diag(CurrentLocation, diag::note_member_synthesized_at)
9039 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9040 MoveConstructor->setInvalidDecl();
9041 } else {
9042 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9043 MoveConstructor->getLocation(),
9044 MultiStmtArg(*this, 0, 0),
9045 /*isStmtExpr=*/false)
9046 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009047 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009048 }
9049
9050 MoveConstructor->setUsed();
9051
9052 if (ASTMutationListener *L = getASTMutationListener()) {
9053 L->CompletedImplicitDefinition(MoveConstructor);
9054 }
9055}
9056
John McCall60d7b3a2010-08-24 06:29:42 +00009057ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009058Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009059 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009060 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009061 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009062 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009063 unsigned ConstructKind,
9064 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009065 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009066
Douglas Gregor2f599792010-04-02 18:24:57 +00009067 // C++0x [class.copy]p34:
9068 // When certain criteria are met, an implementation is allowed to
9069 // omit the copy/move construction of a class object, even if the
9070 // copy/move constructor and/or destructor for the object have
9071 // side effects. [...]
9072 // - when a temporary class object that has not been bound to a
9073 // reference (12.2) would be copied/moved to a class object
9074 // with the same cv-unqualified type, the copy/move operation
9075 // can be omitted by constructing the temporary object
9076 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009077 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009078 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009079 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009080 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009081 }
Mike Stump1eb44332009-09-09 15:08:12 +00009082
9083 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009084 Elidable, move(ExprArgs), HadMultipleCandidates,
9085 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009086}
9087
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009088/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9089/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009090ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009091Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9092 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009093 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009094 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009095 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009096 unsigned ConstructKind,
9097 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009098 unsigned NumExprs = ExprArgs.size();
9099 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009100
Nick Lewycky909a70d2011-03-25 01:44:32 +00009101 for (specific_attr_iterator<NonNullAttr>
9102 i = Constructor->specific_attr_begin<NonNullAttr>(),
9103 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9104 const NonNullAttr *NonNull = *i;
9105 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9106 }
9107
Eli Friedman5f2987c2012-02-02 03:46:19 +00009108 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009109 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009110 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009111 HadMultipleCandidates, /*FIXME*/false,
9112 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009113 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9114 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009115}
9116
Mike Stump1eb44332009-09-09 15:08:12 +00009117bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009118 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009119 MultiExprArg Exprs,
9120 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009121 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009122 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009123 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009124 move(Exprs), HadMultipleCandidates, false,
9125 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009126 if (TempResult.isInvalid())
9127 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009128
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009129 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009130 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009131 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009132 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009133 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009134
Anders Carlssonfe2de492009-08-25 05:18:00 +00009135 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009136}
9137
John McCall68c6c9a2010-02-02 09:10:11 +00009138void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009139 if (VD->isInvalidDecl()) return;
9140
John McCall68c6c9a2010-02-02 09:10:11 +00009141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009142 if (ClassDecl->isInvalidDecl()) return;
9143 if (ClassDecl->hasTrivialDestructor()) return;
9144 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009145
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009146 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009147 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009148 CheckDestructorAccess(VD->getLocation(), Destructor,
9149 PDiag(diag::err_access_dtor_var)
9150 << VD->getDeclName()
9151 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009152
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009153 if (!VD->hasGlobalStorage()) return;
9154
9155 // Emit warning for non-trivial dtor in global scope (a real global,
9156 // class-static, function-static).
9157 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9158
9159 // TODO: this should be re-enabled for static locals by !CXAAtExit
9160 if (!VD->isStaticLocal())
9161 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009162}
9163
Douglas Gregor39da0b82009-09-09 23:08:42 +00009164/// \brief Given a constructor and the set of arguments provided for the
9165/// constructor, convert the arguments and add any required default arguments
9166/// to form a proper call to this constructor.
9167///
9168/// \returns true if an error occurred, false otherwise.
9169bool
9170Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9171 MultiExprArg ArgsPtr,
9172 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009173 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009174 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9175 unsigned NumArgs = ArgsPtr.size();
9176 Expr **Args = (Expr **)ArgsPtr.get();
9177
9178 const FunctionProtoType *Proto
9179 = Constructor->getType()->getAs<FunctionProtoType>();
9180 assert(Proto && "Constructor without a prototype?");
9181 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009182
9183 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009184 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009185 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009186 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009187 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009188
9189 VariadicCallType CallType =
9190 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009191 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009192 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9193 Proto, 0, Args, NumArgs, AllArgs,
9194 CallType);
9195 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9196 ConvertedArgs.push_back(AllArgs[i]);
9197 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009198}
9199
Anders Carlsson20d45d22009-12-12 00:32:00 +00009200static inline bool
9201CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9202 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009203 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009204 if (isa<NamespaceDecl>(DC)) {
9205 return SemaRef.Diag(FnDecl->getLocation(),
9206 diag::err_operator_new_delete_declared_in_namespace)
9207 << FnDecl->getDeclName();
9208 }
9209
9210 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009211 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009212 return SemaRef.Diag(FnDecl->getLocation(),
9213 diag::err_operator_new_delete_declared_static)
9214 << FnDecl->getDeclName();
9215 }
9216
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009217 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009218}
9219
Anders Carlsson156c78e2009-12-13 17:53:43 +00009220static inline bool
9221CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9222 CanQualType ExpectedResultType,
9223 CanQualType ExpectedFirstParamType,
9224 unsigned DependentParamTypeDiag,
9225 unsigned InvalidParamTypeDiag) {
9226 QualType ResultType =
9227 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9228
9229 // Check that the result type is not dependent.
9230 if (ResultType->isDependentType())
9231 return SemaRef.Diag(FnDecl->getLocation(),
9232 diag::err_operator_new_delete_dependent_result_type)
9233 << FnDecl->getDeclName() << ExpectedResultType;
9234
9235 // Check that the result type is what we expect.
9236 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9237 return SemaRef.Diag(FnDecl->getLocation(),
9238 diag::err_operator_new_delete_invalid_result_type)
9239 << FnDecl->getDeclName() << ExpectedResultType;
9240
9241 // A function template must have at least 2 parameters.
9242 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9243 return SemaRef.Diag(FnDecl->getLocation(),
9244 diag::err_operator_new_delete_template_too_few_parameters)
9245 << FnDecl->getDeclName();
9246
9247 // The function decl must have at least 1 parameter.
9248 if (FnDecl->getNumParams() == 0)
9249 return SemaRef.Diag(FnDecl->getLocation(),
9250 diag::err_operator_new_delete_too_few_parameters)
9251 << FnDecl->getDeclName();
9252
9253 // Check the the first parameter type is not dependent.
9254 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9255 if (FirstParamType->isDependentType())
9256 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9257 << FnDecl->getDeclName() << ExpectedFirstParamType;
9258
9259 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009260 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009261 ExpectedFirstParamType)
9262 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9263 << FnDecl->getDeclName() << ExpectedFirstParamType;
9264
9265 return false;
9266}
9267
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009268static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009269CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009270 // C++ [basic.stc.dynamic.allocation]p1:
9271 // A program is ill-formed if an allocation function is declared in a
9272 // namespace scope other than global scope or declared static in global
9273 // scope.
9274 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9275 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009276
9277 CanQualType SizeTy =
9278 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9279
9280 // C++ [basic.stc.dynamic.allocation]p1:
9281 // The return type shall be void*. The first parameter shall have type
9282 // std::size_t.
9283 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9284 SizeTy,
9285 diag::err_operator_new_dependent_param_type,
9286 diag::err_operator_new_param_type))
9287 return true;
9288
9289 // C++ [basic.stc.dynamic.allocation]p1:
9290 // The first parameter shall not have an associated default argument.
9291 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009292 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009293 diag::err_operator_new_default_arg)
9294 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9295
9296 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009297}
9298
9299static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009300CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9301 // C++ [basic.stc.dynamic.deallocation]p1:
9302 // A program is ill-formed if deallocation functions are declared in a
9303 // namespace scope other than global scope or declared static in global
9304 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009305 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9306 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009307
9308 // C++ [basic.stc.dynamic.deallocation]p2:
9309 // Each deallocation function shall return void and its first parameter
9310 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009311 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9312 SemaRef.Context.VoidPtrTy,
9313 diag::err_operator_delete_dependent_param_type,
9314 diag::err_operator_delete_param_type))
9315 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009316
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009317 return false;
9318}
9319
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009320/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9321/// of this overloaded operator is well-formed. If so, returns false;
9322/// otherwise, emits appropriate diagnostics and returns true.
9323bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009324 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009325 "Expected an overloaded operator declaration");
9326
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009327 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9328
Mike Stump1eb44332009-09-09 15:08:12 +00009329 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009330 // The allocation and deallocation functions, operator new,
9331 // operator new[], operator delete and operator delete[], are
9332 // described completely in 3.7.3. The attributes and restrictions
9333 // found in the rest of this subclause do not apply to them unless
9334 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009335 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009336 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009337
Anders Carlssona3ccda52009-12-12 00:26:23 +00009338 if (Op == OO_New || Op == OO_Array_New)
9339 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009340
9341 // C++ [over.oper]p6:
9342 // An operator function shall either be a non-static member
9343 // function or be a non-member function and have at least one
9344 // parameter whose type is a class, a reference to a class, an
9345 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009346 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9347 if (MethodDecl->isStatic())
9348 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009349 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009350 } else {
9351 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009352 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9353 ParamEnd = FnDecl->param_end();
9354 Param != ParamEnd; ++Param) {
9355 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009356 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9357 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009358 ClassOrEnumParam = true;
9359 break;
9360 }
9361 }
9362
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009363 if (!ClassOrEnumParam)
9364 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009365 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009366 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009367 }
9368
9369 // C++ [over.oper]p8:
9370 // An operator function cannot have default arguments (8.3.6),
9371 // except where explicitly stated below.
9372 //
Mike Stump1eb44332009-09-09 15:08:12 +00009373 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009374 // (C++ [over.call]p1).
9375 if (Op != OO_Call) {
9376 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9377 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009378 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009379 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009380 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009381 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009382 }
9383 }
9384
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009385 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9386 { false, false, false }
9387#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9388 , { Unary, Binary, MemberOnly }
9389#include "clang/Basic/OperatorKinds.def"
9390 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009392 bool CanBeUnaryOperator = OperatorUses[Op][0];
9393 bool CanBeBinaryOperator = OperatorUses[Op][1];
9394 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009395
9396 // C++ [over.oper]p8:
9397 // [...] Operator functions cannot have more or fewer parameters
9398 // than the number required for the corresponding operator, as
9399 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009400 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009401 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009402 if (Op != OO_Call &&
9403 ((NumParams == 1 && !CanBeUnaryOperator) ||
9404 (NumParams == 2 && !CanBeBinaryOperator) ||
9405 (NumParams < 1) || (NumParams > 2))) {
9406 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009407 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009408 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009409 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009410 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009411 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009412 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009413 assert(CanBeBinaryOperator &&
9414 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009415 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009416 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009417
Chris Lattner416e46f2008-11-21 07:57:12 +00009418 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009419 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009420 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009421
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009422 // Overloaded operators other than operator() cannot be variadic.
9423 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009424 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009425 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009426 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009427 }
9428
9429 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009430 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9431 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009432 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009433 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009434 }
9435
9436 // C++ [over.inc]p1:
9437 // The user-defined function called operator++ implements the
9438 // prefix and postfix ++ operator. If this function is a member
9439 // function with no parameters, or a non-member function with one
9440 // parameter of class or enumeration type, it defines the prefix
9441 // increment operator ++ for objects of that type. If the function
9442 // is a member function with one parameter (which shall be of type
9443 // int) or a non-member function with two parameters (the second
9444 // of which shall be of type int), it defines the postfix
9445 // increment operator ++ for objects of that type.
9446 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9447 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9448 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009449 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009450 ParamIsInt = BT->getKind() == BuiltinType::Int;
9451
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009452 if (!ParamIsInt)
9453 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009454 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009455 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009456 }
9457
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009458 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009459}
Chris Lattner5a003a42008-12-17 07:09:26 +00009460
Sean Hunta6c058d2010-01-13 09:01:02 +00009461/// CheckLiteralOperatorDeclaration - Check whether the declaration
9462/// of this literal operator function is well-formed. If so, returns
9463/// false; otherwise, emits appropriate diagnostics and returns true.
9464bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9465 DeclContext *DC = FnDecl->getDeclContext();
9466 Decl::Kind Kind = DC->getDeclKind();
9467 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9468 Kind != Decl::LinkageSpec) {
9469 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9470 << FnDecl->getDeclName();
9471 return true;
9472 }
9473
9474 bool Valid = false;
9475
Sean Hunt216c2782010-04-07 23:11:06 +00009476 // template <char...> type operator "" name() is the only valid template
9477 // signature, and the only valid signature with no parameters.
9478 if (FnDecl->param_size() == 0) {
9479 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9480 // Must have only one template parameter
9481 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9482 if (Params->size() == 1) {
9483 NonTypeTemplateParmDecl *PmDecl =
9484 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009485
Sean Hunt216c2782010-04-07 23:11:06 +00009486 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009487 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9488 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9489 Valid = true;
9490 }
9491 }
9492 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009493 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009494 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9495
Sean Hunta6c058d2010-01-13 09:01:02 +00009496 QualType T = (*Param)->getType();
9497
Sean Hunt30019c02010-04-07 22:57:35 +00009498 // unsigned long long int, long double, and any character type are allowed
9499 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009500 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9501 Context.hasSameType(T, Context.LongDoubleTy) ||
9502 Context.hasSameType(T, Context.CharTy) ||
9503 Context.hasSameType(T, Context.WCharTy) ||
9504 Context.hasSameType(T, Context.Char16Ty) ||
9505 Context.hasSameType(T, Context.Char32Ty)) {
9506 if (++Param == FnDecl->param_end())
9507 Valid = true;
9508 goto FinishedParams;
9509 }
9510
Sean Hunt30019c02010-04-07 22:57:35 +00009511 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009512 const PointerType *PT = T->getAs<PointerType>();
9513 if (!PT)
9514 goto FinishedParams;
9515 T = PT->getPointeeType();
9516 if (!T.isConstQualified())
9517 goto FinishedParams;
9518 T = T.getUnqualifiedType();
9519
9520 // Move on to the second parameter;
9521 ++Param;
9522
9523 // If there is no second parameter, the first must be a const char *
9524 if (Param == FnDecl->param_end()) {
9525 if (Context.hasSameType(T, Context.CharTy))
9526 Valid = true;
9527 goto FinishedParams;
9528 }
9529
9530 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9531 // are allowed as the first parameter to a two-parameter function
9532 if (!(Context.hasSameType(T, Context.CharTy) ||
9533 Context.hasSameType(T, Context.WCharTy) ||
9534 Context.hasSameType(T, Context.Char16Ty) ||
9535 Context.hasSameType(T, Context.Char32Ty)))
9536 goto FinishedParams;
9537
9538 // The second and final parameter must be an std::size_t
9539 T = (*Param)->getType().getUnqualifiedType();
9540 if (Context.hasSameType(T, Context.getSizeType()) &&
9541 ++Param == FnDecl->param_end())
9542 Valid = true;
9543 }
9544
9545 // FIXME: This diagnostic is absolutely terrible.
9546FinishedParams:
9547 if (!Valid) {
9548 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9549 << FnDecl->getDeclName();
9550 return true;
9551 }
9552
Douglas Gregor1155c422011-08-30 22:40:35 +00009553 StringRef LiteralName
9554 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9555 if (LiteralName[0] != '_') {
9556 // C++0x [usrlit.suffix]p1:
9557 // Literal suffix identifiers that do not start with an underscore are
9558 // reserved for future standardization.
9559 bool IsHexFloat = true;
9560 if (LiteralName.size() > 1 &&
9561 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9562 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9563 if (!isdigit(LiteralName[I])) {
9564 IsHexFloat = false;
9565 break;
9566 }
9567 }
9568 }
9569
9570 if (IsHexFloat)
9571 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9572 << LiteralName;
9573 else
9574 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9575 }
9576
Sean Hunta6c058d2010-01-13 09:01:02 +00009577 return false;
9578}
9579
Douglas Gregor074149e2009-01-05 19:45:36 +00009580/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9581/// linkage specification, including the language and (if present)
9582/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9583/// the location of the language string literal, which is provided
9584/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9585/// the '{' brace. Otherwise, this linkage specification does not
9586/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009587Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9588 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009589 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009590 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009591 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009592 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009593 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009594 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009595 Language = LinkageSpecDecl::lang_cxx;
9596 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009597 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009598 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009599 }
Mike Stump1eb44332009-09-09 15:08:12 +00009600
Chris Lattnercc98eac2008-12-17 07:13:27 +00009601 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009602
Douglas Gregor074149e2009-01-05 19:45:36 +00009603 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009604 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009605 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009606 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009607 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009608}
9609
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009610/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009611/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9612/// valid, it's the position of the closing '}' brace in a linkage
9613/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009614Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009615 Decl *LinkageSpec,
9616 SourceLocation RBraceLoc) {
9617 if (LinkageSpec) {
9618 if (RBraceLoc.isValid()) {
9619 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9620 LSDecl->setRBraceLoc(RBraceLoc);
9621 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009622 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009623 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009624 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009625}
9626
Douglas Gregord308e622009-05-18 20:51:54 +00009627/// \brief Perform semantic analysis for the variable declaration that
9628/// occurs within a C++ catch clause, returning the newly-created
9629/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009630VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009631 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009632 SourceLocation StartLoc,
9633 SourceLocation Loc,
9634 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009635 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009636 QualType ExDeclType = TInfo->getType();
9637
Sebastian Redl4b07b292008-12-22 19:15:10 +00009638 // Arrays and functions decay.
9639 if (ExDeclType->isArrayType())
9640 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9641 else if (ExDeclType->isFunctionType())
9642 ExDeclType = Context.getPointerType(ExDeclType);
9643
9644 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9645 // The exception-declaration shall not denote a pointer or reference to an
9646 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009647 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009648 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009649 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009650 Invalid = true;
9651 }
Douglas Gregord308e622009-05-18 20:51:54 +00009652
Sebastian Redl4b07b292008-12-22 19:15:10 +00009653 QualType BaseType = ExDeclType;
9654 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009655 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009656 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009657 BaseType = Ptr->getPointeeType();
9658 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009659 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009660 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009661 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009662 BaseType = Ref->getPointeeType();
9663 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009664 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009665 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009666 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009667 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009668 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009669
Mike Stump1eb44332009-09-09 15:08:12 +00009670 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009671 RequireNonAbstractType(Loc, ExDeclType,
9672 diag::err_abstract_type_in_decl,
9673 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009674 Invalid = true;
9675
John McCall5a180392010-07-24 00:37:23 +00009676 // Only the non-fragile NeXT runtime currently supports C++ catches
9677 // of ObjC types, and no runtime supports catching ObjC types by value.
9678 if (!Invalid && getLangOptions().ObjC1) {
9679 QualType T = ExDeclType;
9680 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9681 T = RT->getPointeeType();
9682
9683 if (T->isObjCObjectType()) {
9684 Diag(Loc, diag::err_objc_object_catch);
9685 Invalid = true;
9686 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009687 if (!getLangOptions().ObjCNonFragileABI)
9688 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009689 }
9690 }
9691
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009692 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9693 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009694 ExDecl->setExceptionVariable(true);
9695
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009696 // In ARC, infer 'retaining' for variables of retainable type.
9697 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9698 Invalid = true;
9699
Douglas Gregorc41b8782011-07-06 18:14:43 +00009700 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009701 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009702 // C++ [except.handle]p16:
9703 // The object declared in an exception-declaration or, if the
9704 // exception-declaration does not specify a name, a temporary (12.2) is
9705 // copy-initialized (8.5) from the exception object. [...]
9706 // The object is destroyed when the handler exits, after the destruction
9707 // of any automatic objects initialized within the handler.
9708 //
9709 // We just pretend to initialize the object with itself, then make sure
9710 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009711 QualType initType = ExDeclType;
9712
9713 InitializedEntity entity =
9714 InitializedEntity::InitializeVariable(ExDecl);
9715 InitializationKind initKind =
9716 InitializationKind::CreateCopy(Loc, SourceLocation());
9717
9718 Expr *opaqueValue =
9719 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9720 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9721 ExprResult result = sequence.Perform(*this, entity, initKind,
9722 MultiExprArg(&opaqueValue, 1));
9723 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009724 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009725 else {
9726 // If the constructor used was non-trivial, set this as the
9727 // "initializer".
9728 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9729 if (!construct->getConstructor()->isTrivial()) {
9730 Expr *init = MaybeCreateExprWithCleanups(construct);
9731 ExDecl->setInit(init);
9732 }
9733
9734 // And make sure it's destructable.
9735 FinalizeVarWithDestructor(ExDecl, recordType);
9736 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009737 }
9738 }
9739
Douglas Gregord308e622009-05-18 20:51:54 +00009740 if (Invalid)
9741 ExDecl->setInvalidDecl();
9742
9743 return ExDecl;
9744}
9745
9746/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9747/// handler.
John McCalld226f652010-08-21 09:40:31 +00009748Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009750 bool Invalid = D.isInvalidType();
9751
9752 // Check for unexpanded parameter packs.
9753 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9754 UPPC_ExceptionType)) {
9755 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9756 D.getIdentifierLoc());
9757 Invalid = true;
9758 }
9759
Sebastian Redl4b07b292008-12-22 19:15:10 +00009760 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009761 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009762 LookupOrdinaryName,
9763 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009764 // The scope should be freshly made just for us. There is just no way
9765 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009766 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009767 if (PrevDecl->isTemplateParameter()) {
9768 // Maybe we will complain about the shadowed template parameter.
9769 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009770 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009771 }
9772 }
9773
Chris Lattnereaaebc72009-04-25 08:06:05 +00009774 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009775 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9776 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009777 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009778 }
9779
Douglas Gregor83cb9422010-09-09 17:09:21 +00009780 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009781 D.getSourceRange().getBegin(),
9782 D.getIdentifierLoc(),
9783 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009784 if (Invalid)
9785 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009786
Sebastian Redl4b07b292008-12-22 19:15:10 +00009787 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009788 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009789 PushOnScopeChains(ExDecl, S);
9790 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009791 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009792
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009793 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009794 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009795}
Anders Carlssonfb311762009-03-14 00:25:26 +00009796
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009797Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009798 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009799 Expr *AssertMessageExpr_,
9800 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009801 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009802
Anders Carlssonc3082412009-03-14 00:33:21 +00009803 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009804 // In a static_assert-declaration, the constant-expression shall be a
9805 // constant expression that can be contextually converted to bool.
9806 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9807 if (Converted.isInvalid())
9808 return 0;
9809
Richard Smithdaaefc52011-12-14 23:32:26 +00009810 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009811 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9812 PDiag(diag::err_static_assert_expression_is_not_constant),
9813 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009814 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009815
Richard Smithdaaefc52011-12-14 23:32:26 +00009816 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009817 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009818 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009819 }
Mike Stump1eb44332009-09-09 15:08:12 +00009820
Douglas Gregor399ad972010-12-15 23:55:21 +00009821 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9822 return 0;
9823
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009824 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9825 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009826
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009827 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009828 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009829}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009830
Douglas Gregor1d869352010-04-07 16:53:43 +00009831/// \brief Perform semantic analysis of the given friend type declaration.
9832///
9833/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009834FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9835 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009836 TypeSourceInfo *TSInfo) {
9837 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9838
9839 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009840 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009841
Richard Smith6b130222011-10-18 21:39:00 +00009842 // C++03 [class.friend]p2:
9843 // An elaborated-type-specifier shall be used in a friend declaration
9844 // for a class.*
9845 //
9846 // * The class-key of the elaborated-type-specifier is required.
9847 if (!ActiveTemplateInstantiations.empty()) {
9848 // Do not complain about the form of friend template types during
9849 // template instantiation; we will already have complained when the
9850 // template was declared.
9851 } else if (!T->isElaboratedTypeSpecifier()) {
9852 // If we evaluated the type to a record type, suggest putting
9853 // a tag in front.
9854 if (const RecordType *RT = T->getAs<RecordType>()) {
9855 RecordDecl *RD = RT->getDecl();
9856
9857 std::string InsertionText = std::string(" ") + RD->getKindName();
9858
9859 Diag(TypeRange.getBegin(),
9860 getLangOptions().CPlusPlus0x ?
9861 diag::warn_cxx98_compat_unelaborated_friend_type :
9862 diag::ext_unelaborated_friend_type)
9863 << (unsigned) RD->getTagKind()
9864 << T
9865 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9866 InsertionText);
9867 } else {
9868 Diag(FriendLoc,
9869 getLangOptions().CPlusPlus0x ?
9870 diag::warn_cxx98_compat_nonclass_type_friend :
9871 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009872 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009873 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009874 }
Richard Smith6b130222011-10-18 21:39:00 +00009875 } else if (T->getAs<EnumType>()) {
9876 Diag(FriendLoc,
9877 getLangOptions().CPlusPlus0x ?
9878 diag::warn_cxx98_compat_enum_friend :
9879 diag::ext_enum_friend)
9880 << T
9881 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009882 }
9883
Douglas Gregor06245bf2010-04-07 17:57:12 +00009884 // C++0x [class.friend]p3:
9885 // If the type specifier in a friend declaration designates a (possibly
9886 // cv-qualified) class type, that class is declared as a friend; otherwise,
9887 // the friend declaration is ignored.
9888
9889 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9890 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009891
Abramo Bagnara0216df82011-10-29 20:52:52 +00009892 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009893}
9894
John McCall9a34edb2010-10-19 01:40:49 +00009895/// Handle a friend tag declaration where the scope specifier was
9896/// templated.
9897Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9898 unsigned TagSpec, SourceLocation TagLoc,
9899 CXXScopeSpec &SS,
9900 IdentifierInfo *Name, SourceLocation NameLoc,
9901 AttributeList *Attr,
9902 MultiTemplateParamsArg TempParamLists) {
9903 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9904
9905 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009906 bool Invalid = false;
9907
9908 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009909 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009910 TempParamLists.get(),
9911 TempParamLists.size(),
9912 /*friend*/ true,
9913 isExplicitSpecialization,
9914 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009915 if (TemplateParams->size() > 0) {
9916 // This is a declaration of a class template.
9917 if (Invalid)
9918 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009919
Eric Christopher4110e132011-07-21 05:34:24 +00009920 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9921 SS, Name, NameLoc, Attr,
9922 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009923 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009924 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009925 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009926 } else {
9927 // The "template<>" header is extraneous.
9928 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9929 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9930 isExplicitSpecialization = true;
9931 }
9932 }
9933
9934 if (Invalid) return 0;
9935
John McCall9a34edb2010-10-19 01:40:49 +00009936 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009937 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009938 if (TempParamLists.get()[I]->size()) {
9939 isAllExplicitSpecializations = false;
9940 break;
9941 }
9942 }
9943
9944 // FIXME: don't ignore attributes.
9945
9946 // If it's explicit specializations all the way down, just forget
9947 // about the template header and build an appropriate non-templated
9948 // friend. TODO: for source fidelity, remember the headers.
9949 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009950 if (SS.isEmpty()) {
9951 bool Owned = false;
9952 bool IsDependent = false;
9953 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9954 Attr, AS_public,
9955 /*ModulePrivateLoc=*/SourceLocation(),
9956 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009957 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009958 /*ScopedEnumUsesClassTag=*/false,
9959 /*UnderlyingType=*/TypeResult());
9960 }
9961
Douglas Gregor2494dd02011-03-01 01:34:45 +00009962 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009963 ElaboratedTypeKeyword Keyword
9964 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009965 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009966 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009967 if (T.isNull())
9968 return 0;
9969
9970 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9971 if (isa<DependentNameType>(T)) {
9972 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009973 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009974 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009975 TL.setNameLoc(NameLoc);
9976 } else {
9977 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009978 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009979 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009980 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9981 }
9982
9983 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9984 TSI, FriendLoc);
9985 Friend->setAccess(AS_public);
9986 CurContext->addDecl(Friend);
9987 return Friend;
9988 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009989
9990 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9991
9992
John McCall9a34edb2010-10-19 01:40:49 +00009993
9994 // Handle the case of a templated-scope friend class. e.g.
9995 // template <class T> class A<T>::B;
9996 // FIXME: we don't support these right now.
9997 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9998 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9999 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10000 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010001 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010002 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010003 TL.setNameLoc(NameLoc);
10004
10005 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10006 TSI, FriendLoc);
10007 Friend->setAccess(AS_public);
10008 Friend->setUnsupportedFriend(true);
10009 CurContext->addDecl(Friend);
10010 return Friend;
10011}
10012
10013
John McCalldd4a3b02009-09-16 22:47:08 +000010014/// Handle a friend type declaration. This works in tandem with
10015/// ActOnTag.
10016///
10017/// Notes on friend class templates:
10018///
10019/// We generally treat friend class declarations as if they were
10020/// declaring a class. So, for example, the elaborated type specifier
10021/// in a friend declaration is required to obey the restrictions of a
10022/// class-head (i.e. no typedefs in the scope chain), template
10023/// parameters are required to match up with simple template-ids, &c.
10024/// However, unlike when declaring a template specialization, it's
10025/// okay to refer to a template specialization without an empty
10026/// template parameter declaration, e.g.
10027/// friend class A<T>::B<unsigned>;
10028/// We permit this as a special case; if there are any template
10029/// parameters present at all, require proper matching, i.e.
10030/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010031Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010032 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010033 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010034
10035 assert(DS.isFriendSpecified());
10036 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10037
John McCalldd4a3b02009-09-16 22:47:08 +000010038 // Try to convert the decl specifier to a type. This works for
10039 // friend templates because ActOnTag never produces a ClassTemplateDecl
10040 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010041 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010042 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10043 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010044 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010045 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010046
Douglas Gregor6ccab972010-12-16 01:14:37 +000010047 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10048 return 0;
10049
John McCalldd4a3b02009-09-16 22:47:08 +000010050 // This is definitely an error in C++98. It's probably meant to
10051 // be forbidden in C++0x, too, but the specification is just
10052 // poorly written.
10053 //
10054 // The problem is with declarations like the following:
10055 // template <T> friend A<T>::foo;
10056 // where deciding whether a class C is a friend or not now hinges
10057 // on whether there exists an instantiation of A that causes
10058 // 'foo' to equal C. There are restrictions on class-heads
10059 // (which we declare (by fiat) elaborated friend declarations to
10060 // be) that makes this tractable.
10061 //
10062 // FIXME: handle "template <> friend class A<T>;", which
10063 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010064 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010065 Diag(Loc, diag::err_tagless_friend_type_template)
10066 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010067 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010068 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010069
John McCall02cace72009-08-28 07:59:38 +000010070 // C++98 [class.friend]p1: A friend of a class is a function
10071 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010072 // This is fixed in DR77, which just barely didn't make the C++03
10073 // deadline. It's also a very silly restriction that seriously
10074 // affects inner classes and which nobody else seems to implement;
10075 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010076 //
10077 // But note that we could warn about it: it's always useless to
10078 // friend one of your own members (it's not, however, worthless to
10079 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010080
John McCalldd4a3b02009-09-16 22:47:08 +000010081 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010082 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010083 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010084 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010085 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010086 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010087 DS.getFriendSpecLoc());
10088 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010089 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010090
10091 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010092 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010093
John McCalldd4a3b02009-09-16 22:47:08 +000010094 D->setAccess(AS_public);
10095 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010096
John McCalld226f652010-08-21 09:40:31 +000010097 return D;
John McCall02cace72009-08-28 07:59:38 +000010098}
10099
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010100Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010101 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010102 const DeclSpec &DS = D.getDeclSpec();
10103
10104 assert(DS.isFriendSpecified());
10105 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10106
10107 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010108 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010109
10110 // C++ [class.friend]p1
10111 // A friend of a class is a function or class....
10112 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010113 // It *doesn't* see through dependent types, which is correct
10114 // according to [temp.arg.type]p3:
10115 // If a declaration acquires a function type through a
10116 // type dependent on a template-parameter and this causes
10117 // a declaration that does not use the syntactic form of a
10118 // function declarator to have a function type, the program
10119 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010120 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010121 Diag(Loc, diag::err_unexpected_friend);
10122
10123 // It might be worthwhile to try to recover by creating an
10124 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010125 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010126 }
10127
10128 // C++ [namespace.memdef]p3
10129 // - If a friend declaration in a non-local class first declares a
10130 // class or function, the friend class or function is a member
10131 // of the innermost enclosing namespace.
10132 // - The name of the friend is not found by simple name lookup
10133 // until a matching declaration is provided in that namespace
10134 // scope (either before or after the class declaration granting
10135 // friendship).
10136 // - If a friend function is called, its name may be found by the
10137 // name lookup that considers functions from namespaces and
10138 // classes associated with the types of the function arguments.
10139 // - When looking for a prior declaration of a class or a function
10140 // declared as a friend, scopes outside the innermost enclosing
10141 // namespace scope are not considered.
10142
John McCall337ec3d2010-10-12 23:13:28 +000010143 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010144 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10145 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010146 assert(Name);
10147
Douglas Gregor6ccab972010-12-16 01:14:37 +000010148 // Check for unexpanded parameter packs.
10149 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10150 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10151 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10152 return 0;
10153
John McCall67d1a672009-08-06 02:15:43 +000010154 // The context we found the declaration in, or in which we should
10155 // create the declaration.
10156 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010157 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010158 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010159 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010160
John McCall337ec3d2010-10-12 23:13:28 +000010161 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010162
John McCall337ec3d2010-10-12 23:13:28 +000010163 // There are four cases here.
10164 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010165 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010166 // there as appropriate.
10167 // Recover from invalid scope qualifiers as if they just weren't there.
10168 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010169 // C++0x [namespace.memdef]p3:
10170 // If the name in a friend declaration is neither qualified nor
10171 // a template-id and the declaration is a function or an
10172 // elaborated-type-specifier, the lookup to determine whether
10173 // the entity has been previously declared shall not consider
10174 // any scopes outside the innermost enclosing namespace.
10175 // C++0x [class.friend]p11:
10176 // If a friend declaration appears in a local class and the name
10177 // specified is an unqualified name, a prior declaration is
10178 // looked up without considering scopes that are outside the
10179 // innermost enclosing non-class scope. For a friend function
10180 // declaration, if there is no prior declaration, the program is
10181 // ill-formed.
10182 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010183 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010184
John McCall29ae6e52010-10-13 05:45:15 +000010185 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010186 DC = CurContext;
10187 while (true) {
10188 // Skip class contexts. If someone can cite chapter and verse
10189 // for this behavior, that would be nice --- it's what GCC and
10190 // EDG do, and it seems like a reasonable intent, but the spec
10191 // really only says that checks for unqualified existing
10192 // declarations should stop at the nearest enclosing namespace,
10193 // not that they should only consider the nearest enclosing
10194 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010195 while (DC->isRecord())
10196 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010197
John McCall68263142009-11-18 22:49:29 +000010198 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010199
10200 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010201 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010202 break;
John McCall29ae6e52010-10-13 05:45:15 +000010203
John McCall8a407372010-10-14 22:22:28 +000010204 if (isTemplateId) {
10205 if (isa<TranslationUnitDecl>(DC)) break;
10206 } else {
10207 if (DC->isFileContext()) break;
10208 }
John McCall67d1a672009-08-06 02:15:43 +000010209 DC = DC->getParent();
10210 }
10211
10212 // C++ [class.friend]p1: A friend of a class is a function or
10213 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010214 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010215 // Most C++ 98 compilers do seem to give an error here, so
10216 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010217 if (!Previous.empty() && DC->Equals(CurContext))
10218 Diag(DS.getFriendSpecLoc(),
10219 getLangOptions().CPlusPlus0x ?
10220 diag::warn_cxx98_compat_friend_is_member :
10221 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010222
John McCall380aaa42010-10-13 06:22:15 +000010223 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010224
Douglas Gregor883af832011-10-10 01:11:59 +000010225 // C++ [class.friend]p6:
10226 // A function can be defined in a friend declaration of a class if and
10227 // only if the class is a non-local class (9.8), the function name is
10228 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010229 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010230 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10231 }
10232
John McCall337ec3d2010-10-12 23:13:28 +000010233 // - There's a non-dependent scope specifier, in which case we
10234 // compute it and do a previous lookup there for a function
10235 // or function template.
10236 } else if (!SS.getScopeRep()->isDependent()) {
10237 DC = computeDeclContext(SS);
10238 if (!DC) return 0;
10239
10240 if (RequireCompleteDeclContext(SS, DC)) return 0;
10241
10242 LookupQualifiedName(Previous, DC);
10243
10244 // Ignore things found implicitly in the wrong scope.
10245 // TODO: better diagnostics for this case. Suggesting the right
10246 // qualified scope would be nice...
10247 LookupResult::Filter F = Previous.makeFilter();
10248 while (F.hasNext()) {
10249 NamedDecl *D = F.next();
10250 if (!DC->InEnclosingNamespaceSetOf(
10251 D->getDeclContext()->getRedeclContext()))
10252 F.erase();
10253 }
10254 F.done();
10255
10256 if (Previous.empty()) {
10257 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010258 Diag(Loc, diag::err_qualified_friend_not_found)
10259 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010260 return 0;
10261 }
10262
10263 // C++ [class.friend]p1: A friend of a class is a function or
10264 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010265 if (DC->Equals(CurContext))
10266 Diag(DS.getFriendSpecLoc(),
10267 getLangOptions().CPlusPlus0x ?
10268 diag::warn_cxx98_compat_friend_is_member :
10269 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010270
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010271 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010272 // C++ [class.friend]p6:
10273 // A function can be defined in a friend declaration of a class if and
10274 // only if the class is a non-local class (9.8), the function name is
10275 // unqualified, and the function has namespace scope.
10276 SemaDiagnosticBuilder DB
10277 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10278
10279 DB << SS.getScopeRep();
10280 if (DC->isFileContext())
10281 DB << FixItHint::CreateRemoval(SS.getRange());
10282 SS.clear();
10283 }
John McCall337ec3d2010-10-12 23:13:28 +000010284
10285 // - There's a scope specifier that does not match any template
10286 // parameter lists, in which case we use some arbitrary context,
10287 // create a method or method template, and wait for instantiation.
10288 // - There's a scope specifier that does match some template
10289 // parameter lists, which we don't handle right now.
10290 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010291 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010292 // C++ [class.friend]p6:
10293 // A function can be defined in a friend declaration of a class if and
10294 // only if the class is a non-local class (9.8), the function name is
10295 // unqualified, and the function has namespace scope.
10296 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10297 << SS.getScopeRep();
10298 }
10299
John McCall337ec3d2010-10-12 23:13:28 +000010300 DC = CurContext;
10301 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010302 }
Douglas Gregor883af832011-10-10 01:11:59 +000010303
John McCall29ae6e52010-10-13 05:45:15 +000010304 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010305 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010306 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10307 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10308 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010309 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010310 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10311 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010312 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010313 }
John McCall67d1a672009-08-06 02:15:43 +000010314 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010315
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010316 // FIXME: This is an egregious hack to cope with cases where the scope stack
10317 // does not contain the declaration context, i.e., in an out-of-line
10318 // definition of a class.
10319 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10320 if (!DCScope) {
10321 FakeDCScope.setEntity(DC);
10322 DCScope = &FakeDCScope;
10323 }
10324
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010325 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010326 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10327 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010328 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010329
Douglas Gregor182ddf02009-09-28 00:08:27 +000010330 assert(ND->getDeclContext() == DC);
10331 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010332
John McCallab88d972009-08-31 22:39:49 +000010333 // Add the function declaration to the appropriate lookup tables,
10334 // adjusting the redeclarations list as necessary. We don't
10335 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010336 //
John McCallab88d972009-08-31 22:39:49 +000010337 // Also update the scope-based lookup if the target context's
10338 // lookup context is in lexical scope.
10339 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010340 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010341 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010342 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010343 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010344 }
John McCall02cace72009-08-28 07:59:38 +000010345
10346 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010347 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010348 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010349 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010350 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010351
John McCall337ec3d2010-10-12 23:13:28 +000010352 if (ND->isInvalidDecl())
10353 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010354 else {
10355 FunctionDecl *FD;
10356 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10357 FD = FTD->getTemplatedDecl();
10358 else
10359 FD = cast<FunctionDecl>(ND);
10360
10361 // Mark templated-scope function declarations as unsupported.
10362 if (FD->getNumTemplateParameterLists())
10363 FrD->setUnsupportedFriend(true);
10364 }
John McCall337ec3d2010-10-12 23:13:28 +000010365
John McCalld226f652010-08-21 09:40:31 +000010366 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010367}
10368
John McCalld226f652010-08-21 09:40:31 +000010369void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10370 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010371
Sebastian Redl50de12f2009-03-24 22:27:57 +000010372 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10373 if (!Fn) {
10374 Diag(DelLoc, diag::err_deleted_non_function);
10375 return;
10376 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010377 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010378 Diag(DelLoc, diag::err_deleted_decl_not_first);
10379 Diag(Prev->getLocation(), diag::note_previous_declaration);
10380 // If the declaration wasn't the first, we delete the function anyway for
10381 // recovery.
10382 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010383 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010384}
Sebastian Redl13e88542009-04-27 21:33:24 +000010385
Sean Hunte4246a62011-05-12 06:15:49 +000010386void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10387 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10388
10389 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010390 if (MD->getParent()->isDependentType()) {
10391 MD->setDefaulted();
10392 MD->setExplicitlyDefaulted();
10393 return;
10394 }
10395
Sean Hunte4246a62011-05-12 06:15:49 +000010396 CXXSpecialMember Member = getSpecialMember(MD);
10397 if (Member == CXXInvalid) {
10398 Diag(DefaultLoc, diag::err_default_special_members);
10399 return;
10400 }
10401
10402 MD->setDefaulted();
10403 MD->setExplicitlyDefaulted();
10404
Sean Huntcd10dec2011-05-23 23:14:04 +000010405 // If this definition appears within the record, do the checking when
10406 // the record is complete.
10407 const FunctionDecl *Primary = MD;
10408 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10409 // Find the uninstantiated declaration that actually had the '= default'
10410 // on it.
10411 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10412
10413 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010414 return;
10415
10416 switch (Member) {
10417 case CXXDefaultConstructor: {
10418 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10419 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010420 if (!CD->isInvalidDecl())
10421 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10422 break;
10423 }
10424
10425 case CXXCopyConstructor: {
10426 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10427 CheckExplicitlyDefaultedCopyConstructor(CD);
10428 if (!CD->isInvalidDecl())
10429 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010430 break;
10431 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010432
Sean Hunt2b188082011-05-14 05:23:28 +000010433 case CXXCopyAssignment: {
10434 CheckExplicitlyDefaultedCopyAssignment(MD);
10435 if (!MD->isInvalidDecl())
10436 DefineImplicitCopyAssignment(DefaultLoc, MD);
10437 break;
10438 }
10439
Sean Huntcb45a0f2011-05-12 22:46:25 +000010440 case CXXDestructor: {
10441 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10442 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010443 if (!DD->isInvalidDecl())
10444 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010445 break;
10446 }
10447
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010448 case CXXMoveConstructor: {
10449 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10450 CheckExplicitlyDefaultedMoveConstructor(CD);
10451 if (!CD->isInvalidDecl())
10452 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010453 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010454 }
Sean Hunt82713172011-05-25 23:16:36 +000010455
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010456 case CXXMoveAssignment: {
10457 CheckExplicitlyDefaultedMoveAssignment(MD);
10458 if (!MD->isInvalidDecl())
10459 DefineImplicitMoveAssignment(DefaultLoc, MD);
10460 break;
10461 }
10462
10463 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010464 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010465 }
10466 } else {
10467 Diag(DefaultLoc, diag::err_default_special_members);
10468 }
10469}
10470
Sebastian Redl13e88542009-04-27 21:33:24 +000010471static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010472 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010473 Stmt *SubStmt = *CI;
10474 if (!SubStmt)
10475 continue;
10476 if (isa<ReturnStmt>(SubStmt))
10477 Self.Diag(SubStmt->getSourceRange().getBegin(),
10478 diag::err_return_in_constructor_handler);
10479 if (!isa<Expr>(SubStmt))
10480 SearchForReturnInStmt(Self, SubStmt);
10481 }
10482}
10483
10484void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10485 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10486 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10487 SearchForReturnInStmt(*this, Handler);
10488 }
10489}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010490
Mike Stump1eb44332009-09-09 15:08:12 +000010491bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010492 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010493 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10494 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010495
Chandler Carruth73857792010-02-15 11:53:20 +000010496 if (Context.hasSameType(NewTy, OldTy) ||
10497 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010498 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010499
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010500 // Check if the return types are covariant
10501 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010502
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010503 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010504 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10505 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010506 NewClassTy = NewPT->getPointeeType();
10507 OldClassTy = OldPT->getPointeeType();
10508 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010509 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10510 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10511 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10512 NewClassTy = NewRT->getPointeeType();
10513 OldClassTy = OldRT->getPointeeType();
10514 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010515 }
10516 }
Mike Stump1eb44332009-09-09 15:08:12 +000010517
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010518 // The return types aren't either both pointers or references to a class type.
10519 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010520 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010521 diag::err_different_return_type_for_overriding_virtual_function)
10522 << New->getDeclName() << NewTy << OldTy;
10523 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010524
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010525 return true;
10526 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010527
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010528 // C++ [class.virtual]p6:
10529 // If the return type of D::f differs from the return type of B::f, the
10530 // class type in the return type of D::f shall be complete at the point of
10531 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010532 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10533 if (!RT->isBeingDefined() &&
10534 RequireCompleteType(New->getLocation(), NewClassTy,
10535 PDiag(diag::err_covariant_return_incomplete)
10536 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010537 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010538 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010539
Douglas Gregora4923eb2009-11-16 21:35:15 +000010540 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010541 // Check if the new class derives from the old class.
10542 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10543 Diag(New->getLocation(),
10544 diag::err_covariant_return_not_derived)
10545 << New->getDeclName() << NewTy << OldTy;
10546 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10547 return true;
10548 }
Mike Stump1eb44332009-09-09 15:08:12 +000010549
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010550 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010551 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010552 diag::err_covariant_return_inaccessible_base,
10553 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10554 // FIXME: Should this point to the return type?
10555 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010556 // FIXME: this note won't trigger for delayed access control
10557 // diagnostics, and it's impossible to get an undelayed error
10558 // here from access control during the original parse because
10559 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010560 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10561 return true;
10562 }
10563 }
Mike Stump1eb44332009-09-09 15:08:12 +000010564
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010565 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010566 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010567 Diag(New->getLocation(),
10568 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010569 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010570 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10571 return true;
10572 };
Mike Stump1eb44332009-09-09 15:08:12 +000010573
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010574
10575 // The new class type must have the same or less qualifiers as the old type.
10576 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10577 Diag(New->getLocation(),
10578 diag::err_covariant_return_type_class_type_more_qualified)
10579 << New->getDeclName() << NewTy << OldTy;
10580 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10581 return true;
10582 };
Mike Stump1eb44332009-09-09 15:08:12 +000010583
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010584 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010585}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010586
Douglas Gregor4ba31362009-12-01 17:24:26 +000010587/// \brief Mark the given method pure.
10588///
10589/// \param Method the method to be marked pure.
10590///
10591/// \param InitRange the source range that covers the "0" initializer.
10592bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010593 SourceLocation EndLoc = InitRange.getEnd();
10594 if (EndLoc.isValid())
10595 Method->setRangeEnd(EndLoc);
10596
Douglas Gregor4ba31362009-12-01 17:24:26 +000010597 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10598 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010599 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010600 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010601
10602 if (!Method->isInvalidDecl())
10603 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10604 << Method->getDeclName() << InitRange;
10605 return true;
10606}
10607
John McCall731ad842009-12-19 09:28:58 +000010608/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10609/// an initializer for the out-of-line declaration 'Dcl'. The scope
10610/// is a fresh scope pushed for just this purpose.
10611///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010612/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10613/// static data member of class X, names should be looked up in the scope of
10614/// class X.
John McCalld226f652010-08-21 09:40:31 +000010615void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010616 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010617 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010618
John McCall731ad842009-12-19 09:28:58 +000010619 // We should only get called for declarations with scope specifiers, like:
10620 // int foo::bar;
10621 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010622 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010623}
10624
10625/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010626/// initializer for the out-of-line declaration 'D'.
10627void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010628 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010629 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010630
John McCall731ad842009-12-19 09:28:58 +000010631 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010632 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010633}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010634
10635/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10636/// C++ if/switch/while/for statement.
10637/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010638DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010639 // C++ 6.4p2:
10640 // The declarator shall not specify a function or an array.
10641 // The type-specifier-seq shall not contain typedef and shall not declare a
10642 // new class or enumeration.
10643 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10644 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010645
10646 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010647 if (!Dcl)
10648 return true;
10649
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010650 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10651 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010652 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010653 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010654 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010655
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010656 return Dcl;
10657}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010658
Douglas Gregordfe65432011-07-28 19:11:31 +000010659void Sema::LoadExternalVTableUses() {
10660 if (!ExternalSource)
10661 return;
10662
10663 SmallVector<ExternalVTableUse, 4> VTables;
10664 ExternalSource->ReadUsedVTables(VTables);
10665 SmallVector<VTableUse, 4> NewUses;
10666 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10667 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10668 = VTablesUsed.find(VTables[I].Record);
10669 // Even if a definition wasn't required before, it may be required now.
10670 if (Pos != VTablesUsed.end()) {
10671 if (!Pos->second && VTables[I].DefinitionRequired)
10672 Pos->second = true;
10673 continue;
10674 }
10675
10676 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10677 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10678 }
10679
10680 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10681}
10682
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010683void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10684 bool DefinitionRequired) {
10685 // Ignore any vtable uses in unevaluated operands or for classes that do
10686 // not have a vtable.
10687 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10688 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010689 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010690 return;
10691
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010692 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010693 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010694 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10695 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10696 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10697 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010698 // If we already had an entry, check to see if we are promoting this vtable
10699 // to required a definition. If so, we need to reappend to the VTableUses
10700 // list, since we may have already processed the first entry.
10701 if (DefinitionRequired && !Pos.first->second) {
10702 Pos.first->second = true;
10703 } else {
10704 // Otherwise, we can early exit.
10705 return;
10706 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010707 }
10708
10709 // Local classes need to have their virtual members marked
10710 // immediately. For all other classes, we mark their virtual members
10711 // at the end of the translation unit.
10712 if (Class->isLocalClass())
10713 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010714 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010715 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010716}
10717
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010718bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010719 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010720 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010721 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010722
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010723 // Note: The VTableUses vector could grow as a result of marking
10724 // the members of a class as "used", so we check the size each
10725 // time through the loop and prefer indices (with are stable) to
10726 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010727 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010728 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010729 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010730 if (!Class)
10731 continue;
10732
10733 SourceLocation Loc = VTableUses[I].second;
10734
10735 // If this class has a key function, but that key function is
10736 // defined in another translation unit, we don't need to emit the
10737 // vtable even though we're using it.
10738 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010739 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010740 switch (KeyFunction->getTemplateSpecializationKind()) {
10741 case TSK_Undeclared:
10742 case TSK_ExplicitSpecialization:
10743 case TSK_ExplicitInstantiationDeclaration:
10744 // The key function is in another translation unit.
10745 continue;
10746
10747 case TSK_ExplicitInstantiationDefinition:
10748 case TSK_ImplicitInstantiation:
10749 // We will be instantiating the key function.
10750 break;
10751 }
10752 } else if (!KeyFunction) {
10753 // If we have a class with no key function that is the subject
10754 // of an explicit instantiation declaration, suppress the
10755 // vtable; it will live with the explicit instantiation
10756 // definition.
10757 bool IsExplicitInstantiationDeclaration
10758 = Class->getTemplateSpecializationKind()
10759 == TSK_ExplicitInstantiationDeclaration;
10760 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10761 REnd = Class->redecls_end();
10762 R != REnd; ++R) {
10763 TemplateSpecializationKind TSK
10764 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10765 if (TSK == TSK_ExplicitInstantiationDeclaration)
10766 IsExplicitInstantiationDeclaration = true;
10767 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10768 IsExplicitInstantiationDeclaration = false;
10769 break;
10770 }
10771 }
10772
10773 if (IsExplicitInstantiationDeclaration)
10774 continue;
10775 }
10776
10777 // Mark all of the virtual members of this class as referenced, so
10778 // that we can build a vtable. Then, tell the AST consumer that a
10779 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010780 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010781 MarkVirtualMembersReferenced(Loc, Class);
10782 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10783 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10784
10785 // Optionally warn if we're emitting a weak vtable.
10786 if (Class->getLinkage() == ExternalLinkage &&
10787 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010788 const FunctionDecl *KeyFunctionDef = 0;
10789 if (!KeyFunction ||
10790 (KeyFunction->hasBody(KeyFunctionDef) &&
10791 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010792 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10793 TSK_ExplicitInstantiationDefinition
10794 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10795 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010796 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010797 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010798 VTableUses.clear();
10799
Douglas Gregor78844032011-04-22 22:25:37 +000010800 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010801}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010802
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010803void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10804 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010805 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10806 e = RD->method_end(); i != e; ++i) {
10807 CXXMethodDecl *MD = *i;
10808
10809 // C++ [basic.def.odr]p2:
10810 // [...] A virtual member function is used if it is not pure. [...]
10811 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010812 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010813 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010814
10815 // Only classes that have virtual bases need a VTT.
10816 if (RD->getNumVBases() == 0)
10817 return;
10818
10819 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10820 e = RD->bases_end(); i != e; ++i) {
10821 const CXXRecordDecl *Base =
10822 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010823 if (Base->getNumVBases() == 0)
10824 continue;
10825 MarkVirtualMembersReferenced(Loc, Base);
10826 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010827}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010828
10829/// SetIvarInitializers - This routine builds initialization ASTs for the
10830/// Objective-C implementation whose ivars need be initialized.
10831void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10832 if (!getLangOptions().CPlusPlus)
10833 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010834 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010835 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010836 CollectIvarsToConstructOrDestruct(OID, ivars);
10837 if (ivars.empty())
10838 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010839 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010840 for (unsigned i = 0; i < ivars.size(); i++) {
10841 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010842 if (Field->isInvalidDecl())
10843 continue;
10844
Sean Huntcbb67482011-01-08 20:30:50 +000010845 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010846 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10847 InitializationKind InitKind =
10848 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10849
10850 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010851 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010852 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010853 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010854 // Note, MemberInit could actually come back empty if no initialization
10855 // is required (e.g., because it would call a trivial default constructor)
10856 if (!MemberInit.get() || MemberInit.isInvalid())
10857 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010858
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010859 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010860 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10861 SourceLocation(),
10862 MemberInit.takeAs<Expr>(),
10863 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010864 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010865
10866 // Be sure that the destructor is accessible and is marked as referenced.
10867 if (const RecordType *RecordTy
10868 = Context.getBaseElementType(Field->getType())
10869 ->getAs<RecordType>()) {
10870 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010871 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010872 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010873 CheckDestructorAccess(Field->getLocation(), Destructor,
10874 PDiag(diag::err_access_dtor_ivar)
10875 << Context.getBaseElementType(Field->getType()));
10876 }
10877 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010878 }
10879 ObjCImplementation->setIvarInitializers(Context,
10880 AllToInit.data(), AllToInit.size());
10881 }
10882}
Sean Huntfe57eef2011-05-04 05:57:24 +000010883
Sean Huntebcbe1d2011-05-04 23:29:54 +000010884static
10885void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10886 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10887 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10888 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10889 Sema &S) {
10890 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10891 CE = Current.end();
10892 if (Ctor->isInvalidDecl())
10893 return;
10894
10895 const FunctionDecl *FNTarget = 0;
10896 CXXConstructorDecl *Target;
10897
10898 // We ignore the result here since if we don't have a body, Target will be
10899 // null below.
10900 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10901 Target
10902= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10903
10904 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10905 // Avoid dereferencing a null pointer here.
10906 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10907
10908 if (!Current.insert(Canonical))
10909 return;
10910
10911 // We know that beyond here, we aren't chaining into a cycle.
10912 if (!Target || !Target->isDelegatingConstructor() ||
10913 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10914 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10915 Valid.insert(*CI);
10916 Current.clear();
10917 // We've hit a cycle.
10918 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10919 Current.count(TCanonical)) {
10920 // If we haven't diagnosed this cycle yet, do so now.
10921 if (!Invalid.count(TCanonical)) {
10922 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010923 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010924 << Ctor;
10925
10926 // Don't add a note for a function delegating directo to itself.
10927 if (TCanonical != Canonical)
10928 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10929
10930 CXXConstructorDecl *C = Target;
10931 while (C->getCanonicalDecl() != Canonical) {
10932 (void)C->getTargetConstructor()->hasBody(FNTarget);
10933 assert(FNTarget && "Ctor cycle through bodiless function");
10934
10935 C
10936 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10937 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10938 }
10939 }
10940
10941 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10942 Invalid.insert(*CI);
10943 Current.clear();
10944 } else {
10945 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10946 }
10947}
10948
10949
Sean Huntfe57eef2011-05-04 05:57:24 +000010950void Sema::CheckDelegatingCtorCycles() {
10951 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10952
Sean Huntebcbe1d2011-05-04 23:29:54 +000010953 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10954 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010955
Douglas Gregor0129b562011-07-27 21:57:17 +000010956 for (DelegatingCtorDeclsType::iterator
10957 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010958 E = DelegatingCtorDecls.end();
10959 I != E; ++I) {
10960 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010961 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010962
10963 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10964 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010965}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010966
10967/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10968Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10969 // Implicitly declared functions (e.g. copy constructors) are
10970 // __host__ __device__
10971 if (D->isImplicit())
10972 return CFT_HostDevice;
10973
10974 if (D->hasAttr<CUDAGlobalAttr>())
10975 return CFT_Global;
10976
10977 if (D->hasAttr<CUDADeviceAttr>()) {
10978 if (D->hasAttr<CUDAHostAttr>())
10979 return CFT_HostDevice;
10980 else
10981 return CFT_Device;
10982 }
10983
10984 return CFT_Host;
10985}
10986
10987bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10988 CUDAFunctionTarget CalleeTarget) {
10989 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10990 // Callable from the device only."
10991 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10992 return true;
10993
10994 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10995 // Callable from the host only."
10996 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10997 // Callable from the host only."
10998 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10999 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11000 return true;
11001
11002 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11003 return true;
11004
11005 return false;
11006}