blob: 72a8de2b71e0a933bf49e8b2d52ea44498235554 [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 {
2153 // Initialize the member.
2154 InitializedEntity MemberEntity =
2155 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2156 : InitializedEntity::InitializeMember(IndirectMember, 0);
2157 InitializationKind Kind =
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002158 InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2159 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002160
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002161 if (isa<InitListExpr>(Init)) {
2162 Args = &Init;
2163 NumArgs = 1;
2164 }
2165 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2166 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2167 MultiExprArg(*this, Args, NumArgs),
2168 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002169 if (MemberInit.isInvalid())
2170 return true;
2171
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002172 CheckImplicitConversions(MemberInit.get(),
2173 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002174
2175 // C++0x [class.base.init]p7:
2176 // The initialization of each base and member constitutes a
2177 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002178 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002179 if (MemberInit.isInvalid())
2180 return true;
2181
2182 // If we are in a dependent context, template instantiation will
2183 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002184 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002185 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2186 // of the information that we have about the member
2187 // initializer. However, deconstructing the ASTs is a dicey process,
2188 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002189 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002190 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002191 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002192 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002193 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2194 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002195 }
2196
Chandler Carruth894aed92010-12-06 09:23:57 +00002197 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002198 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2199 InitRange.getBegin(), Init,
2200 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002201 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002202 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2203 InitRange.getBegin(), Init,
2204 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002205 }
Eli Friedman59c04372009-07-29 19:44:27 +00002206}
2207
John McCallf312b1e2010-08-26 23:41:50 +00002208MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002209Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002210 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002211 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002212 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002213 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002214 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002215 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002216
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002217 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002218 // Initialize the object.
2219 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2220 QualType(ClassDecl->getTypeForDecl(), 0));
2221 InitializationKind Kind =
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002222 InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2223 InitRange.getEnd());
Sean Hunt41717662011-02-26 19:13:13 +00002224
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002225 Expr **Args = &Init;
2226 unsigned NumArgs = 1;
2227 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2228 Args = ParenList->getExprs();
2229 NumArgs = ParenList->getNumExprs();
2230 }
2231 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2232 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2233 MultiExprArg(*this, Args,NumArgs),
2234 0);
Sean Hunt41717662011-02-26 19:13:13 +00002235 if (DelegationInit.isInvalid())
2236 return true;
2237
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002238 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2239 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002240
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002241 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002242
2243 // C++0x [class.base.init]p7:
2244 // The initialization of each base and member constitutes a
2245 // full-expression.
2246 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2247 if (DelegationInit.isInvalid())
2248 return true;
2249
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002250 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002251 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002252 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002253}
2254
2255MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002256Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002257 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002259 SourceLocation BaseLoc
2260 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002261
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002262 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2263 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2264 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2265
2266 // C++ [class.base.init]p2:
2267 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002268 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002269 // of that class, the mem-initializer is ill-formed. A
2270 // mem-initializer-list can initialize a base class using any
2271 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002272 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002273
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002274 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002275 if (EllipsisLoc.isValid()) {
2276 // This is a pack expansion.
2277 if (!BaseType->containsUnexpandedParameterPack()) {
2278 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002279 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002280
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002281 EllipsisLoc = SourceLocation();
2282 }
2283 } else {
2284 // Check for any unexpanded parameter packs.
2285 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2286 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002287
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002288 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002289 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002290 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002291
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002292 // Check for direct and virtual base classes.
2293 const CXXBaseSpecifier *DirectBaseSpec = 0;
2294 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2295 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002296 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2297 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002298 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002299
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002300 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2301 VirtualBaseSpec);
2302
2303 // C++ [base.class.init]p2:
2304 // Unless the mem-initializer-id names a nonstatic data member of the
2305 // constructor's class or a direct or virtual base of that class, the
2306 // mem-initializer is ill-formed.
2307 if (!DirectBaseSpec && !VirtualBaseSpec) {
2308 // If the class has any dependent bases, then it's possible that
2309 // one of those types will resolve to the same type as
2310 // BaseType. Therefore, just treat this as a dependent base
2311 // class initialization. FIXME: Should we try to check the
2312 // initialization anyway? It seems odd.
2313 if (ClassDecl->hasAnyDependentBases())
2314 Dependent = true;
2315 else
2316 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2317 << BaseType << Context.getTypeDeclType(ClassDecl)
2318 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2319 }
2320 }
2321
2322 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002323 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Sebastian Redl6df65482011-09-24 17:48:25 +00002325 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2326 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002327 InitRange.getBegin(), Init,
2328 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002329 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002330
2331 // C++ [base.class.init]p2:
2332 // If a mem-initializer-id is ambiguous because it designates both
2333 // a direct non-virtual base class and an inherited virtual base
2334 // class, the mem-initializer is ill-formed.
2335 if (DirectBaseSpec && VirtualBaseSpec)
2336 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002337 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002338
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002339 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002340 if (!BaseSpec)
2341 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2342
2343 // Initialize the base.
2344 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002345 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002346 InitializationKind Kind =
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002347 InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2348 InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002349
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350 Expr **Args = &Init;
2351 unsigned NumArgs = 1;
2352 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2353 Args = ParenList->getExprs();
2354 NumArgs = ParenList->getNumExprs();
2355 }
2356 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2357 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2358 MultiExprArg(*this, Args, NumArgs),
2359 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002360 if (BaseInit.isInvalid())
2361 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002362
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002363 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002364
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002365 // C++0x [class.base.init]p7:
2366 // The initialization of each base and member constitutes a
2367 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002368 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002369 if (BaseInit.isInvalid())
2370 return true;
2371
2372 // If we are in a dependent context, template instantiation will
2373 // perform this type-checking again. Just save the arguments that we
2374 // received in a ParenListExpr.
2375 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2376 // of the information that we have about the base
2377 // initializer. However, deconstructing the ASTs is a dicey process,
2378 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002379 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002380 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002381
Sean Huntcbb67482011-01-08 20:30:50 +00002382 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002383 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002384 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002385 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002386 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002387}
2388
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002389// Create a static_cast\<T&&>(expr).
2390static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2391 QualType ExprType = E->getType();
2392 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2393 SourceLocation ExprLoc = E->getLocStart();
2394 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2395 TargetType, ExprLoc);
2396
2397 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2398 SourceRange(ExprLoc, ExprLoc),
2399 E->getSourceRange()).take();
2400}
2401
Anders Carlssone5ef7402010-04-23 03:10:23 +00002402/// ImplicitInitializerKind - How an implicit base or member initializer should
2403/// initialize its base or member.
2404enum ImplicitInitializerKind {
2405 IIK_Default,
2406 IIK_Copy,
2407 IIK_Move
2408};
2409
Anders Carlssondefefd22010-04-23 02:00:02 +00002410static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002411BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002412 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002413 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002414 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002415 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002416 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002417 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2418 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002419
John McCall60d7b3a2010-08-24 06:29:42 +00002420 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002421
2422 switch (ImplicitInitKind) {
2423 case IIK_Default: {
2424 InitializationKind InitKind
2425 = InitializationKind::CreateDefault(Constructor->getLocation());
2426 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2427 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002428 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002429 break;
2430 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002432 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002433 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002434 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002435 ParmVarDecl *Param = Constructor->getParamDecl(0);
2436 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002437
Anders Carlssone5ef7402010-04-23 03:10:23 +00002438 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002439 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2440 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002441 Constructor->getLocation(), ParamType,
2442 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002443
Eli Friedman5f2987c2012-02-02 03:46:19 +00002444 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2445
Anders Carlssonc7957502010-04-24 22:02:54 +00002446 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002447 QualType ArgTy =
2448 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2449 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002451 if (Moving) {
2452 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2453 }
2454
John McCallf871d0c2010-08-07 06:22:56 +00002455 CXXCastPath BasePath;
2456 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002457 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2458 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002459 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002460 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002461
Anders Carlssone5ef7402010-04-23 03:10:23 +00002462 InitializationKind InitKind
2463 = InitializationKind::CreateDirect(Constructor->getLocation(),
2464 SourceLocation(), SourceLocation());
2465 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2466 &CopyCtorArg, 1);
2467 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002468 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002469 break;
2470 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002471 }
John McCall9ae2f072010-08-23 23:25:46 +00002472
Douglas Gregor53c374f2010-12-07 00:41:46 +00002473 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002474 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002475 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002476
Anders Carlssondefefd22010-04-23 02:00:02 +00002477 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002478 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002479 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2480 SourceLocation()),
2481 BaseSpec->isVirtual(),
2482 SourceLocation(),
2483 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002484 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002485 SourceLocation());
2486
Anders Carlssondefefd22010-04-23 02:00:02 +00002487 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002488}
2489
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002490static bool RefersToRValueRef(Expr *MemRef) {
2491 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2492 return Referenced->getType()->isRValueReferenceType();
2493}
2494
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002495static bool
2496BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002497 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002498 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002499 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002500 if (Field->isInvalidDecl())
2501 return true;
2502
Chandler Carruthf186b542010-06-29 23:50:44 +00002503 SourceLocation Loc = Constructor->getLocation();
2504
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002505 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2506 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002507 ParmVarDecl *Param = Constructor->getParamDecl(0);
2508 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002509
2510 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002511 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2512 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002513
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002514 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002515 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2516 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002517 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002518
Eli Friedman5f2987c2012-02-02 03:46:19 +00002519 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2520
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002521 if (Moving) {
2522 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2523 }
2524
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002525 // Build a reference to this field within the parameter.
2526 CXXScopeSpec SS;
2527 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2528 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002529 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2530 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002531 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002532 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002533 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002534 ParamType, Loc,
2535 /*IsArrow=*/false,
2536 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002537 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 /*FirstQualifierInScope=*/0,
2539 MemberLookup,
2540 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002541 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002542 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002543
2544 // C++11 [class.copy]p15:
2545 // - if a member m has rvalue reference type T&&, it is direct-initialized
2546 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002547 if (RefersToRValueRef(CtorArg.get())) {
2548 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002549 }
2550
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002551 // When the field we are copying is an array, create index variables for
2552 // each dimension of the array. We use these index variables to subscript
2553 // the source array, and other clients (e.g., CodeGen) will perform the
2554 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002555 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002556 QualType BaseType = Field->getType();
2557 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002558 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002559 while (const ConstantArrayType *Array
2560 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002561 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002562 // Create the iteration variable for this array index.
2563 IdentifierInfo *IterationVarName = 0;
2564 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002565 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 llvm::raw_svector_ostream OS(Str);
2567 OS << "__i" << IndexVariables.size();
2568 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2569 }
2570 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002571 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 IterationVarName, SizeType,
2573 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002574 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002575 IndexVariables.push_back(IterationVar);
2576
2577 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002578 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002579 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002580 assert(!IterationVarRef.isInvalid() &&
2581 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002582 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2583 assert(!IterationVarRef.isInvalid() &&
2584 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002585
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002586 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002587 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002588 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002589 Loc);
2590 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002591 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002592
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002593 BaseType = Array->getElementType();
2594 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002595
2596 // The array subscript expression is an lvalue, which is wrong for moving.
2597 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002598 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002599
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002600 // Construct the entity that we will be initializing. For an array, this
2601 // will be first element in the array, which may require several levels
2602 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002603 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002604 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002605 if (Indirect)
2606 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2607 else
2608 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002609 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2610 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2611 0,
2612 Entities.back()));
2613
2614 // Direct-initialize to use the copy constructor.
2615 InitializationKind InitKind =
2616 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2617
Sebastian Redl74e611a2011-09-04 18:14:28 +00002618 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002619 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002620 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002621
John McCall60d7b3a2010-08-24 06:29:42 +00002622 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002623 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002624 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002626 if (MemberInit.isInvalid())
2627 return true;
2628
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002629 if (Indirect) {
2630 assert(IndexVariables.size() == 0 &&
2631 "Indirect field improperly initialized");
2632 CXXMemberInit
2633 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2634 Loc, Loc,
2635 MemberInit.takeAs<Expr>(),
2636 Loc);
2637 } else
2638 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2639 Loc, MemberInit.takeAs<Expr>(),
2640 Loc,
2641 IndexVariables.data(),
2642 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002643 return false;
2644 }
2645
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002646 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2647
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002648 QualType FieldBaseElementType =
2649 SemaRef.Context.getBaseElementType(Field->getType());
2650
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002651 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002652 InitializedEntity InitEntity
2653 = Indirect? InitializedEntity::InitializeMember(Indirect)
2654 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002655 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002656 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002657
2658 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002659 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002660 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002661
Douglas Gregor53c374f2010-12-07 00:41:46 +00002662 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002663 if (MemberInit.isInvalid())
2664 return true;
2665
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002666 if (Indirect)
2667 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2668 Indirect, Loc,
2669 Loc,
2670 MemberInit.get(),
2671 Loc);
2672 else
2673 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2674 Field, Loc, Loc,
2675 MemberInit.get(),
2676 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002677 return false;
2678 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002679
Sean Hunt1f2f3842011-05-17 00:19:05 +00002680 if (!Field->getParent()->isUnion()) {
2681 if (FieldBaseElementType->isReferenceType()) {
2682 SemaRef.Diag(Constructor->getLocation(),
2683 diag::err_uninitialized_member_in_ctor)
2684 << (int)Constructor->isImplicit()
2685 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2686 << 0 << Field->getDeclName();
2687 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2688 return true;
2689 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002690
Sean Hunt1f2f3842011-05-17 00:19:05 +00002691 if (FieldBaseElementType.isConstQualified()) {
2692 SemaRef.Diag(Constructor->getLocation(),
2693 diag::err_uninitialized_member_in_ctor)
2694 << (int)Constructor->isImplicit()
2695 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2696 << 1 << Field->getDeclName();
2697 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2698 return true;
2699 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002700 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002701
John McCallf85e1932011-06-15 23:02:42 +00002702 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2703 FieldBaseElementType->isObjCRetainableType() &&
2704 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2705 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2706 // Instant objects:
2707 // Default-initialize Objective-C pointers to NULL.
2708 CXXMemberInit
2709 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2710 Loc, Loc,
2711 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2712 Loc);
2713 return false;
2714 }
2715
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002716 // Nothing to initialize.
2717 CXXMemberInit = 0;
2718 return false;
2719}
John McCallf1860e52010-05-20 23:23:51 +00002720
2721namespace {
2722struct BaseAndFieldInfo {
2723 Sema &S;
2724 CXXConstructorDecl *Ctor;
2725 bool AnyErrorsInInits;
2726 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002727 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002728 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002729
2730 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2731 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002732 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2733 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002734 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002735 else if (Generated && Ctor->isMoveConstructor())
2736 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002737 else
2738 IIK = IIK_Default;
2739 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002740
2741 bool isImplicitCopyOrMove() const {
2742 switch (IIK) {
2743 case IIK_Copy:
2744 case IIK_Move:
2745 return true;
2746
2747 case IIK_Default:
2748 return false;
2749 }
David Blaikie30263482012-01-20 21:50:17 +00002750
2751 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002752 }
John McCallf1860e52010-05-20 23:23:51 +00002753};
2754}
2755
Richard Smitha4950662011-09-19 13:34:43 +00002756/// \brief Determine whether the given indirect field declaration is somewhere
2757/// within an anonymous union.
2758static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2759 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2760 CEnd = F->chain_end();
2761 C != CEnd; ++C)
2762 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2763 if (Record->isUnion())
2764 return true;
2765
2766 return false;
2767}
2768
Douglas Gregorddb21472011-11-02 23:04:16 +00002769/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2770/// array type.
2771static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2772 if (T->isIncompleteArrayType())
2773 return true;
2774
2775 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2776 if (!ArrayT->getSize())
2777 return true;
2778
2779 T = ArrayT->getElementType();
2780 }
2781
2782 return false;
2783}
2784
Richard Smith7a614d82011-06-11 17:19:42 +00002785static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002786 FieldDecl *Field,
2787 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002788
Chandler Carruthe861c602010-06-30 02:59:29 +00002789 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002790 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002791 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002792 return false;
2793 }
2794
Richard Smith7a614d82011-06-11 17:19:42 +00002795 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2796 // has a brace-or-equal-initializer, the entity is initialized as specified
2797 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002798 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002799 CXXCtorInitializer *Init;
2800 if (Indirect)
2801 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2802 SourceLocation(),
2803 SourceLocation(), 0,
2804 SourceLocation());
2805 else
2806 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2807 SourceLocation(),
2808 SourceLocation(), 0,
2809 SourceLocation());
2810 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002811 return false;
2812 }
2813
Richard Smithc115f632011-09-18 11:14:50 +00002814 // Don't build an implicit initializer for union members if none was
2815 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002816 if (Field->getParent()->isUnion() ||
2817 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002818 return false;
2819
Douglas Gregorddb21472011-11-02 23:04:16 +00002820 // Don't initialize incomplete or zero-length arrays.
2821 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2822 return false;
2823
John McCallf1860e52010-05-20 23:23:51 +00002824 // Don't try to build an implicit initializer if there were semantic
2825 // errors in any of the initializers (and therefore we might be
2826 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002827 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002828 return false;
2829
Sean Huntcbb67482011-01-08 20:30:50 +00002830 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002831 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2832 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002833 return true;
John McCallf1860e52010-05-20 23:23:51 +00002834
Francois Pichet00eb3f92010-12-04 09:14:42 +00002835 if (Init)
2836 Info.AllToInit.push_back(Init);
2837
John McCallf1860e52010-05-20 23:23:51 +00002838 return false;
2839}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002840
2841bool
2842Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2843 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002844 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002845 Constructor->setNumCtorInitializers(1);
2846 CXXCtorInitializer **initializer =
2847 new (Context) CXXCtorInitializer*[1];
2848 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2849 Constructor->setCtorInitializers(initializer);
2850
Sean Huntb76af9c2011-05-03 23:05:34 +00002851 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002852 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002853 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2854 }
2855
Sean Huntc1598702011-05-05 00:05:47 +00002856 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002857
Sean Hunt059ce0d2011-05-01 07:04:31 +00002858 return false;
2859}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002860
John McCallb77115d2011-06-17 00:18:42 +00002861bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2862 CXXCtorInitializer **Initializers,
2863 unsigned NumInitializers,
2864 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002865 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002866 // Just store the initializers as written, they will be checked during
2867 // instantiation.
2868 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002869 Constructor->setNumCtorInitializers(NumInitializers);
2870 CXXCtorInitializer **baseOrMemberInitializers =
2871 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002872 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002873 NumInitializers * sizeof(CXXCtorInitializer*));
2874 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002875 }
2876
2877 return false;
2878 }
2879
John McCallf1860e52010-05-20 23:23:51 +00002880 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002881
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002882 // We need to build the initializer AST according to order of construction
2883 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002884 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002885 if (!ClassDecl)
2886 return true;
2887
Eli Friedman80c30da2009-11-09 19:20:36 +00002888 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002890 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002891 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002892
2893 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002894 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002895 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002896 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002897 }
2898
Anders Carlsson711f34a2010-04-21 19:52:01 +00002899 // Keep track of the direct virtual bases.
2900 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2901 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2902 E = ClassDecl->bases_end(); I != E; ++I) {
2903 if (I->isVirtual())
2904 DirectVBases.insert(I);
2905 }
2906
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 // Push virtual bases before others.
2908 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2909 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2910
Sean Huntcbb67482011-01-08 20:30:50 +00002911 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002912 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2913 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002914 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002915 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002916 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002917 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002918 VBase, IsInheritedVirtualBase,
2919 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002920 HadError = true;
2921 continue;
2922 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002923
John McCallf1860e52010-05-20 23:23:51 +00002924 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002925 }
2926 }
Mike Stump1eb44332009-09-09 15:08:12 +00002927
John McCallf1860e52010-05-20 23:23:51 +00002928 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002929 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2930 E = ClassDecl->bases_end(); Base != E; ++Base) {
2931 // Virtuals are in the virtual base list and already constructed.
2932 if (Base->isVirtual())
2933 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Sean Huntcbb67482011-01-08 20:30:50 +00002935 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002936 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2937 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002938 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002939 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002940 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002941 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002942 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002943 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002944 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002945 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002946
John McCallf1860e52010-05-20 23:23:51 +00002947 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002948 }
2949 }
Mike Stump1eb44332009-09-09 15:08:12 +00002950
John McCallf1860e52010-05-20 23:23:51 +00002951 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002952 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2953 MemEnd = ClassDecl->decls_end();
2954 Mem != MemEnd; ++Mem) {
2955 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002956 // C++ [class.bit]p2:
2957 // A declaration for a bit-field that omits the identifier declares an
2958 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2959 // initialized.
2960 if (F->isUnnamedBitfield())
2961 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002962
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002963 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002964 // handle anonymous struct/union fields based on their individual
2965 // indirect fields.
2966 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2967 continue;
2968
2969 if (CollectFieldInitializer(*this, Info, F))
2970 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002971 continue;
2972 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002973
2974 // Beyond this point, we only consider default initialization.
2975 if (Info.IIK != IIK_Default)
2976 continue;
2977
2978 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2979 if (F->getType()->isIncompleteArrayType()) {
2980 assert(ClassDecl->hasFlexibleArrayMember() &&
2981 "Incomplete array type is not valid");
2982 continue;
2983 }
2984
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002985 // Initialize each field of an anonymous struct individually.
2986 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2987 HadError = true;
2988
2989 continue;
2990 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992
John McCallf1860e52010-05-20 23:23:51 +00002993 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002994 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002995 Constructor->setNumCtorInitializers(NumInitializers);
2996 CXXCtorInitializer **baseOrMemberInitializers =
2997 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002998 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002999 NumInitializers * sizeof(CXXCtorInitializer*));
3000 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003001
John McCallef027fe2010-03-16 21:39:52 +00003002 // Constructors implicitly reference the base and member
3003 // destructors.
3004 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3005 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003006 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003007
3008 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003009}
3010
Eli Friedman6347f422009-07-21 19:28:10 +00003011static void *GetKeyForTopLevelField(FieldDecl *Field) {
3012 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003013 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003014 if (RT->getDecl()->isAnonymousStructOrUnion())
3015 return static_cast<void *>(RT->getDecl());
3016 }
3017 return static_cast<void *>(Field);
3018}
3019
Anders Carlssonea356fb2010-04-02 05:42:15 +00003020static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003021 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003022}
3023
Anders Carlssonea356fb2010-04-02 05:42:15 +00003024static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003025 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003026 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003027 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003028
Eli Friedman6347f422009-07-21 19:28:10 +00003029 // For fields injected into the class via declaration of an anonymous union,
3030 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003031 FieldDecl *Field = Member->getAnyMember();
3032
John McCall3c3ccdb2010-04-10 09:28:51 +00003033 // If the field is a member of an anonymous struct or union, our key
3034 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003035 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003036 if (RD->isAnonymousStructOrUnion()) {
3037 while (true) {
3038 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3039 if (Parent->isAnonymousStructOrUnion())
3040 RD = Parent;
3041 else
3042 break;
3043 }
3044
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003045 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003046 }
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003048 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003049}
3050
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003051static void
3052DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003053 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003054 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003055 unsigned NumInits) {
3056 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003057 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003059 // Don't check initializers order unless the warning is enabled at the
3060 // location of at least one initializer.
3061 bool ShouldCheckOrder = false;
3062 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003063 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003064 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3065 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003066 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003067 ShouldCheckOrder = true;
3068 break;
3069 }
3070 }
3071 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003072 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003073
John McCalld6ca8da2010-04-10 07:37:23 +00003074 // Build the list of bases and members in the order that they'll
3075 // actually be initialized. The explicit initializers should be in
3076 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003077 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Anders Carlsson071d6102010-04-02 03:38:04 +00003079 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3080
John McCalld6ca8da2010-04-10 07:37:23 +00003081 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003082 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003083 ClassDecl->vbases_begin(),
3084 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003085 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003086
John McCalld6ca8da2010-04-10 07:37:23 +00003087 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003088 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003089 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003090 if (Base->isVirtual())
3091 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003092 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003093 }
Mike Stump1eb44332009-09-09 15:08:12 +00003094
John McCalld6ca8da2010-04-10 07:37:23 +00003095 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003096 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003097 E = ClassDecl->field_end(); Field != E; ++Field) {
3098 if (Field->isUnnamedBitfield())
3099 continue;
3100
John McCalld6ca8da2010-04-10 07:37:23 +00003101 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003102 }
3103
John McCalld6ca8da2010-04-10 07:37:23 +00003104 unsigned NumIdealInits = IdealInitKeys.size();
3105 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003106
Sean Huntcbb67482011-01-08 20:30:50 +00003107 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003108 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003109 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003110 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003111
3112 // Scan forward to try to find this initializer in the idealized
3113 // initializers list.
3114 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3115 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003116 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003117
3118 // If we didn't find this initializer, it must be because we
3119 // scanned past it on a previous iteration. That can only
3120 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003121 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003122 Sema::SemaDiagnosticBuilder D =
3123 SemaRef.Diag(PrevInit->getSourceLocation(),
3124 diag::warn_initializer_out_of_order);
3125
Francois Pichet00eb3f92010-12-04 09:14:42 +00003126 if (PrevInit->isAnyMemberInitializer())
3127 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003128 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003129 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003130
Francois Pichet00eb3f92010-12-04 09:14:42 +00003131 if (Init->isAnyMemberInitializer())
3132 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003133 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003134 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003135
3136 // Move back to the initializer's location in the ideal list.
3137 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3138 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003139 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003140
3141 assert(IdealIndex != NumIdealInits &&
3142 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003143 }
John McCalld6ca8da2010-04-10 07:37:23 +00003144
3145 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003146 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003147}
3148
John McCall3c3ccdb2010-04-10 09:28:51 +00003149namespace {
3150bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003151 CXXCtorInitializer *Init,
3152 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003153 if (!PrevInit) {
3154 PrevInit = Init;
3155 return false;
3156 }
3157
3158 if (FieldDecl *Field = Init->getMember())
3159 S.Diag(Init->getSourceLocation(),
3160 diag::err_multiple_mem_initialization)
3161 << Field->getDeclName()
3162 << Init->getSourceRange();
3163 else {
John McCallf4c73712011-01-19 06:33:43 +00003164 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003165 assert(BaseClass && "neither field nor base");
3166 S.Diag(Init->getSourceLocation(),
3167 diag::err_multiple_base_initialization)
3168 << QualType(BaseClass, 0)
3169 << Init->getSourceRange();
3170 }
3171 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3172 << 0 << PrevInit->getSourceRange();
3173
3174 return true;
3175}
3176
Sean Huntcbb67482011-01-08 20:30:50 +00003177typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003178typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3179
3180bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003181 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003182 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003183 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003184 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003185 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003186
3187 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003188 if (Parent->isUnion()) {
3189 UnionEntry &En = Unions[Parent];
3190 if (En.first && En.first != Child) {
3191 S.Diag(Init->getSourceLocation(),
3192 diag::err_multiple_mem_union_initialization)
3193 << Field->getDeclName()
3194 << Init->getSourceRange();
3195 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3196 << 0 << En.second->getSourceRange();
3197 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003198 }
3199 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003200 En.first = Child;
3201 En.second = Init;
3202 }
David Blaikie6fe29652011-11-17 06:01:57 +00003203 if (!Parent->isAnonymousStructOrUnion())
3204 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003205 }
3206
3207 Child = Parent;
3208 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003209 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003210
3211 return false;
3212}
3213}
3214
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003215/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003216void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003217 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003218 CXXCtorInitializer **meminits,
3219 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003220 bool AnyErrors) {
3221 if (!ConstructorDecl)
3222 return;
3223
3224 AdjustDeclIfTemplate(ConstructorDecl);
3225
3226 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003227 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003228
3229 if (!Constructor) {
3230 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3231 return;
3232 }
3233
Sean Huntcbb67482011-01-08 20:30:50 +00003234 CXXCtorInitializer **MemInits =
3235 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003236
3237 // Mapping for the duplicate initializers check.
3238 // For member initializers, this is keyed with a FieldDecl*.
3239 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003240 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003241
3242 // Mapping for the inconsistent anonymous-union initializers check.
3243 RedundantUnionMap MemberUnions;
3244
Anders Carlssonea356fb2010-04-02 05:42:15 +00003245 bool HadError = false;
3246 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003247 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003248
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003249 // Set the source order index.
3250 Init->setSourceOrder(i);
3251
Francois Pichet00eb3f92010-12-04 09:14:42 +00003252 if (Init->isAnyMemberInitializer()) {
3253 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003254 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3255 CheckRedundantUnionInit(*this, Init, MemberUnions))
3256 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003257 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003258 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3259 if (CheckRedundantInit(*this, Init, Members[Key]))
3260 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003261 } else {
3262 assert(Init->isDelegatingInitializer());
3263 // This must be the only initializer
3264 if (i != 0 || NumMemInits > 1) {
3265 Diag(MemInits[0]->getSourceLocation(),
3266 diag::err_delegating_initializer_alone)
3267 << MemInits[0]->getSourceRange();
3268 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003269 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003270 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003271 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003272 // Return immediately as the initializer is set.
3273 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003274 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003275 }
3276
Anders Carlssonea356fb2010-04-02 05:42:15 +00003277 if (HadError)
3278 return;
3279
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003280 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003281
Sean Huntcbb67482011-01-08 20:30:50 +00003282 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003283}
3284
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003285void
John McCallef027fe2010-03-16 21:39:52 +00003286Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3287 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003288 // Ignore dependent contexts. Also ignore unions, since their members never
3289 // have destructors implicitly called.
3290 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003291 return;
John McCall58e6f342010-03-16 05:22:47 +00003292
3293 // FIXME: all the access-control diagnostics are positioned on the
3294 // field/base declaration. That's probably good; that said, the
3295 // user might reasonably want to know why the destructor is being
3296 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003297
Anders Carlsson9f853df2009-11-17 04:44:12 +00003298 // Non-static data members.
3299 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3300 E = ClassDecl->field_end(); I != E; ++I) {
3301 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003302 if (Field->isInvalidDecl())
3303 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003304
3305 // Don't destroy incomplete or zero-length arrays.
3306 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3307 continue;
3308
Anders Carlsson9f853df2009-11-17 04:44:12 +00003309 QualType FieldType = Context.getBaseElementType(Field->getType());
3310
3311 const RecordType* RT = FieldType->getAs<RecordType>();
3312 if (!RT)
3313 continue;
3314
3315 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003316 if (FieldClassDecl->isInvalidDecl())
3317 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003318 if (FieldClassDecl->hasTrivialDestructor())
3319 continue;
3320
Douglas Gregordb89f282010-07-01 22:47:18 +00003321 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003322 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003323 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003324 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003325 << Field->getDeclName()
3326 << FieldType);
3327
Eli Friedman5f2987c2012-02-02 03:46:19 +00003328 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003329 }
3330
John McCall58e6f342010-03-16 05:22:47 +00003331 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3332
Anders Carlsson9f853df2009-11-17 04:44:12 +00003333 // Bases.
3334 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3335 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003336 // Bases are always records in a well-formed non-dependent class.
3337 const RecordType *RT = Base->getType()->getAs<RecordType>();
3338
3339 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003340 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003341 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003342
John McCall58e6f342010-03-16 05:22:47 +00003343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003344 // If our base class is invalid, we probably can't get its dtor anyway.
3345 if (BaseClassDecl->isInvalidDecl())
3346 continue;
3347 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003348 if (BaseClassDecl->hasTrivialDestructor())
3349 continue;
John McCall58e6f342010-03-16 05:22:47 +00003350
Douglas Gregordb89f282010-07-01 22:47:18 +00003351 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003352 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003353
3354 // FIXME: caret should be on the start of the class name
3355 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003356 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003357 << Base->getType()
3358 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003359
Eli Friedman5f2987c2012-02-02 03:46:19 +00003360 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003361 }
3362
3363 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003364 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003366
3367 // Bases are always records in a well-formed non-dependent class.
3368 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3369
3370 // Ignore direct virtual bases.
3371 if (DirectVirtualBases.count(RT))
3372 continue;
3373
John McCall58e6f342010-03-16 05:22:47 +00003374 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003375 // If our base class is invalid, we probably can't get its dtor anyway.
3376 if (BaseClassDecl->isInvalidDecl())
3377 continue;
3378 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003379 if (BaseClassDecl->hasTrivialDestructor())
3380 continue;
John McCall58e6f342010-03-16 05:22:47 +00003381
Douglas Gregordb89f282010-07-01 22:47:18 +00003382 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003383 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003384 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003385 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003386 << VBase->getType());
3387
Eli Friedman5f2987c2012-02-02 03:46:19 +00003388 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003389 }
3390}
3391
John McCalld226f652010-08-21 09:40:31 +00003392void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003393 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003394 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Mike Stump1eb44332009-09-09 15:08:12 +00003396 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003397 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003398 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003399}
3400
Mike Stump1eb44332009-09-09 15:08:12 +00003401bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003402 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003403 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003404 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003405 else
John McCall94c3b562010-08-18 09:41:07 +00003406 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003407}
3408
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003409bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003410 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003411 if (!getLangOptions().CPlusPlus)
3412 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Anders Carlsson11f21a02009-03-23 19:10:31 +00003414 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003415 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Ted Kremenek6217b802009-07-29 21:53:49 +00003417 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003418 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003419 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003420 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003422 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003423 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003424 }
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Ted Kremenek6217b802009-07-29 21:53:49 +00003426 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003427 if (!RT)
3428 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
John McCall86ff3082010-02-04 22:26:26 +00003430 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003431
John McCall94c3b562010-08-18 09:41:07 +00003432 // We can't answer whether something is abstract until it has a
3433 // definition. If it's currently being defined, we'll walk back
3434 // over all the declarations when we have a full definition.
3435 const CXXRecordDecl *Def = RD->getDefinition();
3436 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003437 return false;
3438
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003439 if (!RD->isAbstract())
3440 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003442 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003443 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003444
John McCall94c3b562010-08-18 09:41:07 +00003445 return true;
3446}
3447
3448void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3449 // Check if we've already emitted the list of pure virtual functions
3450 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003451 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003452 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003454 CXXFinalOverriderMap FinalOverriders;
3455 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003456
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003457 // Keep a set of seen pure methods so we won't diagnose the same method
3458 // more than once.
3459 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3460
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003461 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3462 MEnd = FinalOverriders.end();
3463 M != MEnd;
3464 ++M) {
3465 for (OverridingMethods::iterator SO = M->second.begin(),
3466 SOEnd = M->second.end();
3467 SO != SOEnd; ++SO) {
3468 // C++ [class.abstract]p4:
3469 // A class is abstract if it contains or inherits at least one
3470 // pure virtual function for which the final overrider is pure
3471 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003473 //
3474 if (SO->second.size() != 1)
3475 continue;
3476
3477 if (!SO->second.front().Method->isPure())
3478 continue;
3479
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003480 if (!SeenPureMethods.insert(SO->second.front().Method))
3481 continue;
3482
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003483 Diag(SO->second.front().Method->getLocation(),
3484 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003485 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003486 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003487 }
3488
3489 if (!PureVirtualClassDiagSet)
3490 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3491 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003492}
3493
Anders Carlsson8211eff2009-03-24 01:19:16 +00003494namespace {
John McCall94c3b562010-08-18 09:41:07 +00003495struct AbstractUsageInfo {
3496 Sema &S;
3497 CXXRecordDecl *Record;
3498 CanQualType AbstractType;
3499 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003500
John McCall94c3b562010-08-18 09:41:07 +00003501 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3502 : S(S), Record(Record),
3503 AbstractType(S.Context.getCanonicalType(
3504 S.Context.getTypeDeclType(Record))),
3505 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003506
John McCall94c3b562010-08-18 09:41:07 +00003507 void DiagnoseAbstractType() {
3508 if (Invalid) return;
3509 S.DiagnoseAbstractType(Record);
3510 Invalid = true;
3511 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003512
John McCall94c3b562010-08-18 09:41:07 +00003513 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3514};
3515
3516struct CheckAbstractUsage {
3517 AbstractUsageInfo &Info;
3518 const NamedDecl *Ctx;
3519
3520 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3521 : Info(Info), Ctx(Ctx) {}
3522
3523 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3524 switch (TL.getTypeLocClass()) {
3525#define ABSTRACT_TYPELOC(CLASS, PARENT)
3526#define TYPELOC(CLASS, PARENT) \
3527 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3528#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003529 }
John McCall94c3b562010-08-18 09:41:07 +00003530 }
Mike Stump1eb44332009-09-09 15:08:12 +00003531
John McCall94c3b562010-08-18 09:41:07 +00003532 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3533 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3534 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003535 if (!TL.getArg(I))
3536 continue;
3537
John McCall94c3b562010-08-18 09:41:07 +00003538 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3539 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003540 }
John McCall94c3b562010-08-18 09:41:07 +00003541 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003542
John McCall94c3b562010-08-18 09:41:07 +00003543 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3544 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
John McCall94c3b562010-08-18 09:41:07 +00003547 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3548 // Visit the type parameters from a permissive context.
3549 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3550 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3551 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3552 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3553 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3554 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003555 }
John McCall94c3b562010-08-18 09:41:07 +00003556 }
Mike Stump1eb44332009-09-09 15:08:12 +00003557
John McCall94c3b562010-08-18 09:41:07 +00003558 // Visit pointee types from a permissive context.
3559#define CheckPolymorphic(Type) \
3560 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3561 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3562 }
3563 CheckPolymorphic(PointerTypeLoc)
3564 CheckPolymorphic(ReferenceTypeLoc)
3565 CheckPolymorphic(MemberPointerTypeLoc)
3566 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003567 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003568
John McCall94c3b562010-08-18 09:41:07 +00003569 /// Handle all the types we haven't given a more specific
3570 /// implementation for above.
3571 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3572 // Every other kind of type that we haven't called out already
3573 // that has an inner type is either (1) sugar or (2) contains that
3574 // inner type in some way as a subobject.
3575 if (TypeLoc Next = TL.getNextTypeLoc())
3576 return Visit(Next, Sel);
3577
3578 // If there's no inner type and we're in a permissive context,
3579 // don't diagnose.
3580 if (Sel == Sema::AbstractNone) return;
3581
3582 // Check whether the type matches the abstract type.
3583 QualType T = TL.getType();
3584 if (T->isArrayType()) {
3585 Sel = Sema::AbstractArrayType;
3586 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003587 }
John McCall94c3b562010-08-18 09:41:07 +00003588 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3589 if (CT != Info.AbstractType) return;
3590
3591 // It matched; do some magic.
3592 if (Sel == Sema::AbstractArrayType) {
3593 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3594 << T << TL.getSourceRange();
3595 } else {
3596 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3597 << Sel << T << TL.getSourceRange();
3598 }
3599 Info.DiagnoseAbstractType();
3600 }
3601};
3602
3603void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3604 Sema::AbstractDiagSelID Sel) {
3605 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3606}
3607
3608}
3609
3610/// Check for invalid uses of an abstract type in a method declaration.
3611static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3612 CXXMethodDecl *MD) {
3613 // No need to do the check on definitions, which require that
3614 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003615 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003616 return;
3617
3618 // For safety's sake, just ignore it if we don't have type source
3619 // information. This should never happen for non-implicit methods,
3620 // but...
3621 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3622 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3623}
3624
3625/// Check for invalid uses of an abstract type within a class definition.
3626static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3627 CXXRecordDecl *RD) {
3628 for (CXXRecordDecl::decl_iterator
3629 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3630 Decl *D = *I;
3631 if (D->isImplicit()) continue;
3632
3633 // Methods and method templates.
3634 if (isa<CXXMethodDecl>(D)) {
3635 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3636 } else if (isa<FunctionTemplateDecl>(D)) {
3637 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3638 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3639
3640 // Fields and static variables.
3641 } else if (isa<FieldDecl>(D)) {
3642 FieldDecl *FD = cast<FieldDecl>(D);
3643 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3644 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3645 } else if (isa<VarDecl>(D)) {
3646 VarDecl *VD = cast<VarDecl>(D);
3647 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3648 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3649
3650 // Nested classes and class templates.
3651 } else if (isa<CXXRecordDecl>(D)) {
3652 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3653 } else if (isa<ClassTemplateDecl>(D)) {
3654 CheckAbstractClassUsage(Info,
3655 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3656 }
3657 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003658}
3659
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003660/// \brief Perform semantic checks on a class definition that has been
3661/// completing, introducing implicitly-declared members, checking for
3662/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003663void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003664 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003665 return;
3666
John McCall94c3b562010-08-18 09:41:07 +00003667 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3668 AbstractUsageInfo Info(*this, Record);
3669 CheckAbstractClassUsage(Info, Record);
3670 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003671
3672 // If this is not an aggregate type and has no user-declared constructor,
3673 // complain about any non-static data members of reference or const scalar
3674 // type, since they will never get initializers.
3675 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003676 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3677 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003678 bool Complained = false;
3679 for (RecordDecl::field_iterator F = Record->field_begin(),
3680 FEnd = Record->field_end();
3681 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003682 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003683 continue;
3684
Douglas Gregor325e5932010-04-15 00:00:53 +00003685 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003686 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003687 if (!Complained) {
3688 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3689 << Record->getTagKind() << Record;
3690 Complained = true;
3691 }
3692
3693 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3694 << F->getType()->isReferenceType()
3695 << F->getDeclName();
3696 }
3697 }
3698 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003699
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003700 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003701 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003702
3703 if (Record->getIdentifier()) {
3704 // C++ [class.mem]p13:
3705 // If T is the name of a class, then each of the following shall have a
3706 // name different from T:
3707 // - every member of every anonymous union that is a member of class T.
3708 //
3709 // C++ [class.mem]p14:
3710 // In addition, if class T has a user-declared constructor (12.1), every
3711 // non-static data member of class T shall have a name different from T.
3712 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003713 R.first != R.second; ++R.first) {
3714 NamedDecl *D = *R.first;
3715 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3716 isa<IndirectFieldDecl>(D)) {
3717 Diag(D->getLocation(), diag::err_member_name_of_class)
3718 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003719 break;
3720 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003721 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003722 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003723
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003724 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003725 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003726 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003727 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003728 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3729 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3730 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003731
3732 // See if a method overloads virtual methods in a base
3733 /// class without overriding any.
3734 if (!Record->isDependentType()) {
3735 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3736 MEnd = Record->method_end();
3737 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003738 if (!(*M)->isStatic())
3739 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003740 }
3741 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003742
Richard Smith9f569cc2011-10-01 02:31:28 +00003743 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3744 // function that is not a constructor declares that member function to be
3745 // const. [...] The class of which that function is a member shall be
3746 // a literal type.
3747 //
3748 // It's fine to diagnose constructors here too: such constructors cannot
3749 // produce a constant expression, so are ill-formed (no diagnostic required).
3750 //
3751 // If the class has virtual bases, any constexpr members will already have
3752 // been diagnosed by the checks performed on the member declaration, so
3753 // suppress this (less useful) diagnostic.
3754 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3755 !Record->isLiteral() && !Record->getNumVBases()) {
3756 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3757 MEnd = Record->method_end();
3758 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003759 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003760 switch (Record->getTemplateSpecializationKind()) {
3761 case TSK_ImplicitInstantiation:
3762 case TSK_ExplicitInstantiationDeclaration:
3763 case TSK_ExplicitInstantiationDefinition:
3764 // If a template instantiates to a non-literal type, but its members
3765 // instantiate to constexpr functions, the template is technically
3766 // ill-formed, but we allow it for sanity. Such members are treated as
3767 // non-constexpr.
3768 (*M)->setConstexpr(false);
3769 continue;
3770
3771 case TSK_Undeclared:
3772 case TSK_ExplicitSpecialization:
3773 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3774 PDiag(diag::err_constexpr_method_non_literal));
3775 break;
3776 }
3777
3778 // Only produce one error per class.
3779 break;
3780 }
3781 }
3782 }
3783
Sebastian Redlf677ea32011-02-05 19:23:19 +00003784 // Declare inherited constructors. We do this eagerly here because:
3785 // - The standard requires an eager diagnostic for conflicting inherited
3786 // constructors from different classes.
3787 // - The lazy declaration of the other implicit constructors is so as to not
3788 // waste space and performance on classes that are not meant to be
3789 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3790 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003791 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003792
Sean Hunteb88ae52011-05-23 21:07:59 +00003793 if (!Record->isDependentType())
3794 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003795}
3796
3797void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003798 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3799 ME = Record->method_end();
3800 MI != ME; ++MI) {
3801 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3802 switch (getSpecialMember(*MI)) {
3803 case CXXDefaultConstructor:
3804 CheckExplicitlyDefaultedDefaultConstructor(
3805 cast<CXXConstructorDecl>(*MI));
3806 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003807
Sean Huntcb45a0f2011-05-12 22:46:25 +00003808 case CXXDestructor:
3809 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3810 break;
3811
3812 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003813 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3814 break;
3815
Sean Huntcb45a0f2011-05-12 22:46:25 +00003816 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003817 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003818 break;
3819
Sean Hunt82713172011-05-25 23:16:36 +00003820 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003821 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003822 break;
3823
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003824 case CXXMoveAssignment:
3825 CheckExplicitlyDefaultedMoveAssignment(*MI);
3826 break;
3827
3828 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003829 llvm_unreachable("non-special member explicitly defaulted!");
3830 }
Sean Hunt001cad92011-05-10 00:49:42 +00003831 }
3832 }
3833
Sean Hunt001cad92011-05-10 00:49:42 +00003834}
3835
3836void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3837 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3838
3839 // Whether this was the first-declared instance of the constructor.
3840 // This affects whether we implicitly add an exception spec (and, eventually,
3841 // constexpr). It is also ill-formed to explicitly default a constructor such
3842 // that it would be deleted. (C++0x [decl.fct.def.default])
3843 bool First = CD == CD->getCanonicalDecl();
3844
Sean Hunt49634cf2011-05-13 06:10:58 +00003845 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003846 if (CD->getNumParams() != 0) {
3847 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3848 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003849 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003850 }
3851
3852 ImplicitExceptionSpecification Spec
3853 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3854 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003855 if (EPI.ExceptionSpecType == EST_Delayed) {
3856 // Exception specification depends on some deferred part of the class. We'll
3857 // try again when the class's definition has been fully processed.
3858 return;
3859 }
Sean Hunt001cad92011-05-10 00:49:42 +00003860 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3861 *ExceptionType = Context.getFunctionType(
3862 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3863
Richard Smith61802452011-12-22 02:22:31 +00003864 // C++11 [dcl.fct.def.default]p2:
3865 // An explicitly-defaulted function may be declared constexpr only if it
3866 // would have been implicitly declared as constexpr,
3867 if (CD->isConstexpr()) {
3868 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3869 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3870 << CXXDefaultConstructor;
3871 HadError = true;
3872 }
3873 }
3874 // and may have an explicit exception-specification only if it is compatible
3875 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003876 if (CtorType->hasExceptionSpec()) {
3877 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003878 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003879 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003880 PDiag(),
3881 ExceptionType, SourceLocation(),
3882 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003883 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003884 }
Richard Smith61802452011-12-22 02:22:31 +00003885 }
3886
3887 // If a function is explicitly defaulted on its first declaration,
3888 if (First) {
3889 // -- it is implicitly considered to be constexpr if the implicit
3890 // definition would be,
3891 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3892
3893 // -- it is implicitly considered to have the same
3894 // exception-specification as if it had been implicitly declared
3895 //
3896 // FIXME: a compatible, but different, explicit exception specification
3897 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003898 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003899 }
Sean Huntca46d132011-05-12 03:51:48 +00003900
Sean Hunt49634cf2011-05-13 06:10:58 +00003901 if (HadError) {
3902 CD->setInvalidDecl();
3903 return;
3904 }
3905
Sean Hunte16da072011-10-10 06:18:57 +00003906 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003907 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003908 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003909 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003910 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003911 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003912 CD->setInvalidDecl();
3913 }
3914 }
3915}
3916
3917void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3918 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3919
3920 // Whether this was the first-declared instance of the constructor.
3921 bool First = CD == CD->getCanonicalDecl();
3922
3923 bool HadError = false;
3924 if (CD->getNumParams() != 1) {
3925 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3926 << CD->getSourceRange();
3927 HadError = true;
3928 }
3929
3930 ImplicitExceptionSpecification Spec(Context);
3931 bool Const;
3932 llvm::tie(Spec, Const) =
3933 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3934
3935 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3936 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3937 *ExceptionType = Context.getFunctionType(
3938 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3939
3940 // Check for parameter type matching.
3941 // This is a copy ctor so we know it's a cv-qualified reference to T.
3942 QualType ArgType = CtorType->getArgType(0);
3943 if (ArgType->getPointeeType().isVolatileQualified()) {
3944 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3945 HadError = true;
3946 }
3947 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3948 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3949 HadError = true;
3950 }
3951
Richard Smith61802452011-12-22 02:22:31 +00003952 // C++11 [dcl.fct.def.default]p2:
3953 // An explicitly-defaulted function may be declared constexpr only if it
3954 // would have been implicitly declared as constexpr,
3955 if (CD->isConstexpr()) {
3956 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3957 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3958 << CXXCopyConstructor;
3959 HadError = true;
3960 }
3961 }
3962 // and may have an explicit exception-specification only if it is compatible
3963 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003964 if (CtorType->hasExceptionSpec()) {
3965 if (CheckEquivalentExceptionSpec(
3966 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003967 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003968 PDiag(),
3969 ExceptionType, SourceLocation(),
3970 CtorType, CD->getLocation())) {
3971 HadError = true;
3972 }
Richard Smith61802452011-12-22 02:22:31 +00003973 }
3974
3975 // If a function is explicitly defaulted on its first declaration,
3976 if (First) {
3977 // -- it is implicitly considered to be constexpr if the implicit
3978 // definition would be,
3979 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3980
3981 // -- it is implicitly considered to have the same
3982 // exception-specification as if it had been implicitly declared, and
3983 //
3984 // FIXME: a compatible, but different, explicit exception specification
3985 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003986 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003987
3988 // -- [...] it shall have the same parameter type as if it had been
3989 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003990 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3991 }
3992
3993 if (HadError) {
3994 CD->setInvalidDecl();
3995 return;
3996 }
3997
Sean Huntc32d6842011-10-11 04:55:36 +00003998 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003999 if (First) {
4000 CD->setDeletedAsWritten();
4001 } else {
4002 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004003 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004004 CD->setInvalidDecl();
4005 }
Sean Huntca46d132011-05-12 03:51:48 +00004006 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004007}
Sean Hunt001cad92011-05-10 00:49:42 +00004008
Sean Hunt2b188082011-05-14 05:23:28 +00004009void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4010 assert(MD->isExplicitlyDefaulted());
4011
4012 // Whether this was the first-declared instance of the operator
4013 bool First = MD == MD->getCanonicalDecl();
4014
4015 bool HadError = false;
4016 if (MD->getNumParams() != 1) {
4017 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4018 << MD->getSourceRange();
4019 HadError = true;
4020 }
4021
4022 QualType ReturnType =
4023 MD->getType()->getAs<FunctionType>()->getResultType();
4024 if (!ReturnType->isLValueReferenceType() ||
4025 !Context.hasSameType(
4026 Context.getCanonicalType(ReturnType->getPointeeType()),
4027 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4028 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4029 HadError = true;
4030 }
4031
4032 ImplicitExceptionSpecification Spec(Context);
4033 bool Const;
4034 llvm::tie(Spec, Const) =
4035 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4036
4037 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4038 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4039 *ExceptionType = Context.getFunctionType(
4040 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4041
Sean Hunt2b188082011-05-14 05:23:28 +00004042 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004043 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004044 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004045 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004046 } else {
4047 if (ArgType->getPointeeType().isVolatileQualified()) {
4048 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4049 HadError = true;
4050 }
4051 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4052 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4053 HadError = true;
4054 }
Sean Hunt2b188082011-05-14 05:23:28 +00004055 }
Sean Huntbe631222011-05-17 20:44:43 +00004056
Sean Hunt2b188082011-05-14 05:23:28 +00004057 if (OperType->getTypeQuals()) {
4058 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4059 HadError = true;
4060 }
4061
4062 if (OperType->hasExceptionSpec()) {
4063 if (CheckEquivalentExceptionSpec(
4064 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004065 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004066 PDiag(),
4067 ExceptionType, SourceLocation(),
4068 OperType, MD->getLocation())) {
4069 HadError = true;
4070 }
Richard Smith61802452011-12-22 02:22:31 +00004071 }
4072 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004073 // We set the declaration to have the computed exception spec here.
4074 // We duplicate the one parameter type.
4075 EPI.RefQualifier = OperType->getRefQualifier();
4076 EPI.ExtInfo = OperType->getExtInfo();
4077 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4078 }
4079
4080 if (HadError) {
4081 MD->setInvalidDecl();
4082 return;
4083 }
4084
4085 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4086 if (First) {
4087 MD->setDeletedAsWritten();
4088 } else {
4089 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004090 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004091 MD->setInvalidDecl();
4092 }
4093 }
4094}
4095
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004096void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4097 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4098
4099 // Whether this was the first-declared instance of the constructor.
4100 bool First = CD == CD->getCanonicalDecl();
4101
4102 bool HadError = false;
4103 if (CD->getNumParams() != 1) {
4104 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4105 << CD->getSourceRange();
4106 HadError = true;
4107 }
4108
4109 ImplicitExceptionSpecification Spec(
4110 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4111
4112 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4113 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4114 *ExceptionType = Context.getFunctionType(
4115 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4116
4117 // Check for parameter type matching.
4118 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4119 QualType ArgType = CtorType->getArgType(0);
4120 if (ArgType->getPointeeType().isVolatileQualified()) {
4121 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4122 HadError = true;
4123 }
4124 if (ArgType->getPointeeType().isConstQualified()) {
4125 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4126 HadError = true;
4127 }
4128
Richard Smith61802452011-12-22 02:22:31 +00004129 // C++11 [dcl.fct.def.default]p2:
4130 // An explicitly-defaulted function may be declared constexpr only if it
4131 // would have been implicitly declared as constexpr,
4132 if (CD->isConstexpr()) {
4133 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4134 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4135 << CXXMoveConstructor;
4136 HadError = true;
4137 }
4138 }
4139 // and may have an explicit exception-specification only if it is compatible
4140 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004141 if (CtorType->hasExceptionSpec()) {
4142 if (CheckEquivalentExceptionSpec(
4143 PDiag(diag::err_incorrect_defaulted_exception_spec)
4144 << CXXMoveConstructor,
4145 PDiag(),
4146 ExceptionType, SourceLocation(),
4147 CtorType, CD->getLocation())) {
4148 HadError = true;
4149 }
Richard Smith61802452011-12-22 02:22:31 +00004150 }
4151
4152 // If a function is explicitly defaulted on its first declaration,
4153 if (First) {
4154 // -- it is implicitly considered to be constexpr if the implicit
4155 // definition would be,
4156 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4157
4158 // -- it is implicitly considered to have the same
4159 // exception-specification as if it had been implicitly declared, and
4160 //
4161 // FIXME: a compatible, but different, explicit exception specification
4162 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004163 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004164
4165 // -- [...] it shall have the same parameter type as if it had been
4166 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004167 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4168 }
4169
4170 if (HadError) {
4171 CD->setInvalidDecl();
4172 return;
4173 }
4174
Sean Hunt769bb2d2011-10-11 06:43:29 +00004175 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004176 if (First) {
4177 CD->setDeletedAsWritten();
4178 } else {
4179 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4180 << CXXMoveConstructor;
4181 CD->setInvalidDecl();
4182 }
4183 }
4184}
4185
4186void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4187 assert(MD->isExplicitlyDefaulted());
4188
4189 // Whether this was the first-declared instance of the operator
4190 bool First = MD == MD->getCanonicalDecl();
4191
4192 bool HadError = false;
4193 if (MD->getNumParams() != 1) {
4194 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4195 << MD->getSourceRange();
4196 HadError = true;
4197 }
4198
4199 QualType ReturnType =
4200 MD->getType()->getAs<FunctionType>()->getResultType();
4201 if (!ReturnType->isLValueReferenceType() ||
4202 !Context.hasSameType(
4203 Context.getCanonicalType(ReturnType->getPointeeType()),
4204 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4205 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4206 HadError = true;
4207 }
4208
4209 ImplicitExceptionSpecification Spec(
4210 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4211
4212 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4213 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4214 *ExceptionType = Context.getFunctionType(
4215 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4216
4217 QualType ArgType = OperType->getArgType(0);
4218 if (!ArgType->isRValueReferenceType()) {
4219 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4220 HadError = true;
4221 } else {
4222 if (ArgType->getPointeeType().isVolatileQualified()) {
4223 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4224 HadError = true;
4225 }
4226 if (ArgType->getPointeeType().isConstQualified()) {
4227 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4228 HadError = true;
4229 }
4230 }
4231
4232 if (OperType->getTypeQuals()) {
4233 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4234 HadError = true;
4235 }
4236
4237 if (OperType->hasExceptionSpec()) {
4238 if (CheckEquivalentExceptionSpec(
4239 PDiag(diag::err_incorrect_defaulted_exception_spec)
4240 << CXXMoveAssignment,
4241 PDiag(),
4242 ExceptionType, SourceLocation(),
4243 OperType, MD->getLocation())) {
4244 HadError = true;
4245 }
Richard Smith61802452011-12-22 02:22:31 +00004246 }
4247 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004248 // We set the declaration to have the computed exception spec here.
4249 // We duplicate the one parameter type.
4250 EPI.RefQualifier = OperType->getRefQualifier();
4251 EPI.ExtInfo = OperType->getExtInfo();
4252 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4253 }
4254
4255 if (HadError) {
4256 MD->setInvalidDecl();
4257 return;
4258 }
4259
4260 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4261 if (First) {
4262 MD->setDeletedAsWritten();
4263 } else {
4264 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4265 << CXXMoveAssignment;
4266 MD->setInvalidDecl();
4267 }
4268 }
4269}
4270
Sean Huntcb45a0f2011-05-12 22:46:25 +00004271void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4272 assert(DD->isExplicitlyDefaulted());
4273
4274 // Whether this was the first-declared instance of the destructor.
4275 bool First = DD == DD->getCanonicalDecl();
4276
4277 ImplicitExceptionSpecification Spec
4278 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4279 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4280 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4281 *ExceptionType = Context.getFunctionType(
4282 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4283
4284 if (DtorType->hasExceptionSpec()) {
4285 if (CheckEquivalentExceptionSpec(
4286 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004287 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004288 PDiag(),
4289 ExceptionType, SourceLocation(),
4290 DtorType, DD->getLocation())) {
4291 DD->setInvalidDecl();
4292 return;
4293 }
Richard Smith61802452011-12-22 02:22:31 +00004294 }
4295 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004296 // We set the declaration to have the computed exception spec here.
4297 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004298 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004299 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4300 }
4301
4302 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004303 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004304 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004305 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004306 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004307 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004308 DD->setInvalidDecl();
4309 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004310 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004311}
4312
Sean Hunte16da072011-10-10 06:18:57 +00004313/// This function implements the following C++0x paragraphs:
4314/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004315/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004316bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4317 assert(!MD->isInvalidDecl());
4318 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004319 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004320 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004321 return false;
4322
Sean Hunte16da072011-10-10 06:18:57 +00004323 bool IsUnion = RD->isUnion();
4324 bool IsConstructor = false;
4325 bool IsAssignment = false;
4326 bool IsMove = false;
4327
4328 bool ConstArg = false;
4329
4330 switch (CSM) {
4331 case CXXDefaultConstructor:
4332 IsConstructor = true;
4333 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004334 case CXXCopyConstructor:
4335 IsConstructor = true;
4336 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4337 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004338 case CXXMoveConstructor:
4339 IsConstructor = true;
4340 IsMove = true;
4341 break;
Sean Hunte16da072011-10-10 06:18:57 +00004342 default:
4343 llvm_unreachable("function only currently implemented for default ctors");
4344 }
4345
4346 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004347
Sean Huntc32d6842011-10-11 04:55:36 +00004348 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004349 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004350
Sean Huntcdee3fe2011-05-11 22:34:38 +00004351 bool AllConst = true;
4352
Sean Huntcdee3fe2011-05-11 22:34:38 +00004353 // We do this because we should never actually use an anonymous
4354 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004355 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004356 return false;
4357
4358 // FIXME: We should put some diagnostic logic right into this function.
4359
Sean Huntcdee3fe2011-05-11 22:34:38 +00004360 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4361 BE = RD->bases_end();
4362 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004363 // We'll handle this one later
4364 if (BI->isVirtual())
4365 continue;
4366
Sean Huntcdee3fe2011-05-11 22:34:38 +00004367 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4368 assert(BaseDecl && "base isn't a CXXRecordDecl");
4369
Sean Hunte16da072011-10-10 06:18:57 +00004370 // Unless we have an assignment operator, the base's destructor must
4371 // be accessible and not deleted.
4372 if (!IsAssignment) {
4373 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4374 if (BaseDtor->isDeleted())
4375 return true;
4376 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4377 AR_accessible)
4378 return true;
4379 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004380
Sean Hunte16da072011-10-10 06:18:57 +00004381 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004382 // unique, accessible, non-deleted function. If we are doing
4383 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004384 if (CSM != CXXDestructor) {
4385 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004386 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004387 false);
4388 if (!SMOR->hasSuccess())
4389 return true;
4390 CXXMethodDecl *BaseMember = SMOR->getMethod();
4391 if (IsConstructor) {
4392 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4393 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4394 PDiag()) != AR_accessible)
4395 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004396
4397 // For a move operation, the corresponding operation must actually
4398 // be a move operation (and not a copy selected by overload
4399 // resolution) unless we are working on a trivially copyable class.
4400 if (IsMove && !BaseCtor->isMoveConstructor() &&
4401 !BaseDecl->isTriviallyCopyable())
4402 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004403 }
4404 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004405 }
4406
4407 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4408 BE = RD->vbases_end();
4409 BI != BE; ++BI) {
4410 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4411 assert(BaseDecl && "base isn't a CXXRecordDecl");
4412
Sean Hunte16da072011-10-10 06:18:57 +00004413 // Unless we have an assignment operator, the base's destructor must
4414 // be accessible and not deleted.
4415 if (!IsAssignment) {
4416 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4417 if (BaseDtor->isDeleted())
4418 return true;
4419 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4420 AR_accessible)
4421 return true;
4422 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004423
Sean Hunte16da072011-10-10 06:18:57 +00004424 // Finding the corresponding member in the base should lead to a
4425 // unique, accessible, non-deleted function.
4426 if (CSM != CXXDestructor) {
4427 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004428 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004429 false);
4430 if (!SMOR->hasSuccess())
4431 return true;
4432 CXXMethodDecl *BaseMember = SMOR->getMethod();
4433 if (IsConstructor) {
4434 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4435 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4436 PDiag()) != AR_accessible)
4437 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004438
4439 // For a move operation, the corresponding operation must actually
4440 // be a move operation (and not a copy selected by overload
4441 // resolution) unless we are working on a trivially copyable class.
4442 if (IsMove && !BaseCtor->isMoveConstructor() &&
4443 !BaseDecl->isTriviallyCopyable())
4444 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004445 }
4446 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004447 }
4448
4449 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4450 FE = RD->field_end();
4451 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004452 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004453 continue;
4454
Sean Huntcdee3fe2011-05-11 22:34:38 +00004455 QualType FieldType = Context.getBaseElementType(FI->getType());
4456 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004457
Sean Hunte16da072011-10-10 06:18:57 +00004458 // For a default constructor, all references must be initialized in-class
4459 // and, if a union, it must have a non-const member.
4460 if (CSM == CXXDefaultConstructor) {
4461 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4462 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004463
Sean Hunte16da072011-10-10 06:18:57 +00004464 if (IsUnion && !FieldType.isConstQualified())
4465 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004466 // For a copy constructor, data members must not be of rvalue reference
4467 // type.
4468 } else if (CSM == CXXCopyConstructor) {
4469 if (FieldType->isRValueReferenceType())
4470 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004471 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004472
4473 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004474 // For a default constructor, a const member must have a user-provided
4475 // default constructor or else be explicitly initialized.
4476 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004477 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004478 !FieldRecord->hasUserProvidedDefaultConstructor())
4479 return true;
4480
Sean Huntc32d6842011-10-11 04:55:36 +00004481 // Some additional restrictions exist on the variant members.
4482 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004483 FieldRecord->isAnonymousStructOrUnion()) {
4484 // We're okay to reuse AllConst here since we only care about the
4485 // value otherwise if we're in a union.
4486 AllConst = true;
4487
4488 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4489 UE = FieldRecord->field_end();
4490 UI != UE; ++UI) {
4491 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4492 CXXRecordDecl *UnionFieldRecord =
4493 UnionFieldType->getAsCXXRecordDecl();
4494
4495 if (!UnionFieldType.isConstQualified())
4496 AllConst = false;
4497
Sean Huntc32d6842011-10-11 04:55:36 +00004498 if (UnionFieldRecord) {
4499 // FIXME: Checking for accessibility and validity of this
4500 // destructor is technically going beyond the
4501 // standard, but this is believed to be a defect.
4502 if (!IsAssignment) {
4503 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4504 if (FieldDtor->isDeleted())
4505 return true;
4506 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4507 AR_accessible)
4508 return true;
4509 if (!FieldDtor->isTrivial())
4510 return true;
4511 }
4512
4513 if (CSM != CXXDestructor) {
4514 SpecialMemberOverloadResult *SMOR =
4515 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004516 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004517 // FIXME: Checking for accessibility and validity of this
4518 // corresponding member is technically going beyond the
4519 // standard, but this is believed to be a defect.
4520 if (!SMOR->hasSuccess())
4521 return true;
4522
4523 CXXMethodDecl *FieldMember = SMOR->getMethod();
4524 // A member of a union must have a trivial corresponding
4525 // constructor.
4526 if (!FieldMember->isTrivial())
4527 return true;
4528
4529 if (IsConstructor) {
4530 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4531 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4532 PDiag()) != AR_accessible)
4533 return true;
4534 }
4535 }
4536 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004537 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004538
Sean Huntc32d6842011-10-11 04:55:36 +00004539 // At least one member in each anonymous union must be non-const
4540 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004541 return true;
4542
4543 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004544 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004545 continue;
4546 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004547
Sean Huntc32d6842011-10-11 04:55:36 +00004548 // Unless we're doing assignment, the field's destructor must be
4549 // accessible and not deleted.
4550 if (!IsAssignment) {
4551 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4552 if (FieldDtor->isDeleted())
4553 return true;
4554 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4555 AR_accessible)
4556 return true;
4557 }
4558
Sean Hunte16da072011-10-10 06:18:57 +00004559 // Check that the corresponding member of the field is accessible,
4560 // unique, and non-deleted. We don't do this if it has an explicit
4561 // initialization when default-constructing.
4562 if (CSM != CXXDestructor &&
4563 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4564 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004565 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004566 false);
4567 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004568 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004569
4570 CXXMethodDecl *FieldMember = SMOR->getMethod();
4571 if (IsConstructor) {
4572 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4573 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4574 PDiag()) != AR_accessible)
4575 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004576
4577 // For a move operation, the corresponding operation must actually
4578 // be a move operation (and not a copy selected by overload
4579 // resolution) unless we are working on a trivially copyable class.
4580 if (IsMove && !FieldCtor->isMoveConstructor() &&
4581 !FieldRecord->isTriviallyCopyable())
4582 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004583 }
4584
4585 // We need the corresponding member of a union to be trivial so that
4586 // we can safely copy them all simultaneously.
4587 // FIXME: Note that performing the check here (where we rely on the lack
4588 // of an in-class initializer) is technically ill-formed. However, this
4589 // seems most obviously to be a bug in the standard.
4590 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004591 return true;
4592 }
Sean Hunte16da072011-10-10 06:18:57 +00004593 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4594 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4595 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004596 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004597 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004598 }
4599
Sean Hunte16da072011-10-10 06:18:57 +00004600 // We can't have all const members in a union when default-constructing,
4601 // or else they're all nonsensical garbage values that can't be changed.
4602 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004603 return true;
4604
4605 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004606}
4607
Sean Hunt7f410192011-05-14 05:23:24 +00004608bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4609 CXXRecordDecl *RD = MD->getParent();
4610 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004611 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004612 return false;
4613
Sean Hunt71a682f2011-05-18 03:41:58 +00004614 SourceLocation Loc = MD->getLocation();
4615
Sean Hunt7f410192011-05-14 05:23:24 +00004616 // Do access control from the constructor
4617 ContextRAII MethodContext(*this, MD);
4618
4619 bool Union = RD->isUnion();
4620
Sean Hunt661c67a2011-06-21 23:42:56 +00004621 unsigned ArgQuals =
4622 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4623 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004624
4625 // We do this because we should never actually use an anonymous
4626 // union's constructor.
4627 if (Union && RD->isAnonymousStructOrUnion())
4628 return false;
4629
Sean Hunt7f410192011-05-14 05:23:24 +00004630 // FIXME: We should put some diagnostic logic right into this function.
4631
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004632 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004633 // A defaulted [copy] assignment operator for class X is defined as deleted
4634 // if X has:
4635
4636 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4637 BE = RD->bases_end();
4638 BI != BE; ++BI) {
4639 // We'll handle this one later
4640 if (BI->isVirtual())
4641 continue;
4642
4643 QualType BaseType = BI->getType();
4644 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4645 assert(BaseDecl && "base isn't a CXXRecordDecl");
4646
4647 // -- a [direct base class] B that cannot be [copied] because overload
4648 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004649 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004650 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004651 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4652 0);
4653 if (!CopyOper || CopyOper->isDeleted())
4654 return true;
4655 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004656 return true;
4657 }
4658
4659 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4660 BE = RD->vbases_end();
4661 BI != BE; ++BI) {
4662 QualType BaseType = BI->getType();
4663 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4664 assert(BaseDecl && "base isn't a CXXRecordDecl");
4665
Sean Hunt7f410192011-05-14 05:23:24 +00004666 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004667 // resolution, as applied to B's [copy] assignment operator, results in
4668 // an ambiguity or a function that is deleted or inaccessible from the
4669 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004670 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4671 0);
4672 if (!CopyOper || CopyOper->isDeleted())
4673 return true;
4674 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004675 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004676 }
4677
4678 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4679 FE = RD->field_end();
4680 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004681 if (FI->isUnnamedBitfield())
4682 continue;
4683
Sean Hunt7f410192011-05-14 05:23:24 +00004684 QualType FieldType = Context.getBaseElementType(FI->getType());
4685
4686 // -- a non-static data member of reference type
4687 if (FieldType->isReferenceType())
4688 return true;
4689
4690 // -- a non-static data member of const non-class type (or array thereof)
4691 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4692 return true;
4693
4694 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4695
4696 if (FieldRecord) {
4697 // This is an anonymous union
4698 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4699 // Anonymous unions inside unions do not variant members create
4700 if (!Union) {
4701 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4702 UE = FieldRecord->field_end();
4703 UI != UE; ++UI) {
4704 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4705 CXXRecordDecl *UnionFieldRecord =
4706 UnionFieldType->getAsCXXRecordDecl();
4707
4708 // -- a variant member with a non-trivial [copy] assignment operator
4709 // and X is a union-like class
4710 if (UnionFieldRecord &&
4711 !UnionFieldRecord->hasTrivialCopyAssignment())
4712 return true;
4713 }
4714 }
4715
4716 // Don't try to initalize an anonymous union
4717 continue;
4718 // -- a variant member with a non-trivial [copy] assignment operator
4719 // and X is a union-like class
4720 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4721 return true;
4722 }
Sean Hunt7f410192011-05-14 05:23:24 +00004723
Sean Hunt661c67a2011-06-21 23:42:56 +00004724 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4725 false, 0);
4726 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004727 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004728 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004729 return true;
4730 }
4731 }
4732
4733 return false;
4734}
4735
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004736bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4737 CXXRecordDecl *RD = MD->getParent();
4738 assert(!RD->isDependentType() && "do deletion after instantiation");
4739 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4740 return false;
4741
4742 SourceLocation Loc = MD->getLocation();
4743
4744 // Do access control from the constructor
4745 ContextRAII MethodContext(*this, MD);
4746
4747 bool Union = RD->isUnion();
4748
4749 // We do this because we should never actually use an anonymous
4750 // union's constructor.
4751 if (Union && RD->isAnonymousStructOrUnion())
4752 return false;
4753
4754 // C++0x [class.copy]/20
4755 // A defaulted [move] assignment operator for class X is defined as deleted
4756 // if X has:
4757
4758 // -- for the move constructor, [...] any direct or indirect virtual base
4759 // class.
4760 if (RD->getNumVBases() != 0)
4761 return true;
4762
4763 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4764 BE = RD->bases_end();
4765 BI != BE; ++BI) {
4766
4767 QualType BaseType = BI->getType();
4768 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4769 assert(BaseDecl && "base isn't a CXXRecordDecl");
4770
4771 // -- a [direct base class] B that cannot be [moved] because overload
4772 // resolution, as applied to B's [move] assignment operator, results in
4773 // an ambiguity or a function that is deleted or inaccessible from the
4774 // assignment operator
4775 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4776 if (!MoveOper || MoveOper->isDeleted())
4777 return true;
4778 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4779 return true;
4780
4781 // -- for the move assignment operator, a [direct base class] with a type
4782 // that does not have a move assignment operator and is not trivially
4783 // copyable.
4784 if (!MoveOper->isMoveAssignmentOperator() &&
4785 !BaseDecl->isTriviallyCopyable())
4786 return true;
4787 }
4788
4789 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4790 FE = RD->field_end();
4791 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004792 if (FI->isUnnamedBitfield())
4793 continue;
4794
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004795 QualType FieldType = Context.getBaseElementType(FI->getType());
4796
4797 // -- a non-static data member of reference type
4798 if (FieldType->isReferenceType())
4799 return true;
4800
4801 // -- a non-static data member of const non-class type (or array thereof)
4802 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4803 return true;
4804
4805 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4806
4807 if (FieldRecord) {
4808 // This is an anonymous union
4809 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4810 // Anonymous unions inside unions do not variant members create
4811 if (!Union) {
4812 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4813 UE = FieldRecord->field_end();
4814 UI != UE; ++UI) {
4815 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4816 CXXRecordDecl *UnionFieldRecord =
4817 UnionFieldType->getAsCXXRecordDecl();
4818
4819 // -- a variant member with a non-trivial [move] assignment operator
4820 // and X is a union-like class
4821 if (UnionFieldRecord &&
4822 !UnionFieldRecord->hasTrivialMoveAssignment())
4823 return true;
4824 }
4825 }
4826
4827 // Don't try to initalize an anonymous union
4828 continue;
4829 // -- a variant member with a non-trivial [move] assignment operator
4830 // and X is a union-like class
4831 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4832 return true;
4833 }
4834
4835 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4836 if (!MoveOper || MoveOper->isDeleted())
4837 return true;
4838 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4839 return true;
4840
4841 // -- for the move assignment operator, a [non-static data member] with a
4842 // type that does not have a move assignment operator and is not
4843 // trivially copyable.
4844 if (!MoveOper->isMoveAssignmentOperator() &&
4845 !FieldRecord->isTriviallyCopyable())
4846 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004847 }
Sean Hunt7f410192011-05-14 05:23:24 +00004848 }
4849
4850 return false;
4851}
4852
Sean Huntcb45a0f2011-05-12 22:46:25 +00004853bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4854 CXXRecordDecl *RD = DD->getParent();
4855 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004856 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004857 return false;
4858
Sean Hunt71a682f2011-05-18 03:41:58 +00004859 SourceLocation Loc = DD->getLocation();
4860
Sean Huntcb45a0f2011-05-12 22:46:25 +00004861 // Do access control from the destructor
4862 ContextRAII CtorContext(*this, DD);
4863
4864 bool Union = RD->isUnion();
4865
Sean Hunt49634cf2011-05-13 06:10:58 +00004866 // We do this because we should never actually use an anonymous
4867 // union's destructor.
4868 if (Union && RD->isAnonymousStructOrUnion())
4869 return false;
4870
Sean Huntcb45a0f2011-05-12 22:46:25 +00004871 // C++0x [class.dtor]p5
4872 // A defaulted destructor for a class X is defined as deleted if:
4873 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4874 BE = RD->bases_end();
4875 BI != BE; ++BI) {
4876 // We'll handle this one later
4877 if (BI->isVirtual())
4878 continue;
4879
4880 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4881 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4882 assert(BaseDtor && "base has no destructor");
4883
4884 // -- any direct or virtual base class has a deleted destructor or
4885 // a destructor that is inaccessible from the defaulted destructor
4886 if (BaseDtor->isDeleted())
4887 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004888 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004889 AR_accessible)
4890 return true;
4891 }
4892
4893 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4894 BE = RD->vbases_end();
4895 BI != BE; ++BI) {
4896 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4897 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4898 assert(BaseDtor && "base has no destructor");
4899
4900 // -- any direct or virtual base class has a deleted destructor or
4901 // a destructor that is inaccessible from the defaulted destructor
4902 if (BaseDtor->isDeleted())
4903 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004904 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004905 AR_accessible)
4906 return true;
4907 }
4908
4909 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4910 FE = RD->field_end();
4911 FI != FE; ++FI) {
4912 QualType FieldType = Context.getBaseElementType(FI->getType());
4913 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4914 if (FieldRecord) {
4915 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4916 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4917 UE = FieldRecord->field_end();
4918 UI != UE; ++UI) {
4919 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4920 CXXRecordDecl *UnionFieldRecord =
4921 UnionFieldType->getAsCXXRecordDecl();
4922
4923 // -- X is a union-like class that has a variant member with a non-
4924 // trivial destructor.
4925 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4926 return true;
4927 }
4928 // Technically we are supposed to do this next check unconditionally.
4929 // But that makes absolutely no sense.
4930 } else {
4931 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4932
4933 // -- any of the non-static data members has class type M (or array
4934 // thereof) and M has a deleted destructor or a destructor that is
4935 // inaccessible from the defaulted destructor
4936 if (FieldDtor->isDeleted())
4937 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004938 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004939 AR_accessible)
4940 return true;
4941
4942 // -- X is a union-like class that has a variant member with a non-
4943 // trivial destructor.
4944 if (Union && !FieldDtor->isTrivial())
4945 return true;
4946 }
4947 }
4948 }
4949
4950 if (DD->isVirtual()) {
4951 FunctionDecl *OperatorDelete = 0;
4952 DeclarationName Name =
4953 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004954 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004955 false))
4956 return true;
4957 }
4958
4959
4960 return false;
4961}
4962
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004963/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004964namespace {
4965 struct FindHiddenVirtualMethodData {
4966 Sema *S;
4967 CXXMethodDecl *Method;
4968 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004969 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004970 };
4971}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004972
4973/// \brief Member lookup function that determines whether a given C++
4974/// method overloads virtual methods in a base class without overriding any,
4975/// to be used with CXXRecordDecl::lookupInBases().
4976static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4977 CXXBasePath &Path,
4978 void *UserData) {
4979 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4980
4981 FindHiddenVirtualMethodData &Data
4982 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4983
4984 DeclarationName Name = Data.Method->getDeclName();
4985 assert(Name.getNameKind() == DeclarationName::Identifier);
4986
4987 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004988 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004989 for (Path.Decls = BaseRecord->lookup(Name);
4990 Path.Decls.first != Path.Decls.second;
4991 ++Path.Decls.first) {
4992 NamedDecl *D = *Path.Decls.first;
4993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004994 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004995 foundSameNameMethod = true;
4996 // Interested only in hidden virtual methods.
4997 if (!MD->isVirtual())
4998 continue;
4999 // If the method we are checking overrides a method from its base
5000 // don't warn about the other overloaded methods.
5001 if (!Data.S->IsOverload(Data.Method, MD, false))
5002 return true;
5003 // Collect the overload only if its hidden.
5004 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5005 overloadedMethods.push_back(MD);
5006 }
5007 }
5008
5009 if (foundSameNameMethod)
5010 Data.OverloadedMethods.append(overloadedMethods.begin(),
5011 overloadedMethods.end());
5012 return foundSameNameMethod;
5013}
5014
5015/// \brief See if a method overloads virtual methods in a base class without
5016/// overriding any.
5017void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5018 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005019 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005020 return;
5021 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5022 return;
5023
5024 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5025 /*bool RecordPaths=*/false,
5026 /*bool DetectVirtual=*/false);
5027 FindHiddenVirtualMethodData Data;
5028 Data.Method = MD;
5029 Data.S = this;
5030
5031 // Keep the base methods that were overriden or introduced in the subclass
5032 // by 'using' in a set. A base method not in this set is hidden.
5033 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5034 res.first != res.second; ++res.first) {
5035 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5036 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5037 E = MD->end_overridden_methods();
5038 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005039 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005040 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5041 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005042 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005043 }
5044
5045 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5046 !Data.OverloadedMethods.empty()) {
5047 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5048 << MD << (Data.OverloadedMethods.size() > 1);
5049
5050 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5051 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5052 Diag(overloadedMD->getLocation(),
5053 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5054 }
5055 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005056}
5057
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005058void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005059 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005060 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005061 SourceLocation RBrac,
5062 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005063 if (!TagDecl)
5064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005065
Douglas Gregor42af25f2009-05-11 19:58:34 +00005066 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005067
David Blaikie77b6de02011-09-22 02:58:26 +00005068 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005069 // strict aliasing violation!
5070 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005071 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005072
Douglas Gregor23c94db2010-07-02 17:43:08 +00005073 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005074 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005075}
5076
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005077/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5078/// special functions, such as the default constructor, copy
5079/// constructor, or destructor, to the given C++ class (C++
5080/// [special]p1). This routine can only be executed just before the
5081/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005082void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005083 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005084 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005085
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005086 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005087 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005088
Richard Smithb701d3d2011-12-24 21:56:24 +00005089 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5090 ++ASTContext::NumImplicitMoveConstructors;
5091
Douglas Gregora376d102010-07-02 21:50:04 +00005092 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5093 ++ASTContext::NumImplicitCopyAssignmentOperators;
5094
5095 // If we have a dynamic class, then the copy assignment operator may be
5096 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5097 // it shows up in the right place in the vtable and that we diagnose
5098 // problems with the implicit exception specification.
5099 if (ClassDecl->isDynamicClass())
5100 DeclareImplicitCopyAssignment(ClassDecl);
5101 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005102
Richard Smithb701d3d2011-12-24 21:56:24 +00005103 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5104 ++ASTContext::NumImplicitMoveAssignmentOperators;
5105
5106 // Likewise for the move assignment operator.
5107 if (ClassDecl->isDynamicClass())
5108 DeclareImplicitMoveAssignment(ClassDecl);
5109 }
5110
Douglas Gregor4923aa22010-07-02 20:37:36 +00005111 if (!ClassDecl->hasUserDeclaredDestructor()) {
5112 ++ASTContext::NumImplicitDestructors;
5113
5114 // If we have a dynamic class, then the destructor may be virtual, so we
5115 // have to declare the destructor immediately. This ensures that, e.g., it
5116 // shows up in the right place in the vtable and that we diagnose problems
5117 // with the implicit exception specification.
5118 if (ClassDecl->isDynamicClass())
5119 DeclareImplicitDestructor(ClassDecl);
5120 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005121}
5122
Francois Pichet8387e2a2011-04-22 22:18:13 +00005123void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5124 if (!D)
5125 return;
5126
5127 int NumParamList = D->getNumTemplateParameterLists();
5128 for (int i = 0; i < NumParamList; i++) {
5129 TemplateParameterList* Params = D->getTemplateParameterList(i);
5130 for (TemplateParameterList::iterator Param = Params->begin(),
5131 ParamEnd = Params->end();
5132 Param != ParamEnd; ++Param) {
5133 NamedDecl *Named = cast<NamedDecl>(*Param);
5134 if (Named->getDeclName()) {
5135 S->AddDecl(Named);
5136 IdResolver.AddDecl(Named);
5137 }
5138 }
5139 }
5140}
5141
John McCalld226f652010-08-21 09:40:31 +00005142void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005143 if (!D)
5144 return;
5145
5146 TemplateParameterList *Params = 0;
5147 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5148 Params = Template->getTemplateParameters();
5149 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5150 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5151 Params = PartialSpec->getTemplateParameters();
5152 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005153 return;
5154
Douglas Gregor6569d682009-05-27 23:11:45 +00005155 for (TemplateParameterList::iterator Param = Params->begin(),
5156 ParamEnd = Params->end();
5157 Param != ParamEnd; ++Param) {
5158 NamedDecl *Named = cast<NamedDecl>(*Param);
5159 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005160 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005161 IdResolver.AddDecl(Named);
5162 }
5163 }
5164}
5165
John McCalld226f652010-08-21 09:40:31 +00005166void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005167 if (!RecordD) return;
5168 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005169 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005170 PushDeclContext(S, Record);
5171}
5172
John McCalld226f652010-08-21 09:40:31 +00005173void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005174 if (!RecordD) return;
5175 PopDeclContext();
5176}
5177
Douglas Gregor72b505b2008-12-16 21:30:33 +00005178/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5179/// parsing a top-level (non-nested) C++ class, and we are now
5180/// parsing those parts of the given Method declaration that could
5181/// not be parsed earlier (C++ [class.mem]p2), such as default
5182/// arguments. This action should enter the scope of the given
5183/// Method declaration as if we had just parsed the qualified method
5184/// name. However, it should not bring the parameters into scope;
5185/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005186void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005187}
5188
5189/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5190/// C++ method declaration. We're (re-)introducing the given
5191/// function parameter into scope for use in parsing later parts of
5192/// the method declaration. For example, we could see an
5193/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005194void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005195 if (!ParamD)
5196 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005197
John McCalld226f652010-08-21 09:40:31 +00005198 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005199
5200 // If this parameter has an unparsed default argument, clear it out
5201 // to make way for the parsed default argument.
5202 if (Param->hasUnparsedDefaultArg())
5203 Param->setDefaultArg(0);
5204
John McCalld226f652010-08-21 09:40:31 +00005205 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005206 if (Param->getDeclName())
5207 IdResolver.AddDecl(Param);
5208}
5209
5210/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5211/// processing the delayed method declaration for Method. The method
5212/// declaration is now considered finished. There may be a separate
5213/// ActOnStartOfFunctionDef action later (not necessarily
5214/// immediately!) for this method, if it was also defined inside the
5215/// class body.
John McCalld226f652010-08-21 09:40:31 +00005216void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005217 if (!MethodD)
5218 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005220 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005221
John McCalld226f652010-08-21 09:40:31 +00005222 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005223
5224 // Now that we have our default arguments, check the constructor
5225 // again. It could produce additional diagnostics or affect whether
5226 // the class has implicitly-declared destructors, among other
5227 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005228 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5229 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005230
5231 // Check the default arguments, which we may have added.
5232 if (!Method->isInvalidDecl())
5233 CheckCXXDefaultArguments(Method);
5234}
5235
Douglas Gregor42a552f2008-11-05 20:51:48 +00005236/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005237/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005238/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005239/// emit diagnostics and set the invalid bit to true. In any case, the type
5240/// will be updated to reflect a well-formed type for the constructor and
5241/// returned.
5242QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005243 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005244 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005245
5246 // C++ [class.ctor]p3:
5247 // A constructor shall not be virtual (10.3) or static (9.4). A
5248 // constructor can be invoked for a const, volatile or const
5249 // volatile object. A constructor shall not be declared const,
5250 // volatile, or const volatile (9.3.2).
5251 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005252 if (!D.isInvalidType())
5253 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5254 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5255 << SourceRange(D.getIdentifierLoc());
5256 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005257 }
John McCalld931b082010-08-26 03:08:43 +00005258 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005259 if (!D.isInvalidType())
5260 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5261 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5262 << SourceRange(D.getIdentifierLoc());
5263 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005264 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005267 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005268 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005269 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005270 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5271 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005272 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005273 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5274 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005275 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005276 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5277 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005278 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005279 }
Mike Stump1eb44332009-09-09 15:08:12 +00005280
Douglas Gregorc938c162011-01-26 05:01:58 +00005281 // C++0x [class.ctor]p4:
5282 // A constructor shall not be declared with a ref-qualifier.
5283 if (FTI.hasRefQualifier()) {
5284 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5285 << FTI.RefQualifierIsLValueRef
5286 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5287 D.setInvalidType();
5288 }
5289
Douglas Gregor42a552f2008-11-05 20:51:48 +00005290 // Rebuild the function type "R" without any type qualifiers (in
5291 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005292 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005293 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005294 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5295 return R;
5296
5297 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5298 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005299 EPI.RefQualifier = RQ_None;
5300
Chris Lattner65401802009-04-25 08:28:21 +00005301 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005302 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005303}
5304
Douglas Gregor72b505b2008-12-16 21:30:33 +00005305/// CheckConstructor - Checks a fully-formed constructor for
5306/// well-formedness, issuing any diagnostics required. Returns true if
5307/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005308void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005309 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005310 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5311 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005312 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005313
5314 // C++ [class.copy]p3:
5315 // A declaration of a constructor for a class X is ill-formed if
5316 // its first parameter is of type (optionally cv-qualified) X and
5317 // either there are no other parameters or else all other
5318 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005319 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005320 ((Constructor->getNumParams() == 1) ||
5321 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005322 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5323 Constructor->getTemplateSpecializationKind()
5324 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005325 QualType ParamType = Constructor->getParamDecl(0)->getType();
5326 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5327 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005328 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005329 const char *ConstRef
5330 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5331 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005332 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005333 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005334
5335 // FIXME: Rather that making the constructor invalid, we should endeavor
5336 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005337 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005338 }
5339 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005340}
5341
John McCall15442822010-08-04 01:04:25 +00005342/// CheckDestructor - Checks a fully-formed destructor definition for
5343/// well-formedness, issuing any diagnostics required. Returns true
5344/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005345bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005346 CXXRecordDecl *RD = Destructor->getParent();
5347
5348 if (Destructor->isVirtual()) {
5349 SourceLocation Loc;
5350
5351 if (!Destructor->isImplicit())
5352 Loc = Destructor->getLocation();
5353 else
5354 Loc = RD->getLocation();
5355
5356 // If we have a virtual destructor, look up the deallocation function
5357 FunctionDecl *OperatorDelete = 0;
5358 DeclarationName Name =
5359 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005360 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005361 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005362
Eli Friedman5f2987c2012-02-02 03:46:19 +00005363 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005364
5365 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005366 }
Anders Carlsson37909802009-11-30 21:24:50 +00005367
5368 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005369}
5370
Mike Stump1eb44332009-09-09 15:08:12 +00005371static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005372FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5373 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5374 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005375 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005376}
5377
Douglas Gregor42a552f2008-11-05 20:51:48 +00005378/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5379/// the well-formednes of the destructor declarator @p D with type @p
5380/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005381/// emit diagnostics and set the declarator to invalid. Even if this happens,
5382/// will be updated to reflect a well-formed type for the destructor and
5383/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005384QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005385 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005386 // C++ [class.dtor]p1:
5387 // [...] A typedef-name that names a class is a class-name
5388 // (7.1.3); however, a typedef-name that names a class shall not
5389 // be used as the identifier in the declarator for a destructor
5390 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005391 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005392 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005393 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005394 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005395 else if (const TemplateSpecializationType *TST =
5396 DeclaratorType->getAs<TemplateSpecializationType>())
5397 if (TST->isTypeAlias())
5398 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5399 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005400
5401 // C++ [class.dtor]p2:
5402 // A destructor is used to destroy objects of its class type. A
5403 // destructor takes no parameters, and no return type can be
5404 // specified for it (not even void). The address of a destructor
5405 // shall not be taken. A destructor shall not be static. A
5406 // destructor can be invoked for a const, volatile or const
5407 // volatile object. A destructor shall not be declared const,
5408 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005409 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005410 if (!D.isInvalidType())
5411 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5412 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005413 << SourceRange(D.getIdentifierLoc())
5414 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5415
John McCalld931b082010-08-26 03:08:43 +00005416 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005417 }
Chris Lattner65401802009-04-25 08:28:21 +00005418 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005419 // Destructors don't have return types, but the parser will
5420 // happily parse something like:
5421 //
5422 // class X {
5423 // float ~X();
5424 // };
5425 //
5426 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005427 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5428 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5429 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005430 }
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005432 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005433 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005434 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005435 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5436 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005437 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005438 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5439 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005440 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005441 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5442 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005443 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005444 }
5445
Douglas Gregorc938c162011-01-26 05:01:58 +00005446 // C++0x [class.dtor]p2:
5447 // A destructor shall not be declared with a ref-qualifier.
5448 if (FTI.hasRefQualifier()) {
5449 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5450 << FTI.RefQualifierIsLValueRef
5451 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5452 D.setInvalidType();
5453 }
5454
Douglas Gregor42a552f2008-11-05 20:51:48 +00005455 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005456 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005457 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5458
5459 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005460 FTI.freeArgs();
5461 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005462 }
5463
Mike Stump1eb44332009-09-09 15:08:12 +00005464 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005465 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005466 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005467 D.setInvalidType();
5468 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005469
5470 // Rebuild the function type "R" without any type qualifiers or
5471 // parameters (in case any of the errors above fired) and with
5472 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005473 // types.
John McCalle23cf432010-12-14 08:05:40 +00005474 if (!D.isInvalidType())
5475 return R;
5476
Douglas Gregord92ec472010-07-01 05:10:53 +00005477 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005478 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5479 EPI.Variadic = false;
5480 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005481 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005482 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005483}
5484
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005485/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5486/// well-formednes of the conversion function declarator @p D with
5487/// type @p R. If there are any errors in the declarator, this routine
5488/// will emit diagnostics and return true. Otherwise, it will return
5489/// false. Either way, the type @p R will be updated to reflect a
5490/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005491void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005492 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005493 // C++ [class.conv.fct]p1:
5494 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005495 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005496 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005497 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005498 if (!D.isInvalidType())
5499 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5500 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5501 << SourceRange(D.getIdentifierLoc());
5502 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005503 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005504 }
John McCalla3f81372010-04-13 00:04:31 +00005505
5506 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5507
Chris Lattner6e475012009-04-25 08:35:12 +00005508 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005509 // Conversion functions don't have return types, but the parser will
5510 // happily parse something like:
5511 //
5512 // class X {
5513 // float operator bool();
5514 // };
5515 //
5516 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005517 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5518 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5519 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005520 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005521 }
5522
John McCalla3f81372010-04-13 00:04:31 +00005523 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5524
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005526 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005527 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5528
5529 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005530 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005531 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005532 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005533 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005534 D.setInvalidType();
5535 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005536
John McCalla3f81372010-04-13 00:04:31 +00005537 // Diagnose "&operator bool()" and other such nonsense. This
5538 // is actually a gcc extension which we don't support.
5539 if (Proto->getResultType() != ConvType) {
5540 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5541 << Proto->getResultType();
5542 D.setInvalidType();
5543 ConvType = Proto->getResultType();
5544 }
5545
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005546 // C++ [class.conv.fct]p4:
5547 // The conversion-type-id shall not represent a function type nor
5548 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005549 if (ConvType->isArrayType()) {
5550 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5551 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005552 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005553 } else if (ConvType->isFunctionType()) {
5554 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5555 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005556 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005557 }
5558
5559 // Rebuild the function type "R" without any parameters (in case any
5560 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005561 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005562 if (D.isInvalidType())
5563 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005564
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005565 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005566 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005567 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005568 getLangOptions().CPlusPlus0x ?
5569 diag::warn_cxx98_compat_explicit_conversion_functions :
5570 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005571 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005572}
5573
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005574/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5575/// the declaration of the given C++ conversion function. This routine
5576/// is responsible for recording the conversion function in the C++
5577/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005578Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005579 assert(Conversion && "Expected to receive a conversion function declaration");
5580
Douglas Gregor9d350972008-12-12 08:25:50 +00005581 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005582
5583 // Make sure we aren't redeclaring the conversion function.
5584 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005585
5586 // C++ [class.conv.fct]p1:
5587 // [...] A conversion function is never used to convert a
5588 // (possibly cv-qualified) object to the (possibly cv-qualified)
5589 // same object type (or a reference to it), to a (possibly
5590 // cv-qualified) base class of that type (or a reference to it),
5591 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005592 // FIXME: Suppress this warning if the conversion function ends up being a
5593 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005594 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005595 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005596 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005597 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005598 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5599 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005600 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005601 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005602 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5603 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005604 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005605 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005606 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005607 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005608 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005609 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005610 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005611 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005612 }
5613
Douglas Gregore80622f2010-09-29 04:25:11 +00005614 if (FunctionTemplateDecl *ConversionTemplate
5615 = Conversion->getDescribedFunctionTemplate())
5616 return ConversionTemplate;
5617
John McCalld226f652010-08-21 09:40:31 +00005618 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005619}
5620
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005621//===----------------------------------------------------------------------===//
5622// Namespace Handling
5623//===----------------------------------------------------------------------===//
5624
John McCallea318642010-08-26 09:15:37 +00005625
5626
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005627/// ActOnStartNamespaceDef - This is called at the start of a namespace
5628/// definition.
John McCalld226f652010-08-21 09:40:31 +00005629Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005630 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005631 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005632 SourceLocation IdentLoc,
5633 IdentifierInfo *II,
5634 SourceLocation LBrace,
5635 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005636 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5637 // For anonymous namespace, take the location of the left brace.
5638 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005639 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005640 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005641 bool IsStd = false;
5642 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005643 Scope *DeclRegionScope = NamespcScope->getParent();
5644
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005645 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005646 if (II) {
5647 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005648 // The identifier in an original-namespace-definition shall not
5649 // have been previously defined in the declarative region in
5650 // which the original-namespace-definition appears. The
5651 // identifier in an original-namespace-definition is the name of
5652 // the namespace. Subsequently in that declarative region, it is
5653 // treated as an original-namespace-name.
5654 //
5655 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005656 // look through using directives, just look for any ordinary names.
5657
5658 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5660 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005661 NamedDecl *PrevDecl = 0;
5662 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005663 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005664 R.first != R.second; ++R.first) {
5665 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5666 PrevDecl = *R.first;
5667 break;
5668 }
5669 }
5670
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005671 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5672
5673 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005674 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005675 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005676 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005677 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005678 // The user probably just forgot the 'inline', so suggest that it
5679 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005680 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005681 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5682 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005683 Diag(Loc, diag::err_inline_namespace_mismatch)
5684 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005685 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005686 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5687
5688 IsInline = PrevNS->isInline();
5689 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005690 } else if (PrevDecl) {
5691 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005692 Diag(Loc, diag::err_redefinition_different_kind)
5693 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005694 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005695 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005696 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005697 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005698 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005699 // This is the first "real" definition of the namespace "std", so update
5700 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005701 PrevNS = getStdNamespace();
5702 IsStd = true;
5703 AddToKnown = !IsInline;
5704 } else {
5705 // We've seen this namespace for the first time.
5706 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005707 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005708 } else {
John McCall9aeed322009-10-01 00:25:31 +00005709 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005710
5711 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005712 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005713 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005714 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005715 } else {
5716 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005717 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005718 }
5719
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005720 if (PrevNS && IsInline != PrevNS->isInline()) {
5721 // inline-ness must match
5722 Diag(Loc, diag::err_inline_namespace_mismatch)
5723 << IsInline;
5724 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005725
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005726 // Recover by ignoring the new namespace's inline status.
5727 IsInline = PrevNS->isInline();
5728 }
5729 }
5730
5731 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5732 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005733 if (IsInvalid)
5734 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005735
5736 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005737
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005738 // FIXME: Should we be merging attributes?
5739 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005740 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005741
5742 if (IsStd)
5743 StdNamespace = Namespc;
5744 if (AddToKnown)
5745 KnownNamespaces[Namespc] = false;
5746
5747 if (II) {
5748 PushOnScopeChains(Namespc, DeclRegionScope);
5749 } else {
5750 // Link the anonymous namespace into its parent.
5751 DeclContext *Parent = CurContext->getRedeclContext();
5752 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5753 TU->setAnonymousNamespace(Namespc);
5754 } else {
5755 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005756 }
John McCall9aeed322009-10-01 00:25:31 +00005757
Douglas Gregora4181472010-03-24 00:46:35 +00005758 CurContext->addDecl(Namespc);
5759
John McCall9aeed322009-10-01 00:25:31 +00005760 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5761 // behaves as if it were replaced by
5762 // namespace unique { /* empty body */ }
5763 // using namespace unique;
5764 // namespace unique { namespace-body }
5765 // where all occurrences of 'unique' in a translation unit are
5766 // replaced by the same identifier and this identifier differs
5767 // from all other identifiers in the entire program.
5768
5769 // We just create the namespace with an empty name and then add an
5770 // implicit using declaration, just like the standard suggests.
5771 //
5772 // CodeGen enforces the "universally unique" aspect by giving all
5773 // declarations semantically contained within an anonymous
5774 // namespace internal linkage.
5775
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005776 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005777 UsingDirectiveDecl* UD
5778 = UsingDirectiveDecl::Create(Context, CurContext,
5779 /* 'using' */ LBrace,
5780 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005781 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005782 /* identifier */ SourceLocation(),
5783 Namespc,
5784 /* Ancestor */ CurContext);
5785 UD->setImplicit();
5786 CurContext->addDecl(UD);
5787 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005788 }
5789
5790 // Although we could have an invalid decl (i.e. the namespace name is a
5791 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005792 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5793 // for the namespace has the declarations that showed up in that particular
5794 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005795 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005796 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005797}
5798
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005799/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5800/// is a namespace alias, returns the namespace it points to.
5801static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5802 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5803 return AD->getNamespace();
5804 return dyn_cast_or_null<NamespaceDecl>(D);
5805}
5806
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005807/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5808/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005809void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005810 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5811 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005812 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005813 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005814 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005815 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005816}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005817
John McCall384aff82010-08-25 07:42:41 +00005818CXXRecordDecl *Sema::getStdBadAlloc() const {
5819 return cast_or_null<CXXRecordDecl>(
5820 StdBadAlloc.get(Context.getExternalSource()));
5821}
5822
5823NamespaceDecl *Sema::getStdNamespace() const {
5824 return cast_or_null<NamespaceDecl>(
5825 StdNamespace.get(Context.getExternalSource()));
5826}
5827
Douglas Gregor66992202010-06-29 17:53:46 +00005828/// \brief Retrieve the special "std" namespace, which may require us to
5829/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005830NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005831 if (!StdNamespace) {
5832 // The "std" namespace has not yet been defined, so build one implicitly.
5833 StdNamespace = NamespaceDecl::Create(Context,
5834 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005835 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005836 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005837 &PP.getIdentifierTable().get("std"),
5838 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005839 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005840 }
5841
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005842 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005843}
5844
Sebastian Redl395e04d2012-01-17 22:49:33 +00005845bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5846 assert(getLangOptions().CPlusPlus &&
5847 "Looking for std::initializer_list outside of C++.");
5848
5849 // We're looking for implicit instantiations of
5850 // template <typename E> class std::initializer_list.
5851
5852 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5853 return false;
5854
Sebastian Redl84760e32012-01-17 22:49:58 +00005855 ClassTemplateDecl *Template = 0;
5856 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005857
Sebastian Redl84760e32012-01-17 22:49:58 +00005858 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005859
Sebastian Redl84760e32012-01-17 22:49:58 +00005860 ClassTemplateSpecializationDecl *Specialization =
5861 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5862 if (!Specialization)
5863 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005864
Sebastian Redl84760e32012-01-17 22:49:58 +00005865 Template = Specialization->getSpecializedTemplate();
5866 Arguments = Specialization->getTemplateArgs().data();
5867 } else if (const TemplateSpecializationType *TST =
5868 Ty->getAs<TemplateSpecializationType>()) {
5869 Template = dyn_cast_or_null<ClassTemplateDecl>(
5870 TST->getTemplateName().getAsTemplateDecl());
5871 Arguments = TST->getArgs();
5872 }
5873 if (!Template)
5874 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005875
5876 if (!StdInitializerList) {
5877 // Haven't recognized std::initializer_list yet, maybe this is it.
5878 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5879 if (TemplateClass->getIdentifier() !=
5880 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005881 !getStdNamespace()->InEnclosingNamespaceSetOf(
5882 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005883 return false;
5884 // This is a template called std::initializer_list, but is it the right
5885 // template?
5886 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005887 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005888 return false;
5889 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5890 return false;
5891
5892 // It's the right template.
5893 StdInitializerList = Template;
5894 }
5895
5896 if (Template != StdInitializerList)
5897 return false;
5898
5899 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005900 if (Element)
5901 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005902 return true;
5903}
5904
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005905static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5906 NamespaceDecl *Std = S.getStdNamespace();
5907 if (!Std) {
5908 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5909 return 0;
5910 }
5911
5912 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5913 Loc, Sema::LookupOrdinaryName);
5914 if (!S.LookupQualifiedName(Result, Std)) {
5915 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5916 return 0;
5917 }
5918 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5919 if (!Template) {
5920 Result.suppressDiagnostics();
5921 // We found something weird. Complain about the first thing we found.
5922 NamedDecl *Found = *Result.begin();
5923 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5924 return 0;
5925 }
5926
5927 // We found some template called std::initializer_list. Now verify that it's
5928 // correct.
5929 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005930 if (Params->getMinRequiredArguments() != 1 ||
5931 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005932 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5933 return 0;
5934 }
5935
5936 return Template;
5937}
5938
5939QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5940 if (!StdInitializerList) {
5941 StdInitializerList = LookupStdInitializerList(*this, Loc);
5942 if (!StdInitializerList)
5943 return QualType();
5944 }
5945
5946 TemplateArgumentListInfo Args(Loc, Loc);
5947 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5948 Context.getTrivialTypeSourceInfo(Element,
5949 Loc)));
5950 return Context.getCanonicalType(
5951 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5952}
5953
Sebastian Redl98d36062012-01-17 22:50:14 +00005954bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5955 // C++ [dcl.init.list]p2:
5956 // A constructor is an initializer-list constructor if its first parameter
5957 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5958 // std::initializer_list<E> for some type E, and either there are no other
5959 // parameters or else all other parameters have default arguments.
5960 if (Ctor->getNumParams() < 1 ||
5961 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5962 return false;
5963
5964 QualType ArgType = Ctor->getParamDecl(0)->getType();
5965 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5966 ArgType = RT->getPointeeType().getUnqualifiedType();
5967
5968 return isStdInitializerList(ArgType, 0);
5969}
5970
Douglas Gregor9172aa62011-03-26 22:25:30 +00005971/// \brief Determine whether a using statement is in a context where it will be
5972/// apply in all contexts.
5973static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5974 switch (CurContext->getDeclKind()) {
5975 case Decl::TranslationUnit:
5976 return true;
5977 case Decl::LinkageSpec:
5978 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5979 default:
5980 return false;
5981 }
5982}
5983
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005984namespace {
5985
5986// Callback to only accept typo corrections that are namespaces.
5987class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5988 public:
5989 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5990 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5991 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5992 }
5993 return false;
5994 }
5995};
5996
5997}
5998
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005999static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6000 CXXScopeSpec &SS,
6001 SourceLocation IdentLoc,
6002 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006003 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006004 R.clear();
6005 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006006 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006007 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006008 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
6009 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
6010 if (DeclContext *DC = S.computeDeclContext(SS, false))
6011 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6012 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6013 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6014 else
6015 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6016 << Ident << CorrectedQuotedStr
6017 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006018
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006019 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6020 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006021
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006022 Ident = Corrected.getCorrectionAsIdentifierInfo();
6023 R.addDecl(Corrected.getCorrectionDecl());
6024 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006025 }
6026 return false;
6027}
6028
John McCalld226f652010-08-21 09:40:31 +00006029Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006030 SourceLocation UsingLoc,
6031 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006032 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006033 SourceLocation IdentLoc,
6034 IdentifierInfo *NamespcName,
6035 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006036 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6037 assert(NamespcName && "Invalid NamespcName.");
6038 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006039
6040 // This can only happen along a recovery path.
6041 while (S->getFlags() & Scope::TemplateParamScope)
6042 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006043 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006044
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006045 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006046 NestedNameSpecifier *Qualifier = 0;
6047 if (SS.isSet())
6048 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6049
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006050 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006051 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6052 LookupParsedName(R, S, &SS);
6053 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006054 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006055
Douglas Gregor66992202010-06-29 17:53:46 +00006056 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006057 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006058 // Allow "using namespace std;" or "using namespace ::std;" even if
6059 // "std" hasn't been defined yet, for GCC compatibility.
6060 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6061 NamespcName->isStr("std")) {
6062 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006063 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006064 R.resolveKind();
6065 }
6066 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006067 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006068 }
6069
John McCallf36e02d2009-10-09 21:13:30 +00006070 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006071 NamedDecl *Named = R.getFoundDecl();
6072 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6073 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006074 // C++ [namespace.udir]p1:
6075 // A using-directive specifies that the names in the nominated
6076 // namespace can be used in the scope in which the
6077 // using-directive appears after the using-directive. During
6078 // unqualified name lookup (3.4.1), the names appear as if they
6079 // were declared in the nearest enclosing namespace which
6080 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006081 // namespace. [Note: in this context, "contains" means "contains
6082 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006083
6084 // Find enclosing context containing both using-directive and
6085 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006086 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006087 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6088 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6089 CommonAncestor = CommonAncestor->getParent();
6090
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006091 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006092 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006093 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006094
Douglas Gregor9172aa62011-03-26 22:25:30 +00006095 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006096 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006097 Diag(IdentLoc, diag::warn_using_directive_in_header);
6098 }
6099
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006100 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006101 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006102 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006103 }
6104
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006105 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006106 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006107}
6108
6109void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6110 // If scope has associated entity, then using directive is at namespace
6111 // or translation unit scope. We add UsingDirectiveDecls, into
6112 // it's lookup structure.
6113 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006114 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006115 else
6116 // Otherwise it is block-sope. using-directives will affect lookup
6117 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006118 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006119}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006120
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006121
John McCalld226f652010-08-21 09:40:31 +00006122Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006123 AccessSpecifier AS,
6124 bool HasUsingKeyword,
6125 SourceLocation UsingLoc,
6126 CXXScopeSpec &SS,
6127 UnqualifiedId &Name,
6128 AttributeList *AttrList,
6129 bool IsTypeName,
6130 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006131 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006132
Douglas Gregor12c118a2009-11-04 16:30:06 +00006133 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006134 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006135 case UnqualifiedId::IK_Identifier:
6136 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006137 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006138 case UnqualifiedId::IK_ConversionFunctionId:
6139 break;
6140
6141 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006142 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006143 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006144 Diag(Name.getSourceRange().getBegin(),
6145 getLangOptions().CPlusPlus0x ?
6146 diag::warn_cxx98_compat_using_decl_constructor :
6147 diag::err_using_decl_constructor)
6148 << SS.getRange();
6149
John McCall604e7f12009-12-08 07:46:18 +00006150 if (getLangOptions().CPlusPlus0x) break;
6151
John McCalld226f652010-08-21 09:40:31 +00006152 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006153
6154 case UnqualifiedId::IK_DestructorName:
6155 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6156 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006157 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006158
6159 case UnqualifiedId::IK_TemplateId:
6160 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6161 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006162 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006163 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006164
6165 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6166 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006167 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006168 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006169
John McCall60fa3cf2009-12-11 02:10:03 +00006170 // Warn about using declarations.
6171 // TODO: store that the declaration was written without 'using' and
6172 // talk about access decls instead of using decls in the
6173 // diagnostics.
6174 if (!HasUsingKeyword) {
6175 UsingLoc = Name.getSourceRange().getBegin();
6176
6177 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006178 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006179 }
6180
Douglas Gregor56c04582010-12-16 00:46:58 +00006181 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6182 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6183 return 0;
6184
John McCall9488ea12009-11-17 05:59:44 +00006185 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006186 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006187 /* IsInstantiation */ false,
6188 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006189 if (UD)
6190 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006191
John McCalld226f652010-08-21 09:40:31 +00006192 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006193}
6194
Douglas Gregor09acc982010-07-07 23:08:52 +00006195/// \brief Determine whether a using declaration considers the given
6196/// declarations as "equivalent", e.g., if they are redeclarations of
6197/// the same entity or are both typedefs of the same type.
6198static bool
6199IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6200 bool &SuppressRedeclaration) {
6201 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6202 SuppressRedeclaration = false;
6203 return true;
6204 }
6205
Richard Smith162e1c12011-04-15 14:24:37 +00006206 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6207 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006208 SuppressRedeclaration = true;
6209 return Context.hasSameType(TD1->getUnderlyingType(),
6210 TD2->getUnderlyingType());
6211 }
6212
6213 return false;
6214}
6215
6216
John McCall9f54ad42009-12-10 09:41:52 +00006217/// Determines whether to create a using shadow decl for a particular
6218/// decl, given the set of decls existing prior to this using lookup.
6219bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6220 const LookupResult &Previous) {
6221 // Diagnose finding a decl which is not from a base class of the
6222 // current class. We do this now because there are cases where this
6223 // function will silently decide not to build a shadow decl, which
6224 // will pre-empt further diagnostics.
6225 //
6226 // We don't need to do this in C++0x because we do the check once on
6227 // the qualifier.
6228 //
6229 // FIXME: diagnose the following if we care enough:
6230 // struct A { int foo; };
6231 // struct B : A { using A::foo; };
6232 // template <class T> struct C : A {};
6233 // template <class T> struct D : C<T> { using B::foo; } // <---
6234 // This is invalid (during instantiation) in C++03 because B::foo
6235 // resolves to the using decl in B, which is not a base class of D<T>.
6236 // We can't diagnose it immediately because C<T> is an unknown
6237 // specialization. The UsingShadowDecl in D<T> then points directly
6238 // to A::foo, which will look well-formed when we instantiate.
6239 // The right solution is to not collapse the shadow-decl chain.
6240 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6241 DeclContext *OrigDC = Orig->getDeclContext();
6242
6243 // Handle enums and anonymous structs.
6244 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6245 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6246 while (OrigRec->isAnonymousStructOrUnion())
6247 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6248
6249 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6250 if (OrigDC == CurContext) {
6251 Diag(Using->getLocation(),
6252 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006253 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006254 Diag(Orig->getLocation(), diag::note_using_decl_target);
6255 return true;
6256 }
6257
Douglas Gregordc355712011-02-25 00:36:19 +00006258 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006259 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006260 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006261 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006262 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006263 Diag(Orig->getLocation(), diag::note_using_decl_target);
6264 return true;
6265 }
6266 }
6267
6268 if (Previous.empty()) return false;
6269
6270 NamedDecl *Target = Orig;
6271 if (isa<UsingShadowDecl>(Target))
6272 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6273
John McCalld7533ec2009-12-11 02:33:26 +00006274 // If the target happens to be one of the previous declarations, we
6275 // don't have a conflict.
6276 //
6277 // FIXME: but we might be increasing its access, in which case we
6278 // should redeclare it.
6279 NamedDecl *NonTag = 0, *Tag = 0;
6280 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6281 I != E; ++I) {
6282 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006283 bool Result;
6284 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6285 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006286
6287 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6288 }
6289
John McCall9f54ad42009-12-10 09:41:52 +00006290 if (Target->isFunctionOrFunctionTemplate()) {
6291 FunctionDecl *FD;
6292 if (isa<FunctionTemplateDecl>(Target))
6293 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6294 else
6295 FD = cast<FunctionDecl>(Target);
6296
6297 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006298 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006299 case Ovl_Overload:
6300 return false;
6301
6302 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006303 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006304 break;
6305
6306 // We found a decl with the exact signature.
6307 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006308 // If we're in a record, we want to hide the target, so we
6309 // return true (without a diagnostic) to tell the caller not to
6310 // build a shadow decl.
6311 if (CurContext->isRecord())
6312 return true;
6313
6314 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006315 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006316 break;
6317 }
6318
6319 Diag(Target->getLocation(), diag::note_using_decl_target);
6320 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6321 return true;
6322 }
6323
6324 // Target is not a function.
6325
John McCall9f54ad42009-12-10 09:41:52 +00006326 if (isa<TagDecl>(Target)) {
6327 // No conflict between a tag and a non-tag.
6328 if (!Tag) return false;
6329
John McCall41ce66f2009-12-10 19:51:03 +00006330 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006331 Diag(Target->getLocation(), diag::note_using_decl_target);
6332 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6333 return true;
6334 }
6335
6336 // No conflict between a tag and a non-tag.
6337 if (!NonTag) return false;
6338
John McCall41ce66f2009-12-10 19:51:03 +00006339 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006340 Diag(Target->getLocation(), diag::note_using_decl_target);
6341 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6342 return true;
6343}
6344
John McCall9488ea12009-11-17 05:59:44 +00006345/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006346UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006347 UsingDecl *UD,
6348 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006349
6350 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006351 NamedDecl *Target = Orig;
6352 if (isa<UsingShadowDecl>(Target)) {
6353 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6354 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006355 }
6356
6357 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006358 = UsingShadowDecl::Create(Context, CurContext,
6359 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006360 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006361
6362 Shadow->setAccess(UD->getAccess());
6363 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6364 Shadow->setInvalidDecl();
6365
John McCall9488ea12009-11-17 05:59:44 +00006366 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006367 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006368 else
John McCall604e7f12009-12-08 07:46:18 +00006369 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006370
John McCall604e7f12009-12-08 07:46:18 +00006371
John McCall9f54ad42009-12-10 09:41:52 +00006372 return Shadow;
6373}
John McCall604e7f12009-12-08 07:46:18 +00006374
John McCall9f54ad42009-12-10 09:41:52 +00006375/// Hides a using shadow declaration. This is required by the current
6376/// using-decl implementation when a resolvable using declaration in a
6377/// class is followed by a declaration which would hide or override
6378/// one or more of the using decl's targets; for example:
6379///
6380/// struct Base { void foo(int); };
6381/// struct Derived : Base {
6382/// using Base::foo;
6383/// void foo(int);
6384/// };
6385///
6386/// The governing language is C++03 [namespace.udecl]p12:
6387///
6388/// When a using-declaration brings names from a base class into a
6389/// derived class scope, member functions in the derived class
6390/// override and/or hide member functions with the same name and
6391/// parameter types in a base class (rather than conflicting).
6392///
6393/// There are two ways to implement this:
6394/// (1) optimistically create shadow decls when they're not hidden
6395/// by existing declarations, or
6396/// (2) don't create any shadow decls (or at least don't make them
6397/// visible) until we've fully parsed/instantiated the class.
6398/// The problem with (1) is that we might have to retroactively remove
6399/// a shadow decl, which requires several O(n) operations because the
6400/// decl structures are (very reasonably) not designed for removal.
6401/// (2) avoids this but is very fiddly and phase-dependent.
6402void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006403 if (Shadow->getDeclName().getNameKind() ==
6404 DeclarationName::CXXConversionFunctionName)
6405 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6406
John McCall9f54ad42009-12-10 09:41:52 +00006407 // Remove it from the DeclContext...
6408 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006409
John McCall9f54ad42009-12-10 09:41:52 +00006410 // ...and the scope, if applicable...
6411 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006412 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006413 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006414 }
6415
John McCall9f54ad42009-12-10 09:41:52 +00006416 // ...and the using decl.
6417 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6418
6419 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006420 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006421}
6422
John McCall7ba107a2009-11-18 02:36:19 +00006423/// Builds a using declaration.
6424///
6425/// \param IsInstantiation - Whether this call arises from an
6426/// instantiation of an unresolved using declaration. We treat
6427/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006428NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6429 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006430 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006431 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006432 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006433 bool IsInstantiation,
6434 bool IsTypeName,
6435 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006436 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006437 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006438 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006439
Anders Carlsson550b14b2009-08-28 05:49:21 +00006440 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006441
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006442 if (SS.isEmpty()) {
6443 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006444 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006445 }
Mike Stump1eb44332009-09-09 15:08:12 +00006446
John McCall9f54ad42009-12-10 09:41:52 +00006447 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006448 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006449 ForRedeclaration);
6450 Previous.setHideTags(false);
6451 if (S) {
6452 LookupName(Previous, S);
6453
6454 // It is really dumb that we have to do this.
6455 LookupResult::Filter F = Previous.makeFilter();
6456 while (F.hasNext()) {
6457 NamedDecl *D = F.next();
6458 if (!isDeclInScope(D, CurContext, S))
6459 F.erase();
6460 }
6461 F.done();
6462 } else {
6463 assert(IsInstantiation && "no scope in non-instantiation");
6464 assert(CurContext->isRecord() && "scope not record in instantiation");
6465 LookupQualifiedName(Previous, CurContext);
6466 }
6467
John McCall9f54ad42009-12-10 09:41:52 +00006468 // Check for invalid redeclarations.
6469 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6470 return 0;
6471
6472 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006473 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6474 return 0;
6475
John McCallaf8e6ed2009-11-12 03:15:40 +00006476 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006477 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006478 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006479 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006480 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006481 // FIXME: not all declaration name kinds are legal here
6482 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6483 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006484 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006485 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006486 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006487 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6488 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006489 }
John McCalled976492009-12-04 22:46:56 +00006490 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006491 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6492 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006493 }
John McCalled976492009-12-04 22:46:56 +00006494 D->setAccess(AS);
6495 CurContext->addDecl(D);
6496
6497 if (!LookupContext) return D;
6498 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006499
John McCall77bb1aa2010-05-01 00:40:08 +00006500 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006501 UD->setInvalidDecl();
6502 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006503 }
6504
Sebastian Redlf677ea32011-02-05 19:23:19 +00006505 // Constructor inheriting using decls get special treatment.
6506 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006507 if (CheckInheritedConstructorUsingDecl(UD))
6508 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006509 return UD;
6510 }
6511
6512 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006513
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006514 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006515
John McCall604e7f12009-12-08 07:46:18 +00006516 // Unlike most lookups, we don't always want to hide tag
6517 // declarations: tag names are visible through the using declaration
6518 // even if hidden by ordinary names, *except* in a dependent context
6519 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006520 if (!IsInstantiation)
6521 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006522
John McCalla24dc2e2009-11-17 02:14:36 +00006523 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006524
John McCallf36e02d2009-10-09 21:13:30 +00006525 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006526 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006527 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006528 UD->setInvalidDecl();
6529 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006530 }
6531
John McCalled976492009-12-04 22:46:56 +00006532 if (R.isAmbiguous()) {
6533 UD->setInvalidDecl();
6534 return UD;
6535 }
Mike Stump1eb44332009-09-09 15:08:12 +00006536
John McCall7ba107a2009-11-18 02:36:19 +00006537 if (IsTypeName) {
6538 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006539 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006540 Diag(IdentLoc, diag::err_using_typename_non_type);
6541 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6542 Diag((*I)->getUnderlyingDecl()->getLocation(),
6543 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006544 UD->setInvalidDecl();
6545 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006546 }
6547 } else {
6548 // If we asked for a non-typename and we got a type, error out,
6549 // but only if this is an instantiation of an unresolved using
6550 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006551 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006552 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6553 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006554 UD->setInvalidDecl();
6555 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006556 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006557 }
6558
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006559 // C++0x N2914 [namespace.udecl]p6:
6560 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006561 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006562 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6563 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006564 UD->setInvalidDecl();
6565 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006566 }
Mike Stump1eb44332009-09-09 15:08:12 +00006567
John McCall9f54ad42009-12-10 09:41:52 +00006568 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6569 if (!CheckUsingShadowDecl(UD, *I, Previous))
6570 BuildUsingShadowDecl(S, UD, *I);
6571 }
John McCall9488ea12009-11-17 05:59:44 +00006572
6573 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006574}
6575
Sebastian Redlf677ea32011-02-05 19:23:19 +00006576/// Additional checks for a using declaration referring to a constructor name.
6577bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6578 if (UD->isTypeName()) {
6579 // FIXME: Cannot specify typename when specifying constructor
6580 return true;
6581 }
6582
Douglas Gregordc355712011-02-25 00:36:19 +00006583 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006584 assert(SourceType &&
6585 "Using decl naming constructor doesn't have type in scope spec.");
6586 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6587
6588 // Check whether the named type is a direct base class.
6589 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6590 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6591 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6592 BaseIt != BaseE; ++BaseIt) {
6593 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6594 if (CanonicalSourceType == BaseType)
6595 break;
6596 }
6597
6598 if (BaseIt == BaseE) {
6599 // Did not find SourceType in the bases.
6600 Diag(UD->getUsingLocation(),
6601 diag::err_using_decl_constructor_not_in_direct_base)
6602 << UD->getNameInfo().getSourceRange()
6603 << QualType(SourceType, 0) << TargetClass;
6604 return true;
6605 }
6606
6607 BaseIt->setInheritConstructors();
6608
6609 return false;
6610}
6611
John McCall9f54ad42009-12-10 09:41:52 +00006612/// Checks that the given using declaration is not an invalid
6613/// redeclaration. Note that this is checking only for the using decl
6614/// itself, not for any ill-formedness among the UsingShadowDecls.
6615bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6616 bool isTypeName,
6617 const CXXScopeSpec &SS,
6618 SourceLocation NameLoc,
6619 const LookupResult &Prev) {
6620 // C++03 [namespace.udecl]p8:
6621 // C++0x [namespace.udecl]p10:
6622 // A using-declaration is a declaration and can therefore be used
6623 // repeatedly where (and only where) multiple declarations are
6624 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006625 //
John McCall8a726212010-11-29 18:01:58 +00006626 // That's in non-member contexts.
6627 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006628 return false;
6629
6630 NestedNameSpecifier *Qual
6631 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6632
6633 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6634 NamedDecl *D = *I;
6635
6636 bool DTypename;
6637 NestedNameSpecifier *DQual;
6638 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6639 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006640 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006641 } else if (UnresolvedUsingValueDecl *UD
6642 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6643 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006644 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006645 } else if (UnresolvedUsingTypenameDecl *UD
6646 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6647 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006648 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006649 } else continue;
6650
6651 // using decls differ if one says 'typename' and the other doesn't.
6652 // FIXME: non-dependent using decls?
6653 if (isTypeName != DTypename) continue;
6654
6655 // using decls differ if they name different scopes (but note that
6656 // template instantiation can cause this check to trigger when it
6657 // didn't before instantiation).
6658 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6659 Context.getCanonicalNestedNameSpecifier(DQual))
6660 continue;
6661
6662 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006663 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006664 return true;
6665 }
6666
6667 return false;
6668}
6669
John McCall604e7f12009-12-08 07:46:18 +00006670
John McCalled976492009-12-04 22:46:56 +00006671/// Checks that the given nested-name qualifier used in a using decl
6672/// in the current context is appropriately related to the current
6673/// scope. If an error is found, diagnoses it and returns true.
6674bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6675 const CXXScopeSpec &SS,
6676 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006677 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006678
John McCall604e7f12009-12-08 07:46:18 +00006679 if (!CurContext->isRecord()) {
6680 // C++03 [namespace.udecl]p3:
6681 // C++0x [namespace.udecl]p8:
6682 // A using-declaration for a class member shall be a member-declaration.
6683
6684 // If we weren't able to compute a valid scope, it must be a
6685 // dependent class scope.
6686 if (!NamedContext || NamedContext->isRecord()) {
6687 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6688 << SS.getRange();
6689 return true;
6690 }
6691
6692 // Otherwise, everything is known to be fine.
6693 return false;
6694 }
6695
6696 // The current scope is a record.
6697
6698 // If the named context is dependent, we can't decide much.
6699 if (!NamedContext) {
6700 // FIXME: in C++0x, we can diagnose if we can prove that the
6701 // nested-name-specifier does not refer to a base class, which is
6702 // still possible in some cases.
6703
6704 // Otherwise we have to conservatively report that things might be
6705 // okay.
6706 return false;
6707 }
6708
6709 if (!NamedContext->isRecord()) {
6710 // Ideally this would point at the last name in the specifier,
6711 // but we don't have that level of source info.
6712 Diag(SS.getRange().getBegin(),
6713 diag::err_using_decl_nested_name_specifier_is_not_class)
6714 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6715 return true;
6716 }
6717
Douglas Gregor6fb07292010-12-21 07:41:49 +00006718 if (!NamedContext->isDependentContext() &&
6719 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6720 return true;
6721
John McCall604e7f12009-12-08 07:46:18 +00006722 if (getLangOptions().CPlusPlus0x) {
6723 // C++0x [namespace.udecl]p3:
6724 // In a using-declaration used as a member-declaration, the
6725 // nested-name-specifier shall name a base class of the class
6726 // being defined.
6727
6728 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6729 cast<CXXRecordDecl>(NamedContext))) {
6730 if (CurContext == NamedContext) {
6731 Diag(NameLoc,
6732 diag::err_using_decl_nested_name_specifier_is_current_class)
6733 << SS.getRange();
6734 return true;
6735 }
6736
6737 Diag(SS.getRange().getBegin(),
6738 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6739 << (NestedNameSpecifier*) SS.getScopeRep()
6740 << cast<CXXRecordDecl>(CurContext)
6741 << SS.getRange();
6742 return true;
6743 }
6744
6745 return false;
6746 }
6747
6748 // C++03 [namespace.udecl]p4:
6749 // A using-declaration used as a member-declaration shall refer
6750 // to a member of a base class of the class being defined [etc.].
6751
6752 // Salient point: SS doesn't have to name a base class as long as
6753 // lookup only finds members from base classes. Therefore we can
6754 // diagnose here only if we can prove that that can't happen,
6755 // i.e. if the class hierarchies provably don't intersect.
6756
6757 // TODO: it would be nice if "definitely valid" results were cached
6758 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6759 // need to be repeated.
6760
6761 struct UserData {
6762 llvm::DenseSet<const CXXRecordDecl*> Bases;
6763
6764 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6765 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6766 Data->Bases.insert(Base);
6767 return true;
6768 }
6769
6770 bool hasDependentBases(const CXXRecordDecl *Class) {
6771 return !Class->forallBases(collect, this);
6772 }
6773
6774 /// Returns true if the base is dependent or is one of the
6775 /// accumulated base classes.
6776 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6777 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6778 return !Data->Bases.count(Base);
6779 }
6780
6781 bool mightShareBases(const CXXRecordDecl *Class) {
6782 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6783 }
6784 };
6785
6786 UserData Data;
6787
6788 // Returns false if we find a dependent base.
6789 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6790 return false;
6791
6792 // Returns false if the class has a dependent base or if it or one
6793 // of its bases is present in the base set of the current context.
6794 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6795 return false;
6796
6797 Diag(SS.getRange().getBegin(),
6798 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6799 << (NestedNameSpecifier*) SS.getScopeRep()
6800 << cast<CXXRecordDecl>(CurContext)
6801 << SS.getRange();
6802
6803 return true;
John McCalled976492009-12-04 22:46:56 +00006804}
6805
Richard Smith162e1c12011-04-15 14:24:37 +00006806Decl *Sema::ActOnAliasDeclaration(Scope *S,
6807 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006808 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006809 SourceLocation UsingLoc,
6810 UnqualifiedId &Name,
6811 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006812 // Skip up to the relevant declaration scope.
6813 while (S->getFlags() & Scope::TemplateParamScope)
6814 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006815 assert((S->getFlags() & Scope::DeclScope) &&
6816 "got alias-declaration outside of declaration scope");
6817
6818 if (Type.isInvalid())
6819 return 0;
6820
6821 bool Invalid = false;
6822 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6823 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006824 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006825
6826 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6827 return 0;
6828
6829 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006830 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006831 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006832 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6833 TInfo->getTypeLoc().getBeginLoc());
6834 }
Richard Smith162e1c12011-04-15 14:24:37 +00006835
6836 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6837 LookupName(Previous, S);
6838
6839 // Warn about shadowing the name of a template parameter.
6840 if (Previous.isSingleResult() &&
6841 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006842 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006843 Previous.clear();
6844 }
6845
6846 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6847 "name in alias declaration must be an identifier");
6848 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6849 Name.StartLocation,
6850 Name.Identifier, TInfo);
6851
6852 NewTD->setAccess(AS);
6853
6854 if (Invalid)
6855 NewTD->setInvalidDecl();
6856
Richard Smith3e4c6c42011-05-05 21:57:07 +00006857 CheckTypedefForVariablyModifiedType(S, NewTD);
6858 Invalid |= NewTD->isInvalidDecl();
6859
Richard Smith162e1c12011-04-15 14:24:37 +00006860 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006861
6862 NamedDecl *NewND;
6863 if (TemplateParamLists.size()) {
6864 TypeAliasTemplateDecl *OldDecl = 0;
6865 TemplateParameterList *OldTemplateParams = 0;
6866
6867 if (TemplateParamLists.size() != 1) {
6868 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6869 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6870 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6871 }
6872 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6873
6874 // Only consider previous declarations in the same scope.
6875 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6876 /*ExplicitInstantiationOrSpecialization*/false);
6877 if (!Previous.empty()) {
6878 Redeclaration = true;
6879
6880 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6881 if (!OldDecl && !Invalid) {
6882 Diag(UsingLoc, diag::err_redefinition_different_kind)
6883 << Name.Identifier;
6884
6885 NamedDecl *OldD = Previous.getRepresentativeDecl();
6886 if (OldD->getLocation().isValid())
6887 Diag(OldD->getLocation(), diag::note_previous_definition);
6888
6889 Invalid = true;
6890 }
6891
6892 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6893 if (TemplateParameterListsAreEqual(TemplateParams,
6894 OldDecl->getTemplateParameters(),
6895 /*Complain=*/true,
6896 TPL_TemplateMatch))
6897 OldTemplateParams = OldDecl->getTemplateParameters();
6898 else
6899 Invalid = true;
6900
6901 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6902 if (!Invalid &&
6903 !Context.hasSameType(OldTD->getUnderlyingType(),
6904 NewTD->getUnderlyingType())) {
6905 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6906 // but we can't reasonably accept it.
6907 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6908 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6909 if (OldTD->getLocation().isValid())
6910 Diag(OldTD->getLocation(), diag::note_previous_definition);
6911 Invalid = true;
6912 }
6913 }
6914 }
6915
6916 // Merge any previous default template arguments into our parameters,
6917 // and check the parameter list.
6918 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6919 TPC_TypeAliasTemplate))
6920 return 0;
6921
6922 TypeAliasTemplateDecl *NewDecl =
6923 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6924 Name.Identifier, TemplateParams,
6925 NewTD);
6926
6927 NewDecl->setAccess(AS);
6928
6929 if (Invalid)
6930 NewDecl->setInvalidDecl();
6931 else if (OldDecl)
6932 NewDecl->setPreviousDeclaration(OldDecl);
6933
6934 NewND = NewDecl;
6935 } else {
6936 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6937 NewND = NewTD;
6938 }
Richard Smith162e1c12011-04-15 14:24:37 +00006939
6940 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006941 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006942
Richard Smith3e4c6c42011-05-05 21:57:07 +00006943 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006944}
6945
John McCalld226f652010-08-21 09:40:31 +00006946Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006947 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006948 SourceLocation AliasLoc,
6949 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006950 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006951 SourceLocation IdentLoc,
6952 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006953
Anders Carlsson81c85c42009-03-28 23:53:49 +00006954 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006955 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6956 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006957
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006958 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006959 NamedDecl *PrevDecl
6960 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6961 ForRedeclaration);
6962 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6963 PrevDecl = 0;
6964
6965 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006966 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006967 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006968 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006969 // FIXME: At some point, we'll want to create the (redundant)
6970 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006971 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006972 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006973 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006974 }
Mike Stump1eb44332009-09-09 15:08:12 +00006975
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006976 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6977 diag::err_redefinition_different_kind;
6978 Diag(AliasLoc, DiagID) << Alias;
6979 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006980 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006981 }
6982
John McCalla24dc2e2009-11-17 02:14:36 +00006983 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006984 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006985
John McCallf36e02d2009-10-09 21:13:30 +00006986 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006987 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006988 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006989 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006990 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006991 }
Mike Stump1eb44332009-09-09 15:08:12 +00006992
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006993 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006994 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006995 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006996 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006997
John McCall3dbd3d52010-02-16 06:53:13 +00006998 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006999 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007000}
7001
Douglas Gregor39957dc2010-05-01 15:04:51 +00007002namespace {
7003 /// \brief Scoped object used to handle the state changes required in Sema
7004 /// to implicitly define the body of a C++ member function;
7005 class ImplicitlyDefinedFunctionScope {
7006 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00007007 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00007008
7009 public:
7010 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00007011 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00007012 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00007013 S.PushFunctionScope();
7014 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
7015 }
7016
7017 ~ImplicitlyDefinedFunctionScope() {
7018 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00007019 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00007020 }
7021 };
7022}
7023
Sean Hunt001cad92011-05-10 00:49:42 +00007024Sema::ImplicitExceptionSpecification
7025Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007026 // C++ [except.spec]p14:
7027 // An implicitly declared special member function (Clause 12) shall have an
7028 // exception-specification. [...]
7029 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007030 if (ClassDecl->isInvalidDecl())
7031 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007032
Sebastian Redl60618fa2011-03-12 11:50:43 +00007033 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007034 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7035 BEnd = ClassDecl->bases_end();
7036 B != BEnd; ++B) {
7037 if (B->isVirtual()) // Handled below.
7038 continue;
7039
Douglas Gregor18274032010-07-03 00:47:00 +00007040 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7041 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007042 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7043 // If this is a deleted function, add it anyway. This might be conformant
7044 // with the standard. This might not. I'm not sure. It might not matter.
7045 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007046 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007047 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007048 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007049
7050 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007051 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7052 BEnd = ClassDecl->vbases_end();
7053 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007054 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7055 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007056 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7057 // If this is a deleted function, add it anyway. This might be conformant
7058 // with the standard. This might not. I'm not sure. It might not matter.
7059 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007060 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007061 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007062 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007063
7064 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007065 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7066 FEnd = ClassDecl->field_end();
7067 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007068 if (F->hasInClassInitializer()) {
7069 if (Expr *E = F->getInClassInitializer())
7070 ExceptSpec.CalledExpr(E);
7071 else if (!F->isInvalidDecl())
7072 ExceptSpec.SetDelayed();
7073 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007074 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007075 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7076 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7077 // If this is a deleted function, add it anyway. This might be conformant
7078 // with the standard. This might not. I'm not sure. It might not matter.
7079 // In particular, the problem is that this function never gets called. It
7080 // might just be ill-formed because this function attempts to refer to
7081 // a deleted function here.
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 }
John McCalle23cf432010-12-14 08:05:40 +00007086
Sean Hunt001cad92011-05-10 00:49:42 +00007087 return ExceptSpec;
7088}
7089
7090CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7091 CXXRecordDecl *ClassDecl) {
7092 // C++ [class.ctor]p5:
7093 // A default constructor for a class X is a constructor of class X
7094 // that can be called without an argument. If there is no
7095 // user-declared constructor for class X, a default constructor is
7096 // implicitly declared. An implicitly-declared default constructor
7097 // is an inline public member of its class.
7098 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7099 "Should not build implicit default constructor!");
7100
7101 ImplicitExceptionSpecification Spec =
7102 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7103 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007104
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007105 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007106 CanQualType ClassType
7107 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007108 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007109 DeclarationName Name
7110 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007111 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007112 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7113 Context, ClassDecl, ClassLoc, NameInfo,
7114 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7115 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7116 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7117 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007118 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007119 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007120 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007121 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007122
7123 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007124 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7125
Douglas Gregor23c94db2010-07-02 17:43:08 +00007126 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007127 PushOnScopeChains(DefaultCon, S, false);
7128 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007129
Sean Hunte16da072011-10-10 06:18:57 +00007130 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007131 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007132
Douglas Gregor32df23e2010-07-01 22:02:46 +00007133 return DefaultCon;
7134}
7135
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007136void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7137 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007138 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007139 !Constructor->doesThisDeclarationHaveABody() &&
7140 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007141 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007142
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007143 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007144 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007145
Douglas Gregor39957dc2010-05-01 15:04:51 +00007146 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007147 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007148 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007149 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007150 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007151 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007152 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007153 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007154 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007155
7156 SourceLocation Loc = Constructor->getLocation();
7157 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7158
7159 Constructor->setUsed();
7160 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007161
7162 if (ASTMutationListener *L = getASTMutationListener()) {
7163 L->CompletedImplicitDefinition(Constructor);
7164 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007165}
7166
Richard Smith7a614d82011-06-11 17:19:42 +00007167/// Get any existing defaulted default constructor for the given class. Do not
7168/// implicitly define one if it does not exist.
7169static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7170 CXXRecordDecl *D) {
7171 ASTContext &Context = Self.Context;
7172 QualType ClassType = Context.getTypeDeclType(D);
7173 DeclarationName ConstructorName
7174 = Context.DeclarationNames.getCXXConstructorName(
7175 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7176
7177 DeclContext::lookup_const_iterator Con, ConEnd;
7178 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7179 Con != ConEnd; ++Con) {
7180 // A function template cannot be defaulted.
7181 if (isa<FunctionTemplateDecl>(*Con))
7182 continue;
7183
7184 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7185 if (Constructor->isDefaultConstructor())
7186 return Constructor->isDefaulted() ? Constructor : 0;
7187 }
7188 return 0;
7189}
7190
7191void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7192 if (!D) return;
7193 AdjustDeclIfTemplate(D);
7194
7195 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7196 CXXConstructorDecl *CtorDecl
7197 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7198
7199 if (!CtorDecl) return;
7200
7201 // Compute the exception specification for the default constructor.
7202 const FunctionProtoType *CtorTy =
7203 CtorDecl->getType()->castAs<FunctionProtoType>();
7204 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7205 ImplicitExceptionSpecification Spec =
7206 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7207 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7208 assert(EPI.ExceptionSpecType != EST_Delayed);
7209
7210 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7211 }
7212
7213 // If the default constructor is explicitly defaulted, checking the exception
7214 // specification is deferred until now.
7215 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7216 !ClassDecl->isDependentType())
7217 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7218}
7219
Sebastian Redlf677ea32011-02-05 19:23:19 +00007220void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7221 // We start with an initial pass over the base classes to collect those that
7222 // inherit constructors from. If there are none, we can forgo all further
7223 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007224 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007225 BasesVector BasesToInheritFrom;
7226 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7227 BaseE = ClassDecl->bases_end();
7228 BaseIt != BaseE; ++BaseIt) {
7229 if (BaseIt->getInheritConstructors()) {
7230 QualType Base = BaseIt->getType();
7231 if (Base->isDependentType()) {
7232 // If we inherit constructors from anything that is dependent, just
7233 // abort processing altogether. We'll get another chance for the
7234 // instantiations.
7235 return;
7236 }
7237 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7238 }
7239 }
7240 if (BasesToInheritFrom.empty())
7241 return;
7242
7243 // Now collect the constructors that we already have in the current class.
7244 // Those take precedence over inherited constructors.
7245 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7246 // unless there is a user-declared constructor with the same signature in
7247 // the class where the using-declaration appears.
7248 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7249 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7250 CtorE = ClassDecl->ctor_end();
7251 CtorIt != CtorE; ++CtorIt) {
7252 ExistingConstructors.insert(
7253 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7254 }
7255
7256 Scope *S = getScopeForContext(ClassDecl);
7257 DeclarationName CreatedCtorName =
7258 Context.DeclarationNames.getCXXConstructorName(
7259 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7260
7261 // Now comes the true work.
7262 // First, we keep a map from constructor types to the base that introduced
7263 // them. Needed for finding conflicting constructors. We also keep the
7264 // actually inserted declarations in there, for pretty diagnostics.
7265 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7266 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7267 ConstructorToSourceMap InheritedConstructors;
7268 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7269 BaseE = BasesToInheritFrom.end();
7270 BaseIt != BaseE; ++BaseIt) {
7271 const RecordType *Base = *BaseIt;
7272 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7273 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7274 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7275 CtorE = BaseDecl->ctor_end();
7276 CtorIt != CtorE; ++CtorIt) {
7277 // Find the using declaration for inheriting this base's constructors.
7278 DeclarationName Name =
7279 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7280 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7281 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7282 SourceLocation UsingLoc = UD ? UD->getLocation() :
7283 ClassDecl->getLocation();
7284
7285 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7286 // from the class X named in the using-declaration consists of actual
7287 // constructors and notional constructors that result from the
7288 // transformation of defaulted parameters as follows:
7289 // - all non-template default constructors of X, and
7290 // - for each non-template constructor of X that has at least one
7291 // parameter with a default argument, the set of constructors that
7292 // results from omitting any ellipsis parameter specification and
7293 // successively omitting parameters with a default argument from the
7294 // end of the parameter-type-list.
7295 CXXConstructorDecl *BaseCtor = *CtorIt;
7296 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7297 const FunctionProtoType *BaseCtorType =
7298 BaseCtor->getType()->getAs<FunctionProtoType>();
7299
7300 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7301 maxParams = BaseCtor->getNumParams();
7302 params <= maxParams; ++params) {
7303 // Skip default constructors. They're never inherited.
7304 if (params == 0)
7305 continue;
7306 // Skip copy and move constructors for the same reason.
7307 if (CanBeCopyOrMove && params == 1)
7308 continue;
7309
7310 // Build up a function type for this particular constructor.
7311 // FIXME: The working paper does not consider that the exception spec
7312 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007313 // source. This code doesn't yet, either. When it does, this code will
7314 // need to be delayed until after exception specifications and in-class
7315 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007316 const Type *NewCtorType;
7317 if (params == maxParams)
7318 NewCtorType = BaseCtorType;
7319 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007320 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007321 for (unsigned i = 0; i < params; ++i) {
7322 Args.push_back(BaseCtorType->getArgType(i));
7323 }
7324 FunctionProtoType::ExtProtoInfo ExtInfo =
7325 BaseCtorType->getExtProtoInfo();
7326 ExtInfo.Variadic = false;
7327 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7328 Args.data(), params, ExtInfo)
7329 .getTypePtr();
7330 }
7331 const Type *CanonicalNewCtorType =
7332 Context.getCanonicalType(NewCtorType);
7333
7334 // Now that we have the type, first check if the class already has a
7335 // constructor with this signature.
7336 if (ExistingConstructors.count(CanonicalNewCtorType))
7337 continue;
7338
7339 // Then we check if we have already declared an inherited constructor
7340 // with this signature.
7341 std::pair<ConstructorToSourceMap::iterator, bool> result =
7342 InheritedConstructors.insert(std::make_pair(
7343 CanonicalNewCtorType,
7344 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7345 if (!result.second) {
7346 // Already in the map. If it came from a different class, that's an
7347 // error. Not if it's from the same.
7348 CanQualType PreviousBase = result.first->second.first;
7349 if (CanonicalBase != PreviousBase) {
7350 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7351 const CXXConstructorDecl *PrevBaseCtor =
7352 PrevCtor->getInheritedConstructor();
7353 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7354
7355 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7356 Diag(BaseCtor->getLocation(),
7357 diag::note_using_decl_constructor_conflict_current_ctor);
7358 Diag(PrevBaseCtor->getLocation(),
7359 diag::note_using_decl_constructor_conflict_previous_ctor);
7360 Diag(PrevCtor->getLocation(),
7361 diag::note_using_decl_constructor_conflict_previous_using);
7362 }
7363 continue;
7364 }
7365
7366 // OK, we're there, now add the constructor.
7367 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007368 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007369 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7370 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007371 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7372 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007373 /*ImplicitlyDeclared=*/true,
7374 // FIXME: Due to a defect in the standard, we treat inherited
7375 // constructors as constexpr even if that makes them ill-formed.
7376 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007377 NewCtor->setAccess(BaseCtor->getAccess());
7378
7379 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007380 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007381 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007382 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7383 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007384 /*IdentifierInfo=*/0,
7385 BaseCtorType->getArgType(i),
7386 /*TInfo=*/0, SC_None,
7387 SC_None, /*DefaultArg=*/0));
7388 }
David Blaikie4278c652011-09-21 18:16:56 +00007389 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007390 NewCtor->setInheritedConstructor(BaseCtor);
7391
7392 PushOnScopeChains(NewCtor, S, false);
7393 ClassDecl->addDecl(NewCtor);
7394 result.first->second.second = NewCtor;
7395 }
7396 }
7397 }
7398}
7399
Sean Huntcb45a0f2011-05-12 22:46:25 +00007400Sema::ImplicitExceptionSpecification
7401Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007402 // C++ [except.spec]p14:
7403 // An implicitly declared special member function (Clause 12) shall have
7404 // an exception-specification.
7405 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007406 if (ClassDecl->isInvalidDecl())
7407 return ExceptSpec;
7408
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007409 // Direct base-class destructors.
7410 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7411 BEnd = ClassDecl->bases_end();
7412 B != BEnd; ++B) {
7413 if (B->isVirtual()) // Handled below.
7414 continue;
7415
7416 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7417 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007418 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007419 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007420
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007421 // Virtual base-class destructors.
7422 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7423 BEnd = ClassDecl->vbases_end();
7424 B != BEnd; ++B) {
7425 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7426 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007427 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007428 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007429
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007430 // Field destructors.
7431 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7432 FEnd = ClassDecl->field_end();
7433 F != FEnd; ++F) {
7434 if (const RecordType *RecordTy
7435 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7436 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007437 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007438 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007439
Sean Huntcb45a0f2011-05-12 22:46:25 +00007440 return ExceptSpec;
7441}
7442
7443CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7444 // C++ [class.dtor]p2:
7445 // If a class has no user-declared destructor, a destructor is
7446 // declared implicitly. An implicitly-declared destructor is an
7447 // inline public member of its class.
7448
7449 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007450 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007451 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7452
Douglas Gregor4923aa22010-07-02 20:37:36 +00007453 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007454 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007455
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007456 CanQualType ClassType
7457 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007458 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007459 DeclarationName Name
7460 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007461 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007462 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007463 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7464 /*isInline=*/true,
7465 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007466 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007467 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007468 Destructor->setImplicit();
7469 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007470
7471 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007472 ++ASTContext::NumImplicitDestructorsDeclared;
7473
7474 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007475 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007476 PushOnScopeChains(Destructor, S, false);
7477 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007478
7479 // This could be uniqued if it ever proves significant.
7480 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007481
7482 if (ShouldDeleteDestructor(Destructor))
7483 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007484
7485 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007486
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007487 return Destructor;
7488}
7489
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007490void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007491 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007492 assert((Destructor->isDefaulted() &&
7493 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007494 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007495 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007496 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007497
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007498 if (Destructor->isInvalidDecl())
7499 return;
7500
Douglas Gregor39957dc2010-05-01 15:04:51 +00007501 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007502
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007503 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007504 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7505 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007506
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007507 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007508 Diag(CurrentLocation, diag::note_member_synthesized_at)
7509 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7510
7511 Destructor->setInvalidDecl();
7512 return;
7513 }
7514
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007515 SourceLocation Loc = Destructor->getLocation();
7516 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007517 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007518 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007519 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007520
7521 if (ASTMutationListener *L = getASTMutationListener()) {
7522 L->CompletedImplicitDefinition(Destructor);
7523 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007524}
7525
Sebastian Redl0ee33912011-05-19 05:13:44 +00007526void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7527 CXXDestructorDecl *destructor) {
7528 // C++11 [class.dtor]p3:
7529 // A declaration of a destructor that does not have an exception-
7530 // specification is implicitly considered to have the same exception-
7531 // specification as an implicit declaration.
7532 const FunctionProtoType *dtorType = destructor->getType()->
7533 getAs<FunctionProtoType>();
7534 if (dtorType->hasExceptionSpec())
7535 return;
7536
7537 ImplicitExceptionSpecification exceptSpec =
7538 ComputeDefaultedDtorExceptionSpec(classDecl);
7539
Chandler Carruth3f224b22011-09-20 04:55:26 +00007540 // Replace the destructor's type, building off the existing one. Fortunately,
7541 // the only thing of interest in the destructor type is its extended info.
7542 // The return and arguments are fixed.
7543 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007544 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7545 epi.NumExceptions = exceptSpec.size();
7546 epi.Exceptions = exceptSpec.data();
7547 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7548
7549 destructor->setType(ty);
7550
7551 // FIXME: If the destructor has a body that could throw, and the newly created
7552 // spec doesn't allow exceptions, we should emit a warning, because this
7553 // change in behavior can break conforming C++03 programs at runtime.
7554 // However, we don't have a body yet, so it needs to be done somewhere else.
7555}
7556
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007557/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007558/// \c To.
7559///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007560/// This routine is used to copy/move the members of a class with an
7561/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007562/// copied are arrays, this routine builds for loops to copy them.
7563///
7564/// \param S The Sema object used for type-checking.
7565///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007566/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007567///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007568/// \param T The type of the expressions being copied/moved. Both expressions
7569/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007570///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007571/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007572///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007573/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007574///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007575/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007576/// Otherwise, it's a non-static member subobject.
7577///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007578/// \param Copying Whether we're copying or moving.
7579///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007580/// \param Depth Internal parameter recording the depth of the recursion.
7581///
7582/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007583static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007584BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007585 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007586 bool CopyingBaseSubobject, bool Copying,
7587 unsigned Depth = 0) {
7588 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007589 // Each subobject is assigned in the manner appropriate to its type:
7590 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007591 // - if the subobject is of class type, as if by a call to operator= with
7592 // the subobject as the object expression and the corresponding
7593 // subobject of x as a single function argument (as if by explicit
7594 // qualification; that is, ignoring any possible virtual overriding
7595 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007596 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7597 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7598
7599 // Look for operator=.
7600 DeclarationName Name
7601 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7602 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7603 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7604
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007605 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007606 LookupResult::Filter F = OpLookup.makeFilter();
7607 while (F.hasNext()) {
7608 NamedDecl *D = F.next();
7609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007610 if (Copying ? Method->isCopyAssignmentOperator() :
7611 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007612 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007613
Douglas Gregor06a9f362010-05-01 20:49:11 +00007614 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007615 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007616 F.done();
7617
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007618 // Suppress the protected check (C++ [class.protected]) for each of the
7619 // assignment operators we found. This strange dance is required when
7620 // we're assigning via a base classes's copy-assignment operator. To
7621 // ensure that we're getting the right base class subobject (without
7622 // ambiguities), we need to cast "this" to that subobject type; to
7623 // ensure that we don't go through the virtual call mechanism, we need
7624 // to qualify the operator= name with the base class (see below). However,
7625 // this means that if the base class has a protected copy assignment
7626 // operator, the protected member access check will fail. So, we
7627 // rewrite "protected" access to "public" access in this case, since we
7628 // know by construction that we're calling from a derived class.
7629 if (CopyingBaseSubobject) {
7630 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7631 L != LEnd; ++L) {
7632 if (L.getAccess() == AS_protected)
7633 L.setAccess(AS_public);
7634 }
7635 }
7636
Douglas Gregor06a9f362010-05-01 20:49:11 +00007637 // Create the nested-name-specifier that will be used to qualify the
7638 // reference to operator=; this is required to suppress the virtual
7639 // call mechanism.
7640 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007641 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007642 SS.MakeTrivial(S.Context,
7643 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007644 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007645 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007646
7647 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007648 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007649 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007650 /*TemplateKWLoc=*/SourceLocation(),
7651 /*FirstQualifierInScope=*/0,
7652 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007653 /*TemplateArgs=*/0,
7654 /*SuppressQualifierCheck=*/true);
7655 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007656 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007657
7658 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007659
John McCall60d7b3a2010-08-24 06:29:42 +00007660 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007661 OpEqualRef.takeAs<Expr>(),
7662 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007664 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007665
7666 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007667 }
John McCallb0207482010-03-16 06:11:48 +00007668
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669 // - if the subobject is of scalar type, the built-in assignment
7670 // operator is used.
7671 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7672 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007673 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007674 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007675 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007676
7677 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007678 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679
7680 // - if the subobject is an array, each element is assigned, in the
7681 // manner appropriate to the element type;
7682
7683 // Construct a loop over the array bounds, e.g.,
7684 //
7685 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7686 //
7687 // that will copy each of the array elements.
7688 QualType SizeType = S.Context.getSizeType();
7689
7690 // Create the iteration variable.
7691 IdentifierInfo *IterationVarName = 0;
7692 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007693 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007694 llvm::raw_svector_ostream OS(Str);
7695 OS << "__i" << Depth;
7696 IterationVarName = &S.Context.Idents.get(OS.str());
7697 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007698 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007699 IterationVarName, SizeType,
7700 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007701 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007702
7703 // Initialize the iteration variable to zero.
7704 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007705 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007706
7707 // Create a reference to the iteration variable; we'll use this several
7708 // times throughout.
7709 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007710 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007711 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007712 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7713 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7714
Douglas Gregor06a9f362010-05-01 20:49:11 +00007715 // Create the DeclStmt that holds the iteration variable.
7716 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7717
7718 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007719 llvm::APInt Upper
7720 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007721 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007722 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007723 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7724 BO_NE, S.Context.BoolTy,
7725 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007726
7727 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007728 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007729 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7730 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007731
7732 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007733 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007734 IterationVarRefRVal,
7735 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007736 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007737 IterationVarRefRVal,
7738 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007739 if (!Copying) // Cast to rvalue
7740 From = CastForMoving(S, From);
7741
7742 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007743 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7744 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007745 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007746 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007747 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007748
7749 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007750 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007751 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007752 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007753 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007754}
7755
Sean Hunt30de05c2011-05-14 05:23:20 +00007756std::pair<Sema::ImplicitExceptionSpecification, bool>
7757Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7758 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007759 if (ClassDecl->isInvalidDecl())
7760 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7761
Douglas Gregord3c35902010-07-01 16:36:15 +00007762 // C++ [class.copy]p10:
7763 // If the class definition does not explicitly declare a copy
7764 // assignment operator, one is declared implicitly.
7765 // The implicitly-defined copy assignment operator for a class X
7766 // will have the form
7767 //
7768 // X& X::operator=(const X&)
7769 //
7770 // if
7771 bool HasConstCopyAssignment = true;
7772
7773 // -- each direct base class B of X has a copy assignment operator
7774 // whose parameter is of type const B&, const volatile B& or B,
7775 // and
7776 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7777 BaseEnd = ClassDecl->bases_end();
7778 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007779 // We'll handle this below
7780 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7781 continue;
7782
Douglas Gregord3c35902010-07-01 16:36:15 +00007783 assert(!Base->getType()->isDependentType() &&
7784 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007785 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7786 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7787 &HasConstCopyAssignment);
7788 }
7789
Richard Smithebaf0e62011-10-18 20:49:44 +00007790 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007791 if (LangOpts.CPlusPlus0x) {
7792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7793 BaseEnd = ClassDecl->vbases_end();
7794 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7795 assert(!Base->getType()->isDependentType() &&
7796 "Cannot generate implicit members for class with dependent bases.");
7797 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7798 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7799 &HasConstCopyAssignment);
7800 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007801 }
7802
7803 // -- for all the nonstatic data members of X that are of a class
7804 // type M (or array thereof), each such class type has a copy
7805 // assignment operator whose parameter is of type const M&,
7806 // const volatile M& or M.
7807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7808 FieldEnd = ClassDecl->field_end();
7809 HasConstCopyAssignment && Field != FieldEnd;
7810 ++Field) {
7811 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007812 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7813 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7814 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007815 }
7816 }
7817
7818 // Otherwise, the implicitly declared copy assignment operator will
7819 // have the form
7820 //
7821 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007822
Douglas Gregorb87786f2010-07-01 17:48:08 +00007823 // C++ [except.spec]p14:
7824 // An implicitly declared special member function (Clause 12) shall have an
7825 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007826
7827 // It is unspecified whether or not an implicit copy assignment operator
7828 // attempts to deduplicate calls to assignment operators of virtual bases are
7829 // made. As such, this exception specification is effectively unspecified.
7830 // Based on a similar decision made for constness in C++0x, we're erring on
7831 // the side of assuming such calls to be made regardless of whether they
7832 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007833 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007834 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007835 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7836 BaseEnd = ClassDecl->bases_end();
7837 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007838 if (Base->isVirtual())
7839 continue;
7840
Douglas Gregora376d102010-07-02 21:50:04 +00007841 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007842 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007843 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7844 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007845 ExceptSpec.CalledDecl(CopyAssign);
7846 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007847
7848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7849 BaseEnd = ClassDecl->vbases_end();
7850 Base != BaseEnd; ++Base) {
7851 CXXRecordDecl *BaseClassDecl
7852 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7853 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7854 ArgQuals, false, 0))
7855 ExceptSpec.CalledDecl(CopyAssign);
7856 }
7857
Douglas Gregorb87786f2010-07-01 17:48:08 +00007858 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7859 FieldEnd = ClassDecl->field_end();
7860 Field != FieldEnd;
7861 ++Field) {
7862 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007863 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7864 if (CXXMethodDecl *CopyAssign =
7865 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7866 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007867 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007868 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007869
Sean Hunt30de05c2011-05-14 05:23:20 +00007870 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7871}
7872
7873CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7874 // Note: The following rules are largely analoguous to the copy
7875 // constructor rules. Note that virtual bases are not taken into account
7876 // for determining the argument type of the operator. Note also that
7877 // operators taking an object instead of a reference are allowed.
7878
7879 ImplicitExceptionSpecification Spec(Context);
7880 bool Const;
7881 llvm::tie(Spec, Const) =
7882 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7883
7884 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7885 QualType RetType = Context.getLValueReferenceType(ArgType);
7886 if (Const)
7887 ArgType = ArgType.withConst();
7888 ArgType = Context.getLValueReferenceType(ArgType);
7889
Douglas Gregord3c35902010-07-01 16:36:15 +00007890 // An implicitly-declared copy assignment operator is an inline public
7891 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007892 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007893 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007894 SourceLocation ClassLoc = ClassDecl->getLocation();
7895 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007896 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007897 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007898 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007899 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007900 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007901 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007902 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007903 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007904 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007905 CopyAssignment->setImplicit();
7906 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007907
7908 // Add the parameter to the operator.
7909 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007910 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007911 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007912 SC_None,
7913 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007914 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007915
Douglas Gregora376d102010-07-02 21:50:04 +00007916 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007917 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007918
Douglas Gregor23c94db2010-07-02 17:43:08 +00007919 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007920 PushOnScopeChains(CopyAssignment, S, false);
7921 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007922
Nico Weberafcc96a2012-01-23 03:19:29 +00007923 // C++0x [class.copy]p19:
7924 // .... If the class definition does not explicitly declare a copy
7925 // assignment operator, there is no user-declared move constructor, and
7926 // there is no user-declared move assignment operator, a copy assignment
7927 // operator is implicitly declared as defaulted.
7928 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007929 !getLangOptions().MicrosoftMode) ||
7930 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007931 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007932 CopyAssignment->setDeletedAsWritten();
7933
Douglas Gregord3c35902010-07-01 16:36:15 +00007934 AddOverriddenMethods(ClassDecl, CopyAssignment);
7935 return CopyAssignment;
7936}
7937
Douglas Gregor06a9f362010-05-01 20:49:11 +00007938void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7939 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007940 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007941 CopyAssignOperator->isOverloadedOperator() &&
7942 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007943 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007944 "DefineImplicitCopyAssignment called for wrong function");
7945
7946 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7947
7948 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7949 CopyAssignOperator->setInvalidDecl();
7950 return;
7951 }
7952
7953 CopyAssignOperator->setUsed();
7954
7955 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007956 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007957
7958 // C++0x [class.copy]p30:
7959 // The implicitly-defined or explicitly-defaulted copy assignment operator
7960 // for a non-union class X performs memberwise copy assignment of its
7961 // subobjects. The direct base classes of X are assigned first, in the
7962 // order of their declaration in the base-specifier-list, and then the
7963 // immediate non-static data members of X are assigned, in the order in
7964 // which they were declared in the class definition.
7965
7966 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007967 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007968
7969 // The parameter for the "other" object, which we are copying from.
7970 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7971 Qualifiers OtherQuals = Other->getType().getQualifiers();
7972 QualType OtherRefType = Other->getType();
7973 if (const LValueReferenceType *OtherRef
7974 = OtherRefType->getAs<LValueReferenceType>()) {
7975 OtherRefType = OtherRef->getPointeeType();
7976 OtherQuals = OtherRefType.getQualifiers();
7977 }
7978
7979 // Our location for everything implicitly-generated.
7980 SourceLocation Loc = CopyAssignOperator->getLocation();
7981
7982 // Construct a reference to the "other" object. We'll be using this
7983 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007984 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007985 assert(OtherRef && "Reference to parameter cannot fail!");
7986
7987 // Construct the "this" pointer. We'll be using this throughout the generated
7988 // ASTs.
7989 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7990 assert(This && "Reference to this cannot fail!");
7991
7992 // Assign base classes.
7993 bool Invalid = false;
7994 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7995 E = ClassDecl->bases_end(); Base != E; ++Base) {
7996 // Form the assignment:
7997 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7998 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007999 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008000 Invalid = true;
8001 continue;
8002 }
8003
John McCallf871d0c2010-08-07 06:22:56 +00008004 CXXCastPath BasePath;
8005 BasePath.push_back(Base);
8006
Douglas Gregor06a9f362010-05-01 20:49:11 +00008007 // Construct the "from" expression, which is an implicit cast to the
8008 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008009 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008010 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8011 CK_UncheckedDerivedToBase,
8012 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008013
8014 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008015 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008016
8017 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008018 To = ImpCastExprToType(To.take(),
8019 Context.getCVRQualifiedType(BaseType,
8020 CopyAssignOperator->getTypeQualifiers()),
8021 CK_UncheckedDerivedToBase,
8022 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008023
8024 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00008025 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008026 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008027 /*CopyingBaseSubobject=*/true,
8028 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008029 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008030 Diag(CurrentLocation, diag::note_member_synthesized_at)
8031 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8032 CopyAssignOperator->setInvalidDecl();
8033 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008034 }
8035
8036 // Success! Record the copy.
8037 Statements.push_back(Copy.takeAs<Expr>());
8038 }
8039
8040 // \brief Reference to the __builtin_memcpy function.
8041 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008042 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008043 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008044
8045 // Assign non-static members.
8046 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8047 FieldEnd = ClassDecl->field_end();
8048 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008049 if (Field->isUnnamedBitfield())
8050 continue;
8051
Douglas Gregor06a9f362010-05-01 20:49:11 +00008052 // Check for members of reference type; we can't copy those.
8053 if (Field->getType()->isReferenceType()) {
8054 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8055 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8056 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008057 Diag(CurrentLocation, diag::note_member_synthesized_at)
8058 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008059 Invalid = true;
8060 continue;
8061 }
8062
8063 // Check for members of const-qualified, non-class type.
8064 QualType BaseType = Context.getBaseElementType(Field->getType());
8065 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8066 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8067 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8068 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008069 Diag(CurrentLocation, diag::note_member_synthesized_at)
8070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008071 Invalid = true;
8072 continue;
8073 }
John McCallb77115d2011-06-17 00:18:42 +00008074
8075 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008076 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8077 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008078
8079 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008080 if (FieldType->isIncompleteArrayType()) {
8081 assert(ClassDecl->hasFlexibleArrayMember() &&
8082 "Incomplete array type is not valid");
8083 continue;
8084 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008085
8086 // Build references to the field in the object we're copying from and to.
8087 CXXScopeSpec SS; // Intentionally empty
8088 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8089 LookupMemberName);
8090 MemberLookup.addDecl(*Field);
8091 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008092 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008093 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008094 SS, SourceLocation(), 0,
8095 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008096 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008097 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008098 SS, SourceLocation(), 0,
8099 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008100 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8101 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8102
8103 // If the field should be copied with __builtin_memcpy rather than via
8104 // explicit assignments, do so. This optimization only applies for arrays
8105 // of scalars and arrays of class type with trivial copy-assignment
8106 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008107 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008108 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008109 // Compute the size of the memory buffer to be copied.
8110 QualType SizeType = Context.getSizeType();
8111 llvm::APInt Size(Context.getTypeSize(SizeType),
8112 Context.getTypeSizeInChars(BaseType).getQuantity());
8113 for (const ConstantArrayType *Array
8114 = Context.getAsConstantArrayType(FieldType);
8115 Array;
8116 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008117 llvm::APInt ArraySize
8118 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 Size *= ArraySize;
8120 }
8121
8122 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008123 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8124 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008125
8126 bool NeedsCollectableMemCpy =
8127 (BaseType->isRecordType() &&
8128 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8129
8130 if (NeedsCollectableMemCpy) {
8131 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008132 // Create a reference to the __builtin_objc_memmove_collectable function.
8133 LookupResult R(*this,
8134 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008135 Loc, LookupOrdinaryName);
8136 LookupName(R, TUScope, true);
8137
8138 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8139 if (!CollectableMemCpy) {
8140 // Something went horribly wrong earlier, and we will have
8141 // complained about it.
8142 Invalid = true;
8143 continue;
8144 }
8145
8146 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8147 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008148 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008149 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8150 }
8151 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008152 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008153 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008154 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8155 LookupOrdinaryName);
8156 LookupName(R, TUScope, true);
8157
8158 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8159 if (!BuiltinMemCpy) {
8160 // Something went horribly wrong earlier, and we will have complained
8161 // about it.
8162 Invalid = true;
8163 continue;
8164 }
8165
8166 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8167 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008168 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008169 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8170 }
8171
John McCallca0408f2010-08-23 06:44:23 +00008172 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008173 CallArgs.push_back(To.takeAs<Expr>());
8174 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008175 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008176 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008177 if (NeedsCollectableMemCpy)
8178 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008179 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008180 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008181 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008182 else
8183 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008184 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008185 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008186 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008187
Douglas Gregor06a9f362010-05-01 20:49:11 +00008188 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8189 Statements.push_back(Call.takeAs<Expr>());
8190 continue;
8191 }
8192
8193 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008194 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008195 To.get(), From.get(),
8196 /*CopyingBaseSubobject=*/false,
8197 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008198 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008199 Diag(CurrentLocation, diag::note_member_synthesized_at)
8200 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8201 CopyAssignOperator->setInvalidDecl();
8202 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008203 }
8204
8205 // Success! Record the copy.
8206 Statements.push_back(Copy.takeAs<Stmt>());
8207 }
8208
8209 if (!Invalid) {
8210 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008211 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008212
John McCall60d7b3a2010-08-24 06:29:42 +00008213 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008214 if (Return.isInvalid())
8215 Invalid = true;
8216 else {
8217 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008218
8219 if (Trap.hasErrorOccurred()) {
8220 Diag(CurrentLocation, diag::note_member_synthesized_at)
8221 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8222 Invalid = true;
8223 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008224 }
8225 }
8226
8227 if (Invalid) {
8228 CopyAssignOperator->setInvalidDecl();
8229 return;
8230 }
8231
John McCall60d7b3a2010-08-24 06:29:42 +00008232 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008233 /*isStmtExpr=*/false);
8234 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8235 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008236
8237 if (ASTMutationListener *L = getASTMutationListener()) {
8238 L->CompletedImplicitDefinition(CopyAssignOperator);
8239 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008240}
8241
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008242Sema::ImplicitExceptionSpecification
8243Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8244 ImplicitExceptionSpecification ExceptSpec(Context);
8245
8246 if (ClassDecl->isInvalidDecl())
8247 return ExceptSpec;
8248
8249 // C++0x [except.spec]p14:
8250 // An implicitly declared special member function (Clause 12) shall have an
8251 // exception-specification. [...]
8252
8253 // It is unspecified whether or not an implicit move assignment operator
8254 // attempts to deduplicate calls to assignment operators of virtual bases are
8255 // made. As such, this exception specification is effectively unspecified.
8256 // Based on a similar decision made for constness in C++0x, we're erring on
8257 // the side of assuming such calls to be made regardless of whether they
8258 // actually happen.
8259 // Note that a move constructor is not implicitly declared when there are
8260 // virtual bases, but it can still be user-declared and explicitly defaulted.
8261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8262 BaseEnd = ClassDecl->bases_end();
8263 Base != BaseEnd; ++Base) {
8264 if (Base->isVirtual())
8265 continue;
8266
8267 CXXRecordDecl *BaseClassDecl
8268 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8269 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8270 false, 0))
8271 ExceptSpec.CalledDecl(MoveAssign);
8272 }
8273
8274 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8275 BaseEnd = ClassDecl->vbases_end();
8276 Base != BaseEnd; ++Base) {
8277 CXXRecordDecl *BaseClassDecl
8278 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8279 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8280 false, 0))
8281 ExceptSpec.CalledDecl(MoveAssign);
8282 }
8283
8284 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8285 FieldEnd = ClassDecl->field_end();
8286 Field != FieldEnd;
8287 ++Field) {
8288 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8289 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8290 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8291 false, 0))
8292 ExceptSpec.CalledDecl(MoveAssign);
8293 }
8294 }
8295
8296 return ExceptSpec;
8297}
8298
8299CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8300 // Note: The following rules are largely analoguous to the move
8301 // constructor rules.
8302
8303 ImplicitExceptionSpecification Spec(
8304 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8305
8306 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8307 QualType RetType = Context.getLValueReferenceType(ArgType);
8308 ArgType = Context.getRValueReferenceType(ArgType);
8309
8310 // An implicitly-declared move assignment operator is an inline public
8311 // member of its class.
8312 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8313 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8314 SourceLocation ClassLoc = ClassDecl->getLocation();
8315 DeclarationNameInfo NameInfo(Name, ClassLoc);
8316 CXXMethodDecl *MoveAssignment
8317 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8318 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8319 /*TInfo=*/0, /*isStatic=*/false,
8320 /*StorageClassAsWritten=*/SC_None,
8321 /*isInline=*/true,
8322 /*isConstexpr=*/false,
8323 SourceLocation());
8324 MoveAssignment->setAccess(AS_public);
8325 MoveAssignment->setDefaulted();
8326 MoveAssignment->setImplicit();
8327 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8328
8329 // Add the parameter to the operator.
8330 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8331 ClassLoc, ClassLoc, /*Id=*/0,
8332 ArgType, /*TInfo=*/0,
8333 SC_None,
8334 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008335 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008336
8337 // Note that we have added this copy-assignment operator.
8338 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8339
8340 // C++0x [class.copy]p9:
8341 // If the definition of a class X does not explicitly declare a move
8342 // assignment operator, one will be implicitly declared as defaulted if and
8343 // only if:
8344 // [...]
8345 // - the move assignment operator would not be implicitly defined as
8346 // deleted.
8347 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8348 // Cache this result so that we don't try to generate this over and over
8349 // on every lookup, leaking memory and wasting time.
8350 ClassDecl->setFailedImplicitMoveAssignment();
8351 return 0;
8352 }
8353
8354 if (Scope *S = getScopeForContext(ClassDecl))
8355 PushOnScopeChains(MoveAssignment, S, false);
8356 ClassDecl->addDecl(MoveAssignment);
8357
8358 AddOverriddenMethods(ClassDecl, MoveAssignment);
8359 return MoveAssignment;
8360}
8361
8362void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8363 CXXMethodDecl *MoveAssignOperator) {
8364 assert((MoveAssignOperator->isDefaulted() &&
8365 MoveAssignOperator->isOverloadedOperator() &&
8366 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8367 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8368 "DefineImplicitMoveAssignment called for wrong function");
8369
8370 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8371
8372 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8373 MoveAssignOperator->setInvalidDecl();
8374 return;
8375 }
8376
8377 MoveAssignOperator->setUsed();
8378
8379 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8380 DiagnosticErrorTrap Trap(Diags);
8381
8382 // C++0x [class.copy]p28:
8383 // The implicitly-defined or move assignment operator for a non-union class
8384 // X performs memberwise move assignment of its subobjects. The direct base
8385 // classes of X are assigned first, in the order of their declaration in the
8386 // base-specifier-list, and then the immediate non-static data members of X
8387 // are assigned, in the order in which they were declared in the class
8388 // definition.
8389
8390 // The statements that form the synthesized function body.
8391 ASTOwningVector<Stmt*> Statements(*this);
8392
8393 // The parameter for the "other" object, which we are move from.
8394 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8395 QualType OtherRefType = Other->getType()->
8396 getAs<RValueReferenceType>()->getPointeeType();
8397 assert(OtherRefType.getQualifiers() == 0 &&
8398 "Bad argument type of defaulted move assignment");
8399
8400 // Our location for everything implicitly-generated.
8401 SourceLocation Loc = MoveAssignOperator->getLocation();
8402
8403 // Construct a reference to the "other" object. We'll be using this
8404 // throughout the generated ASTs.
8405 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8406 assert(OtherRef && "Reference to parameter cannot fail!");
8407 // Cast to rvalue.
8408 OtherRef = CastForMoving(*this, OtherRef);
8409
8410 // Construct the "this" pointer. We'll be using this throughout the generated
8411 // ASTs.
8412 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8413 assert(This && "Reference to this cannot fail!");
8414
8415 // Assign base classes.
8416 bool Invalid = false;
8417 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8418 E = ClassDecl->bases_end(); Base != E; ++Base) {
8419 // Form the assignment:
8420 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8421 QualType BaseType = Base->getType().getUnqualifiedType();
8422 if (!BaseType->isRecordType()) {
8423 Invalid = true;
8424 continue;
8425 }
8426
8427 CXXCastPath BasePath;
8428 BasePath.push_back(Base);
8429
8430 // Construct the "from" expression, which is an implicit cast to the
8431 // appropriately-qualified base type.
8432 Expr *From = OtherRef;
8433 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008434 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008435
8436 // Dereference "this".
8437 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8438
8439 // Implicitly cast "this" to the appropriately-qualified base type.
8440 To = ImpCastExprToType(To.take(),
8441 Context.getCVRQualifiedType(BaseType,
8442 MoveAssignOperator->getTypeQualifiers()),
8443 CK_UncheckedDerivedToBase,
8444 VK_LValue, &BasePath);
8445
8446 // Build the move.
8447 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8448 To.get(), From,
8449 /*CopyingBaseSubobject=*/true,
8450 /*Copying=*/false);
8451 if (Move.isInvalid()) {
8452 Diag(CurrentLocation, diag::note_member_synthesized_at)
8453 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8454 MoveAssignOperator->setInvalidDecl();
8455 return;
8456 }
8457
8458 // Success! Record the move.
8459 Statements.push_back(Move.takeAs<Expr>());
8460 }
8461
8462 // \brief Reference to the __builtin_memcpy function.
8463 Expr *BuiltinMemCpyRef = 0;
8464 // \brief Reference to the __builtin_objc_memmove_collectable function.
8465 Expr *CollectableMemCpyRef = 0;
8466
8467 // Assign non-static members.
8468 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8469 FieldEnd = ClassDecl->field_end();
8470 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008471 if (Field->isUnnamedBitfield())
8472 continue;
8473
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008474 // Check for members of reference type; we can't move those.
8475 if (Field->getType()->isReferenceType()) {
8476 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8477 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8478 Diag(Field->getLocation(), diag::note_declared_at);
8479 Diag(CurrentLocation, diag::note_member_synthesized_at)
8480 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8481 Invalid = true;
8482 continue;
8483 }
8484
8485 // Check for members of const-qualified, non-class type.
8486 QualType BaseType = Context.getBaseElementType(Field->getType());
8487 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8488 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8489 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8490 Diag(Field->getLocation(), diag::note_declared_at);
8491 Diag(CurrentLocation, diag::note_member_synthesized_at)
8492 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8493 Invalid = true;
8494 continue;
8495 }
8496
8497 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008498 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8499 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008500
8501 QualType FieldType = Field->getType().getNonReferenceType();
8502 if (FieldType->isIncompleteArrayType()) {
8503 assert(ClassDecl->hasFlexibleArrayMember() &&
8504 "Incomplete array type is not valid");
8505 continue;
8506 }
8507
8508 // Build references to the field in the object we're copying from and to.
8509 CXXScopeSpec SS; // Intentionally empty
8510 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8511 LookupMemberName);
8512 MemberLookup.addDecl(*Field);
8513 MemberLookup.resolveKind();
8514 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8515 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008516 SS, SourceLocation(), 0,
8517 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008518 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8519 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008520 SS, SourceLocation(), 0,
8521 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008522 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8523 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8524
8525 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8526 "Member reference with rvalue base must be rvalue except for reference "
8527 "members, which aren't allowed for move assignment.");
8528
8529 // If the field should be copied with __builtin_memcpy rather than via
8530 // explicit assignments, do so. This optimization only applies for arrays
8531 // of scalars and arrays of class type with trivial move-assignment
8532 // operators.
8533 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8534 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8535 // Compute the size of the memory buffer to be copied.
8536 QualType SizeType = Context.getSizeType();
8537 llvm::APInt Size(Context.getTypeSize(SizeType),
8538 Context.getTypeSizeInChars(BaseType).getQuantity());
8539 for (const ConstantArrayType *Array
8540 = Context.getAsConstantArrayType(FieldType);
8541 Array;
8542 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8543 llvm::APInt ArraySize
8544 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8545 Size *= ArraySize;
8546 }
8547
Douglas Gregor45d3d712011-09-01 02:09:07 +00008548 // Take the address of the field references for "from" and "to". We
8549 // directly construct UnaryOperators here because semantic analysis
8550 // does not permit us to take the address of an xvalue.
8551 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8552 Context.getPointerType(From.get()->getType()),
8553 VK_RValue, OK_Ordinary, Loc);
8554 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8555 Context.getPointerType(To.get()->getType()),
8556 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008557
8558 bool NeedsCollectableMemCpy =
8559 (BaseType->isRecordType() &&
8560 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8561
8562 if (NeedsCollectableMemCpy) {
8563 if (!CollectableMemCpyRef) {
8564 // Create a reference to the __builtin_objc_memmove_collectable function.
8565 LookupResult R(*this,
8566 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8567 Loc, LookupOrdinaryName);
8568 LookupName(R, TUScope, true);
8569
8570 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8571 if (!CollectableMemCpy) {
8572 // Something went horribly wrong earlier, and we will have
8573 // complained about it.
8574 Invalid = true;
8575 continue;
8576 }
8577
8578 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8579 CollectableMemCpy->getType(),
8580 VK_LValue, Loc, 0).take();
8581 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8582 }
8583 }
8584 // Create a reference to the __builtin_memcpy builtin function.
8585 else if (!BuiltinMemCpyRef) {
8586 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8587 LookupOrdinaryName);
8588 LookupName(R, TUScope, true);
8589
8590 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8591 if (!BuiltinMemCpy) {
8592 // Something went horribly wrong earlier, and we will have complained
8593 // about it.
8594 Invalid = true;
8595 continue;
8596 }
8597
8598 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8599 BuiltinMemCpy->getType(),
8600 VK_LValue, Loc, 0).take();
8601 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8602 }
8603
8604 ASTOwningVector<Expr*> CallArgs(*this);
8605 CallArgs.push_back(To.takeAs<Expr>());
8606 CallArgs.push_back(From.takeAs<Expr>());
8607 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8608 ExprResult Call = ExprError();
8609 if (NeedsCollectableMemCpy)
8610 Call = ActOnCallExpr(/*Scope=*/0,
8611 CollectableMemCpyRef,
8612 Loc, move_arg(CallArgs),
8613 Loc);
8614 else
8615 Call = ActOnCallExpr(/*Scope=*/0,
8616 BuiltinMemCpyRef,
8617 Loc, move_arg(CallArgs),
8618 Loc);
8619
8620 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8621 Statements.push_back(Call.takeAs<Expr>());
8622 continue;
8623 }
8624
8625 // Build the move of this field.
8626 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8627 To.get(), From.get(),
8628 /*CopyingBaseSubobject=*/false,
8629 /*Copying=*/false);
8630 if (Move.isInvalid()) {
8631 Diag(CurrentLocation, diag::note_member_synthesized_at)
8632 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8633 MoveAssignOperator->setInvalidDecl();
8634 return;
8635 }
8636
8637 // Success! Record the copy.
8638 Statements.push_back(Move.takeAs<Stmt>());
8639 }
8640
8641 if (!Invalid) {
8642 // Add a "return *this;"
8643 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8644
8645 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8646 if (Return.isInvalid())
8647 Invalid = true;
8648 else {
8649 Statements.push_back(Return.takeAs<Stmt>());
8650
8651 if (Trap.hasErrorOccurred()) {
8652 Diag(CurrentLocation, diag::note_member_synthesized_at)
8653 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8654 Invalid = true;
8655 }
8656 }
8657 }
8658
8659 if (Invalid) {
8660 MoveAssignOperator->setInvalidDecl();
8661 return;
8662 }
8663
8664 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8665 /*isStmtExpr=*/false);
8666 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8667 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8668
8669 if (ASTMutationListener *L = getASTMutationListener()) {
8670 L->CompletedImplicitDefinition(MoveAssignOperator);
8671 }
8672}
8673
Sean Hunt49634cf2011-05-13 06:10:58 +00008674std::pair<Sema::ImplicitExceptionSpecification, bool>
8675Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008676 if (ClassDecl->isInvalidDecl())
8677 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8678
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008679 // C++ [class.copy]p5:
8680 // The implicitly-declared copy constructor for a class X will
8681 // have the form
8682 //
8683 // X::X(const X&)
8684 //
8685 // if
Sean Huntc530d172011-06-10 04:44:37 +00008686 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008687 bool HasConstCopyConstructor = true;
8688
8689 // -- each direct or virtual base class B of X has a copy
8690 // constructor whose first parameter is of type const B& or
8691 // const volatile B&, and
8692 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8693 BaseEnd = ClassDecl->bases_end();
8694 HasConstCopyConstructor && Base != BaseEnd;
8695 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008696 // Virtual bases are handled below.
8697 if (Base->isVirtual())
8698 continue;
8699
Douglas Gregor22584312010-07-02 23:41:54 +00008700 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008701 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008702 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8703 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008704 }
8705
8706 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8707 BaseEnd = ClassDecl->vbases_end();
8708 HasConstCopyConstructor && Base != BaseEnd;
8709 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008710 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008711 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008712 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8713 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008714 }
8715
8716 // -- for all the nonstatic data members of X that are of a
8717 // class type M (or array thereof), each such class type
8718 // has a copy constructor whose first parameter is of type
8719 // const M& or const volatile M&.
8720 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8721 FieldEnd = ClassDecl->field_end();
8722 HasConstCopyConstructor && Field != FieldEnd;
8723 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008724 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008725 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008726 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8727 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008728 }
8729 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008730 // Otherwise, the implicitly declared copy constructor will have
8731 // the form
8732 //
8733 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008734
Douglas Gregor0d405db2010-07-01 20:59:04 +00008735 // C++ [except.spec]p14:
8736 // An implicitly declared special member function (Clause 12) shall have an
8737 // exception-specification. [...]
8738 ImplicitExceptionSpecification ExceptSpec(Context);
8739 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8740 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8741 BaseEnd = ClassDecl->bases_end();
8742 Base != BaseEnd;
8743 ++Base) {
8744 // Virtual bases are handled below.
8745 if (Base->isVirtual())
8746 continue;
8747
Douglas Gregor22584312010-07-02 23:41:54 +00008748 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008749 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008750 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008751 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008752 ExceptSpec.CalledDecl(CopyConstructor);
8753 }
8754 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8755 BaseEnd = ClassDecl->vbases_end();
8756 Base != BaseEnd;
8757 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008758 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008759 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008760 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008761 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008762 ExceptSpec.CalledDecl(CopyConstructor);
8763 }
8764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8765 FieldEnd = ClassDecl->field_end();
8766 Field != FieldEnd;
8767 ++Field) {
8768 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008769 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8770 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008771 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008772 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008773 }
8774 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008775
Sean Hunt49634cf2011-05-13 06:10:58 +00008776 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8777}
8778
8779CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8780 CXXRecordDecl *ClassDecl) {
8781 // C++ [class.copy]p4:
8782 // If the class definition does not explicitly declare a copy
8783 // constructor, one is declared implicitly.
8784
8785 ImplicitExceptionSpecification Spec(Context);
8786 bool Const;
8787 llvm::tie(Spec, Const) =
8788 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8789
8790 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8791 QualType ArgType = ClassType;
8792 if (Const)
8793 ArgType = ArgType.withConst();
8794 ArgType = Context.getLValueReferenceType(ArgType);
8795
8796 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8797
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008798 DeclarationName Name
8799 = Context.DeclarationNames.getCXXConstructorName(
8800 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008801 SourceLocation ClassLoc = ClassDecl->getLocation();
8802 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008803
8804 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008805 // member of its class.
8806 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8807 Context, ClassDecl, ClassLoc, NameInfo,
8808 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8809 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8810 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8811 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008812 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008813 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008814 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008815
Douglas Gregor22584312010-07-02 23:41:54 +00008816 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008817 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8818
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008819 // Add the parameter to the constructor.
8820 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008821 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008822 /*IdentifierInfo=*/0,
8823 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008824 SC_None,
8825 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008826 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008827
Douglas Gregor23c94db2010-07-02 17:43:08 +00008828 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008829 PushOnScopeChains(CopyConstructor, S, false);
8830 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008831
Nico Weberafcc96a2012-01-23 03:19:29 +00008832 // C++11 [class.copy]p8:
8833 // ... If the class definition does not explicitly declare a copy
8834 // constructor, there is no user-declared move constructor, and there is no
8835 // user-declared move assignment operator, a copy constructor is implicitly
8836 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008837 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008838 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008839 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008840 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008841 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008842
8843 return CopyConstructor;
8844}
8845
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008846void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008847 CXXConstructorDecl *CopyConstructor) {
8848 assert((CopyConstructor->isDefaulted() &&
8849 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008850 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008851 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008852
Anders Carlsson63010a72010-04-23 16:24:12 +00008853 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008854 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008855
Douglas Gregor39957dc2010-05-01 15:04:51 +00008856 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008857 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008858
Sean Huntcbb67482011-01-08 20:30:50 +00008859 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008860 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008861 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008862 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008863 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008864 } else {
8865 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8866 CopyConstructor->getLocation(),
8867 MultiStmtArg(*this, 0, 0),
8868 /*isStmtExpr=*/false)
8869 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008870 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008871 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008872
8873 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008874 if (ASTMutationListener *L = getASTMutationListener()) {
8875 L->CompletedImplicitDefinition(CopyConstructor);
8876 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008877}
8878
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008879Sema::ImplicitExceptionSpecification
8880Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8881 // C++ [except.spec]p14:
8882 // An implicitly declared special member function (Clause 12) shall have an
8883 // exception-specification. [...]
8884 ImplicitExceptionSpecification ExceptSpec(Context);
8885 if (ClassDecl->isInvalidDecl())
8886 return ExceptSpec;
8887
8888 // Direct base-class constructors.
8889 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8890 BEnd = ClassDecl->bases_end();
8891 B != BEnd; ++B) {
8892 if (B->isVirtual()) // Handled below.
8893 continue;
8894
8895 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8896 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8897 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8898 // If this is a deleted function, add it anyway. This might be conformant
8899 // with the standard. This might not. I'm not sure. It might not matter.
8900 if (Constructor)
8901 ExceptSpec.CalledDecl(Constructor);
8902 }
8903 }
8904
8905 // Virtual base-class constructors.
8906 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8907 BEnd = ClassDecl->vbases_end();
8908 B != BEnd; ++B) {
8909 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8910 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8911 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8912 // If this is a deleted function, add it anyway. This might be conformant
8913 // with the standard. This might not. I'm not sure. It might not matter.
8914 if (Constructor)
8915 ExceptSpec.CalledDecl(Constructor);
8916 }
8917 }
8918
8919 // Field constructors.
8920 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8921 FEnd = ClassDecl->field_end();
8922 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008923 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008924 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8925 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8926 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8927 // If this is a deleted function, add it anyway. This might be conformant
8928 // with the standard. This might not. I'm not sure. It might not matter.
8929 // In particular, the problem is that this function never gets called. It
8930 // might just be ill-formed because this function attempts to refer to
8931 // a deleted function here.
8932 if (Constructor)
8933 ExceptSpec.CalledDecl(Constructor);
8934 }
8935 }
8936
8937 return ExceptSpec;
8938}
8939
8940CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8941 CXXRecordDecl *ClassDecl) {
8942 ImplicitExceptionSpecification Spec(
8943 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8944
8945 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8946 QualType ArgType = Context.getRValueReferenceType(ClassType);
8947
8948 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8949
8950 DeclarationName Name
8951 = Context.DeclarationNames.getCXXConstructorName(
8952 Context.getCanonicalType(ClassType));
8953 SourceLocation ClassLoc = ClassDecl->getLocation();
8954 DeclarationNameInfo NameInfo(Name, ClassLoc);
8955
8956 // C++0x [class.copy]p11:
8957 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008958 // member of its class.
8959 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8960 Context, ClassDecl, ClassLoc, NameInfo,
8961 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8962 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8963 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8964 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008965 MoveConstructor->setAccess(AS_public);
8966 MoveConstructor->setDefaulted();
8967 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008968
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008969 // Add the parameter to the constructor.
8970 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8971 ClassLoc, ClassLoc,
8972 /*IdentifierInfo=*/0,
8973 ArgType, /*TInfo=*/0,
8974 SC_None,
8975 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008976 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008977
8978 // C++0x [class.copy]p9:
8979 // If the definition of a class X does not explicitly declare a move
8980 // constructor, one will be implicitly declared as defaulted if and only if:
8981 // [...]
8982 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008983 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008984 // Cache this result so that we don't try to generate this over and over
8985 // on every lookup, leaking memory and wasting time.
8986 ClassDecl->setFailedImplicitMoveConstructor();
8987 return 0;
8988 }
8989
8990 // Note that we have declared this constructor.
8991 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8992
8993 if (Scope *S = getScopeForContext(ClassDecl))
8994 PushOnScopeChains(MoveConstructor, S, false);
8995 ClassDecl->addDecl(MoveConstructor);
8996
8997 return MoveConstructor;
8998}
8999
9000void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9001 CXXConstructorDecl *MoveConstructor) {
9002 assert((MoveConstructor->isDefaulted() &&
9003 MoveConstructor->isMoveConstructor() &&
9004 !MoveConstructor->doesThisDeclarationHaveABody()) &&
9005 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9006
9007 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9008 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9009
9010 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
9011 DiagnosticErrorTrap Trap(Diags);
9012
9013 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9014 Trap.hasErrorOccurred()) {
9015 Diag(CurrentLocation, diag::note_member_synthesized_at)
9016 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9017 MoveConstructor->setInvalidDecl();
9018 } else {
9019 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9020 MoveConstructor->getLocation(),
9021 MultiStmtArg(*this, 0, 0),
9022 /*isStmtExpr=*/false)
9023 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009024 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009025 }
9026
9027 MoveConstructor->setUsed();
9028
9029 if (ASTMutationListener *L = getASTMutationListener()) {
9030 L->CompletedImplicitDefinition(MoveConstructor);
9031 }
9032}
9033
John McCall60d7b3a2010-08-24 06:29:42 +00009034ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009035Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009036 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009037 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009038 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009039 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009040 unsigned ConstructKind,
9041 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009042 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009043
Douglas Gregor2f599792010-04-02 18:24:57 +00009044 // C++0x [class.copy]p34:
9045 // When certain criteria are met, an implementation is allowed to
9046 // omit the copy/move construction of a class object, even if the
9047 // copy/move constructor and/or destructor for the object have
9048 // side effects. [...]
9049 // - when a temporary class object that has not been bound to a
9050 // reference (12.2) would be copied/moved to a class object
9051 // with the same cv-unqualified type, the copy/move operation
9052 // can be omitted by constructing the temporary object
9053 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009054 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009055 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009056 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009057 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009058 }
Mike Stump1eb44332009-09-09 15:08:12 +00009059
9060 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009061 Elidable, move(ExprArgs), HadMultipleCandidates,
9062 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009063}
9064
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009065/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9066/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009067ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009068Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9069 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009070 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009071 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009072 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009073 unsigned ConstructKind,
9074 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009075 unsigned NumExprs = ExprArgs.size();
9076 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009077
Nick Lewycky909a70d2011-03-25 01:44:32 +00009078 for (specific_attr_iterator<NonNullAttr>
9079 i = Constructor->specific_attr_begin<NonNullAttr>(),
9080 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9081 const NonNullAttr *NonNull = *i;
9082 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9083 }
9084
Eli Friedman5f2987c2012-02-02 03:46:19 +00009085 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009086 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009087 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009088 HadMultipleCandidates, /*FIXME*/false,
9089 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009090 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9091 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009092}
9093
Mike Stump1eb44332009-09-09 15:08:12 +00009094bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009095 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009096 MultiExprArg Exprs,
9097 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009098 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009099 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009100 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009101 move(Exprs), HadMultipleCandidates, false,
9102 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009103 if (TempResult.isInvalid())
9104 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009105
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009106 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009107 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009108 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009109 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009110 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009111
Anders Carlssonfe2de492009-08-25 05:18:00 +00009112 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009113}
9114
John McCall68c6c9a2010-02-02 09:10:11 +00009115void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009116 if (VD->isInvalidDecl()) return;
9117
John McCall68c6c9a2010-02-02 09:10:11 +00009118 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009119 if (ClassDecl->isInvalidDecl()) return;
9120 if (ClassDecl->hasTrivialDestructor()) return;
9121 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009122
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009123 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009124 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009125 CheckDestructorAccess(VD->getLocation(), Destructor,
9126 PDiag(diag::err_access_dtor_var)
9127 << VD->getDeclName()
9128 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009129
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009130 if (!VD->hasGlobalStorage()) return;
9131
9132 // Emit warning for non-trivial dtor in global scope (a real global,
9133 // class-static, function-static).
9134 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9135
9136 // TODO: this should be re-enabled for static locals by !CXAAtExit
9137 if (!VD->isStaticLocal())
9138 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009139}
9140
Douglas Gregor39da0b82009-09-09 23:08:42 +00009141/// \brief Given a constructor and the set of arguments provided for the
9142/// constructor, convert the arguments and add any required default arguments
9143/// to form a proper call to this constructor.
9144///
9145/// \returns true if an error occurred, false otherwise.
9146bool
9147Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9148 MultiExprArg ArgsPtr,
9149 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009150 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009151 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9152 unsigned NumArgs = ArgsPtr.size();
9153 Expr **Args = (Expr **)ArgsPtr.get();
9154
9155 const FunctionProtoType *Proto
9156 = Constructor->getType()->getAs<FunctionProtoType>();
9157 assert(Proto && "Constructor without a prototype?");
9158 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009159
9160 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009161 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009162 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009163 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009164 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009165
9166 VariadicCallType CallType =
9167 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009168 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009169 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9170 Proto, 0, Args, NumArgs, AllArgs,
9171 CallType);
9172 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9173 ConvertedArgs.push_back(AllArgs[i]);
9174 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009175}
9176
Anders Carlsson20d45d22009-12-12 00:32:00 +00009177static inline bool
9178CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9179 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009180 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009181 if (isa<NamespaceDecl>(DC)) {
9182 return SemaRef.Diag(FnDecl->getLocation(),
9183 diag::err_operator_new_delete_declared_in_namespace)
9184 << FnDecl->getDeclName();
9185 }
9186
9187 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009188 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009189 return SemaRef.Diag(FnDecl->getLocation(),
9190 diag::err_operator_new_delete_declared_static)
9191 << FnDecl->getDeclName();
9192 }
9193
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009194 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009195}
9196
Anders Carlsson156c78e2009-12-13 17:53:43 +00009197static inline bool
9198CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9199 CanQualType ExpectedResultType,
9200 CanQualType ExpectedFirstParamType,
9201 unsigned DependentParamTypeDiag,
9202 unsigned InvalidParamTypeDiag) {
9203 QualType ResultType =
9204 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9205
9206 // Check that the result type is not dependent.
9207 if (ResultType->isDependentType())
9208 return SemaRef.Diag(FnDecl->getLocation(),
9209 diag::err_operator_new_delete_dependent_result_type)
9210 << FnDecl->getDeclName() << ExpectedResultType;
9211
9212 // Check that the result type is what we expect.
9213 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9214 return SemaRef.Diag(FnDecl->getLocation(),
9215 diag::err_operator_new_delete_invalid_result_type)
9216 << FnDecl->getDeclName() << ExpectedResultType;
9217
9218 // A function template must have at least 2 parameters.
9219 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9220 return SemaRef.Diag(FnDecl->getLocation(),
9221 diag::err_operator_new_delete_template_too_few_parameters)
9222 << FnDecl->getDeclName();
9223
9224 // The function decl must have at least 1 parameter.
9225 if (FnDecl->getNumParams() == 0)
9226 return SemaRef.Diag(FnDecl->getLocation(),
9227 diag::err_operator_new_delete_too_few_parameters)
9228 << FnDecl->getDeclName();
9229
9230 // Check the the first parameter type is not dependent.
9231 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9232 if (FirstParamType->isDependentType())
9233 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9234 << FnDecl->getDeclName() << ExpectedFirstParamType;
9235
9236 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009237 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009238 ExpectedFirstParamType)
9239 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9240 << FnDecl->getDeclName() << ExpectedFirstParamType;
9241
9242 return false;
9243}
9244
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009245static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009246CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009247 // C++ [basic.stc.dynamic.allocation]p1:
9248 // A program is ill-formed if an allocation function is declared in a
9249 // namespace scope other than global scope or declared static in global
9250 // scope.
9251 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9252 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009253
9254 CanQualType SizeTy =
9255 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9256
9257 // C++ [basic.stc.dynamic.allocation]p1:
9258 // The return type shall be void*. The first parameter shall have type
9259 // std::size_t.
9260 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9261 SizeTy,
9262 diag::err_operator_new_dependent_param_type,
9263 diag::err_operator_new_param_type))
9264 return true;
9265
9266 // C++ [basic.stc.dynamic.allocation]p1:
9267 // The first parameter shall not have an associated default argument.
9268 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009269 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009270 diag::err_operator_new_default_arg)
9271 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9272
9273 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009274}
9275
9276static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009277CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9278 // C++ [basic.stc.dynamic.deallocation]p1:
9279 // A program is ill-formed if deallocation functions are declared in a
9280 // namespace scope other than global scope or declared static in global
9281 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009282 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9283 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009284
9285 // C++ [basic.stc.dynamic.deallocation]p2:
9286 // Each deallocation function shall return void and its first parameter
9287 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009288 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9289 SemaRef.Context.VoidPtrTy,
9290 diag::err_operator_delete_dependent_param_type,
9291 diag::err_operator_delete_param_type))
9292 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009293
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009294 return false;
9295}
9296
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009297/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9298/// of this overloaded operator is well-formed. If so, returns false;
9299/// otherwise, emits appropriate diagnostics and returns true.
9300bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009301 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009302 "Expected an overloaded operator declaration");
9303
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009304 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9305
Mike Stump1eb44332009-09-09 15:08:12 +00009306 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009307 // The allocation and deallocation functions, operator new,
9308 // operator new[], operator delete and operator delete[], are
9309 // described completely in 3.7.3. The attributes and restrictions
9310 // found in the rest of this subclause do not apply to them unless
9311 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009312 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009313 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009314
Anders Carlssona3ccda52009-12-12 00:26:23 +00009315 if (Op == OO_New || Op == OO_Array_New)
9316 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009317
9318 // C++ [over.oper]p6:
9319 // An operator function shall either be a non-static member
9320 // function or be a non-member function and have at least one
9321 // parameter whose type is a class, a reference to a class, an
9322 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009323 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9324 if (MethodDecl->isStatic())
9325 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009326 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009327 } else {
9328 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009329 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9330 ParamEnd = FnDecl->param_end();
9331 Param != ParamEnd; ++Param) {
9332 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009333 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9334 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009335 ClassOrEnumParam = true;
9336 break;
9337 }
9338 }
9339
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009340 if (!ClassOrEnumParam)
9341 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009342 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009343 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009344 }
9345
9346 // C++ [over.oper]p8:
9347 // An operator function cannot have default arguments (8.3.6),
9348 // except where explicitly stated below.
9349 //
Mike Stump1eb44332009-09-09 15:08:12 +00009350 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009351 // (C++ [over.call]p1).
9352 if (Op != OO_Call) {
9353 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9354 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009355 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009356 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009357 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009358 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009359 }
9360 }
9361
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009362 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9363 { false, false, false }
9364#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9365 , { Unary, Binary, MemberOnly }
9366#include "clang/Basic/OperatorKinds.def"
9367 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009368
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009369 bool CanBeUnaryOperator = OperatorUses[Op][0];
9370 bool CanBeBinaryOperator = OperatorUses[Op][1];
9371 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009372
9373 // C++ [over.oper]p8:
9374 // [...] Operator functions cannot have more or fewer parameters
9375 // than the number required for the corresponding operator, as
9376 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009377 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009378 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009379 if (Op != OO_Call &&
9380 ((NumParams == 1 && !CanBeUnaryOperator) ||
9381 (NumParams == 2 && !CanBeBinaryOperator) ||
9382 (NumParams < 1) || (NumParams > 2))) {
9383 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009384 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009385 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009386 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009387 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009388 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009389 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009390 assert(CanBeBinaryOperator &&
9391 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009392 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009393 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009394
Chris Lattner416e46f2008-11-21 07:57:12 +00009395 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009396 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009397 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009398
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009399 // Overloaded operators other than operator() cannot be variadic.
9400 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009401 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009402 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009403 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009404 }
9405
9406 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009407 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9408 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009409 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009410 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009411 }
9412
9413 // C++ [over.inc]p1:
9414 // The user-defined function called operator++ implements the
9415 // prefix and postfix ++ operator. If this function is a member
9416 // function with no parameters, or a non-member function with one
9417 // parameter of class or enumeration type, it defines the prefix
9418 // increment operator ++ for objects of that type. If the function
9419 // is a member function with one parameter (which shall be of type
9420 // int) or a non-member function with two parameters (the second
9421 // of which shall be of type int), it defines the postfix
9422 // increment operator ++ for objects of that type.
9423 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9424 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9425 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009426 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009427 ParamIsInt = BT->getKind() == BuiltinType::Int;
9428
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009429 if (!ParamIsInt)
9430 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009431 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009432 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009433 }
9434
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009435 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009436}
Chris Lattner5a003a42008-12-17 07:09:26 +00009437
Sean Hunta6c058d2010-01-13 09:01:02 +00009438/// CheckLiteralOperatorDeclaration - Check whether the declaration
9439/// of this literal operator function is well-formed. If so, returns
9440/// false; otherwise, emits appropriate diagnostics and returns true.
9441bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9442 DeclContext *DC = FnDecl->getDeclContext();
9443 Decl::Kind Kind = DC->getDeclKind();
9444 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9445 Kind != Decl::LinkageSpec) {
9446 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9447 << FnDecl->getDeclName();
9448 return true;
9449 }
9450
9451 bool Valid = false;
9452
Sean Hunt216c2782010-04-07 23:11:06 +00009453 // template <char...> type operator "" name() is the only valid template
9454 // signature, and the only valid signature with no parameters.
9455 if (FnDecl->param_size() == 0) {
9456 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9457 // Must have only one template parameter
9458 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9459 if (Params->size() == 1) {
9460 NonTypeTemplateParmDecl *PmDecl =
9461 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009462
Sean Hunt216c2782010-04-07 23:11:06 +00009463 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009464 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9465 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9466 Valid = true;
9467 }
9468 }
9469 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009470 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009471 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9472
Sean Hunta6c058d2010-01-13 09:01:02 +00009473 QualType T = (*Param)->getType();
9474
Sean Hunt30019c02010-04-07 22:57:35 +00009475 // unsigned long long int, long double, and any character type are allowed
9476 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009477 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9478 Context.hasSameType(T, Context.LongDoubleTy) ||
9479 Context.hasSameType(T, Context.CharTy) ||
9480 Context.hasSameType(T, Context.WCharTy) ||
9481 Context.hasSameType(T, Context.Char16Ty) ||
9482 Context.hasSameType(T, Context.Char32Ty)) {
9483 if (++Param == FnDecl->param_end())
9484 Valid = true;
9485 goto FinishedParams;
9486 }
9487
Sean Hunt30019c02010-04-07 22:57:35 +00009488 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009489 const PointerType *PT = T->getAs<PointerType>();
9490 if (!PT)
9491 goto FinishedParams;
9492 T = PT->getPointeeType();
9493 if (!T.isConstQualified())
9494 goto FinishedParams;
9495 T = T.getUnqualifiedType();
9496
9497 // Move on to the second parameter;
9498 ++Param;
9499
9500 // If there is no second parameter, the first must be a const char *
9501 if (Param == FnDecl->param_end()) {
9502 if (Context.hasSameType(T, Context.CharTy))
9503 Valid = true;
9504 goto FinishedParams;
9505 }
9506
9507 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9508 // are allowed as the first parameter to a two-parameter function
9509 if (!(Context.hasSameType(T, Context.CharTy) ||
9510 Context.hasSameType(T, Context.WCharTy) ||
9511 Context.hasSameType(T, Context.Char16Ty) ||
9512 Context.hasSameType(T, Context.Char32Ty)))
9513 goto FinishedParams;
9514
9515 // The second and final parameter must be an std::size_t
9516 T = (*Param)->getType().getUnqualifiedType();
9517 if (Context.hasSameType(T, Context.getSizeType()) &&
9518 ++Param == FnDecl->param_end())
9519 Valid = true;
9520 }
9521
9522 // FIXME: This diagnostic is absolutely terrible.
9523FinishedParams:
9524 if (!Valid) {
9525 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9526 << FnDecl->getDeclName();
9527 return true;
9528 }
9529
Douglas Gregor1155c422011-08-30 22:40:35 +00009530 StringRef LiteralName
9531 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9532 if (LiteralName[0] != '_') {
9533 // C++0x [usrlit.suffix]p1:
9534 // Literal suffix identifiers that do not start with an underscore are
9535 // reserved for future standardization.
9536 bool IsHexFloat = true;
9537 if (LiteralName.size() > 1 &&
9538 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9539 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9540 if (!isdigit(LiteralName[I])) {
9541 IsHexFloat = false;
9542 break;
9543 }
9544 }
9545 }
9546
9547 if (IsHexFloat)
9548 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9549 << LiteralName;
9550 else
9551 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9552 }
9553
Sean Hunta6c058d2010-01-13 09:01:02 +00009554 return false;
9555}
9556
Douglas Gregor074149e2009-01-05 19:45:36 +00009557/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9558/// linkage specification, including the language and (if present)
9559/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9560/// the location of the language string literal, which is provided
9561/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9562/// the '{' brace. Otherwise, this linkage specification does not
9563/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009564Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9565 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009566 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009567 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009568 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009569 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009570 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009571 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009572 Language = LinkageSpecDecl::lang_cxx;
9573 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009574 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009575 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009576 }
Mike Stump1eb44332009-09-09 15:08:12 +00009577
Chris Lattnercc98eac2008-12-17 07:13:27 +00009578 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009579
Douglas Gregor074149e2009-01-05 19:45:36 +00009580 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009581 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009582 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009583 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009584 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009585}
9586
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009587/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009588/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9589/// valid, it's the position of the closing '}' brace in a linkage
9590/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009591Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009592 Decl *LinkageSpec,
9593 SourceLocation RBraceLoc) {
9594 if (LinkageSpec) {
9595 if (RBraceLoc.isValid()) {
9596 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9597 LSDecl->setRBraceLoc(RBraceLoc);
9598 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009599 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009600 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009601 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009602}
9603
Douglas Gregord308e622009-05-18 20:51:54 +00009604/// \brief Perform semantic analysis for the variable declaration that
9605/// occurs within a C++ catch clause, returning the newly-created
9606/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009607VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009608 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009609 SourceLocation StartLoc,
9610 SourceLocation Loc,
9611 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009612 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009613 QualType ExDeclType = TInfo->getType();
9614
Sebastian Redl4b07b292008-12-22 19:15:10 +00009615 // Arrays and functions decay.
9616 if (ExDeclType->isArrayType())
9617 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9618 else if (ExDeclType->isFunctionType())
9619 ExDeclType = Context.getPointerType(ExDeclType);
9620
9621 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9622 // The exception-declaration shall not denote a pointer or reference to an
9623 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009624 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009625 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009626 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009627 Invalid = true;
9628 }
Douglas Gregord308e622009-05-18 20:51:54 +00009629
Sebastian Redl4b07b292008-12-22 19:15:10 +00009630 QualType BaseType = ExDeclType;
9631 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009632 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009633 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009634 BaseType = Ptr->getPointeeType();
9635 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009636 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009637 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009638 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009639 BaseType = Ref->getPointeeType();
9640 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009641 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009642 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009643 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009644 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009645 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009646
Mike Stump1eb44332009-09-09 15:08:12 +00009647 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009648 RequireNonAbstractType(Loc, ExDeclType,
9649 diag::err_abstract_type_in_decl,
9650 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009651 Invalid = true;
9652
John McCall5a180392010-07-24 00:37:23 +00009653 // Only the non-fragile NeXT runtime currently supports C++ catches
9654 // of ObjC types, and no runtime supports catching ObjC types by value.
9655 if (!Invalid && getLangOptions().ObjC1) {
9656 QualType T = ExDeclType;
9657 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9658 T = RT->getPointeeType();
9659
9660 if (T->isObjCObjectType()) {
9661 Diag(Loc, diag::err_objc_object_catch);
9662 Invalid = true;
9663 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009664 if (!getLangOptions().ObjCNonFragileABI)
9665 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009666 }
9667 }
9668
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009669 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9670 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009671 ExDecl->setExceptionVariable(true);
9672
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009673 // In ARC, infer 'retaining' for variables of retainable type.
9674 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9675 Invalid = true;
9676
Douglas Gregorc41b8782011-07-06 18:14:43 +00009677 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009678 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009679 // C++ [except.handle]p16:
9680 // The object declared in an exception-declaration or, if the
9681 // exception-declaration does not specify a name, a temporary (12.2) is
9682 // copy-initialized (8.5) from the exception object. [...]
9683 // The object is destroyed when the handler exits, after the destruction
9684 // of any automatic objects initialized within the handler.
9685 //
9686 // We just pretend to initialize the object with itself, then make sure
9687 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009688 QualType initType = ExDeclType;
9689
9690 InitializedEntity entity =
9691 InitializedEntity::InitializeVariable(ExDecl);
9692 InitializationKind initKind =
9693 InitializationKind::CreateCopy(Loc, SourceLocation());
9694
9695 Expr *opaqueValue =
9696 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9697 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9698 ExprResult result = sequence.Perform(*this, entity, initKind,
9699 MultiExprArg(&opaqueValue, 1));
9700 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009701 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009702 else {
9703 // If the constructor used was non-trivial, set this as the
9704 // "initializer".
9705 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9706 if (!construct->getConstructor()->isTrivial()) {
9707 Expr *init = MaybeCreateExprWithCleanups(construct);
9708 ExDecl->setInit(init);
9709 }
9710
9711 // And make sure it's destructable.
9712 FinalizeVarWithDestructor(ExDecl, recordType);
9713 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009714 }
9715 }
9716
Douglas Gregord308e622009-05-18 20:51:54 +00009717 if (Invalid)
9718 ExDecl->setInvalidDecl();
9719
9720 return ExDecl;
9721}
9722
9723/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9724/// handler.
John McCalld226f652010-08-21 09:40:31 +00009725Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009726 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009727 bool Invalid = D.isInvalidType();
9728
9729 // Check for unexpanded parameter packs.
9730 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9731 UPPC_ExceptionType)) {
9732 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9733 D.getIdentifierLoc());
9734 Invalid = true;
9735 }
9736
Sebastian Redl4b07b292008-12-22 19:15:10 +00009737 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009738 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009739 LookupOrdinaryName,
9740 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009741 // The scope should be freshly made just for us. There is just no way
9742 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009743 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009744 if (PrevDecl->isTemplateParameter()) {
9745 // Maybe we will complain about the shadowed template parameter.
9746 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009747 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009748 }
9749 }
9750
Chris Lattnereaaebc72009-04-25 08:06:05 +00009751 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009752 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9753 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009754 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009755 }
9756
Douglas Gregor83cb9422010-09-09 17:09:21 +00009757 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009758 D.getSourceRange().getBegin(),
9759 D.getIdentifierLoc(),
9760 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009761 if (Invalid)
9762 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009763
Sebastian Redl4b07b292008-12-22 19:15:10 +00009764 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009765 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009766 PushOnScopeChains(ExDecl, S);
9767 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009768 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009769
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009770 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009771 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009772}
Anders Carlssonfb311762009-03-14 00:25:26 +00009773
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009774Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009775 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009776 Expr *AssertMessageExpr_,
9777 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009778 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009779
Anders Carlssonc3082412009-03-14 00:33:21 +00009780 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009781 // In a static_assert-declaration, the constant-expression shall be a
9782 // constant expression that can be contextually converted to bool.
9783 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9784 if (Converted.isInvalid())
9785 return 0;
9786
Richard Smithdaaefc52011-12-14 23:32:26 +00009787 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009788 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9789 PDiag(diag::err_static_assert_expression_is_not_constant),
9790 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009791 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009792
Richard Smithdaaefc52011-12-14 23:32:26 +00009793 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009794 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009795 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009796 }
Mike Stump1eb44332009-09-09 15:08:12 +00009797
Douglas Gregor399ad972010-12-15 23:55:21 +00009798 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9799 return 0;
9800
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009801 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9802 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009803
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009804 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009805 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009806}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009807
Douglas Gregor1d869352010-04-07 16:53:43 +00009808/// \brief Perform semantic analysis of the given friend type declaration.
9809///
9810/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009811FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9812 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009813 TypeSourceInfo *TSInfo) {
9814 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9815
9816 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009817 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009818
Richard Smith6b130222011-10-18 21:39:00 +00009819 // C++03 [class.friend]p2:
9820 // An elaborated-type-specifier shall be used in a friend declaration
9821 // for a class.*
9822 //
9823 // * The class-key of the elaborated-type-specifier is required.
9824 if (!ActiveTemplateInstantiations.empty()) {
9825 // Do not complain about the form of friend template types during
9826 // template instantiation; we will already have complained when the
9827 // template was declared.
9828 } else if (!T->isElaboratedTypeSpecifier()) {
9829 // If we evaluated the type to a record type, suggest putting
9830 // a tag in front.
9831 if (const RecordType *RT = T->getAs<RecordType>()) {
9832 RecordDecl *RD = RT->getDecl();
9833
9834 std::string InsertionText = std::string(" ") + RD->getKindName();
9835
9836 Diag(TypeRange.getBegin(),
9837 getLangOptions().CPlusPlus0x ?
9838 diag::warn_cxx98_compat_unelaborated_friend_type :
9839 diag::ext_unelaborated_friend_type)
9840 << (unsigned) RD->getTagKind()
9841 << T
9842 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9843 InsertionText);
9844 } else {
9845 Diag(FriendLoc,
9846 getLangOptions().CPlusPlus0x ?
9847 diag::warn_cxx98_compat_nonclass_type_friend :
9848 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009849 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009850 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009851 }
Richard Smith6b130222011-10-18 21:39:00 +00009852 } else if (T->getAs<EnumType>()) {
9853 Diag(FriendLoc,
9854 getLangOptions().CPlusPlus0x ?
9855 diag::warn_cxx98_compat_enum_friend :
9856 diag::ext_enum_friend)
9857 << T
9858 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009859 }
9860
Douglas Gregor06245bf2010-04-07 17:57:12 +00009861 // C++0x [class.friend]p3:
9862 // If the type specifier in a friend declaration designates a (possibly
9863 // cv-qualified) class type, that class is declared as a friend; otherwise,
9864 // the friend declaration is ignored.
9865
9866 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9867 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009868
Abramo Bagnara0216df82011-10-29 20:52:52 +00009869 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009870}
9871
John McCall9a34edb2010-10-19 01:40:49 +00009872/// Handle a friend tag declaration where the scope specifier was
9873/// templated.
9874Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9875 unsigned TagSpec, SourceLocation TagLoc,
9876 CXXScopeSpec &SS,
9877 IdentifierInfo *Name, SourceLocation NameLoc,
9878 AttributeList *Attr,
9879 MultiTemplateParamsArg TempParamLists) {
9880 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9881
9882 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009883 bool Invalid = false;
9884
9885 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009886 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009887 TempParamLists.get(),
9888 TempParamLists.size(),
9889 /*friend*/ true,
9890 isExplicitSpecialization,
9891 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009892 if (TemplateParams->size() > 0) {
9893 // This is a declaration of a class template.
9894 if (Invalid)
9895 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009896
Eric Christopher4110e132011-07-21 05:34:24 +00009897 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9898 SS, Name, NameLoc, Attr,
9899 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009900 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009901 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009902 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009903 } else {
9904 // The "template<>" header is extraneous.
9905 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9906 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9907 isExplicitSpecialization = true;
9908 }
9909 }
9910
9911 if (Invalid) return 0;
9912
John McCall9a34edb2010-10-19 01:40:49 +00009913 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009914 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009915 if (TempParamLists.get()[I]->size()) {
9916 isAllExplicitSpecializations = false;
9917 break;
9918 }
9919 }
9920
9921 // FIXME: don't ignore attributes.
9922
9923 // If it's explicit specializations all the way down, just forget
9924 // about the template header and build an appropriate non-templated
9925 // friend. TODO: for source fidelity, remember the headers.
9926 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009927 if (SS.isEmpty()) {
9928 bool Owned = false;
9929 bool IsDependent = false;
9930 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9931 Attr, AS_public,
9932 /*ModulePrivateLoc=*/SourceLocation(),
9933 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009934 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009935 /*ScopedEnumUsesClassTag=*/false,
9936 /*UnderlyingType=*/TypeResult());
9937 }
9938
Douglas Gregor2494dd02011-03-01 01:34:45 +00009939 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009940 ElaboratedTypeKeyword Keyword
9941 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009942 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009943 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009944 if (T.isNull())
9945 return 0;
9946
9947 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9948 if (isa<DependentNameType>(T)) {
9949 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009950 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009951 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009952 TL.setNameLoc(NameLoc);
9953 } else {
9954 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009955 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009956 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009957 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9958 }
9959
9960 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9961 TSI, FriendLoc);
9962 Friend->setAccess(AS_public);
9963 CurContext->addDecl(Friend);
9964 return Friend;
9965 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009966
9967 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9968
9969
John McCall9a34edb2010-10-19 01:40:49 +00009970
9971 // Handle the case of a templated-scope friend class. e.g.
9972 // template <class T> class A<T>::B;
9973 // FIXME: we don't support these right now.
9974 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9975 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9976 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9977 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009978 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009979 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009980 TL.setNameLoc(NameLoc);
9981
9982 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9983 TSI, FriendLoc);
9984 Friend->setAccess(AS_public);
9985 Friend->setUnsupportedFriend(true);
9986 CurContext->addDecl(Friend);
9987 return Friend;
9988}
9989
9990
John McCalldd4a3b02009-09-16 22:47:08 +00009991/// Handle a friend type declaration. This works in tandem with
9992/// ActOnTag.
9993///
9994/// Notes on friend class templates:
9995///
9996/// We generally treat friend class declarations as if they were
9997/// declaring a class. So, for example, the elaborated type specifier
9998/// in a friend declaration is required to obey the restrictions of a
9999/// class-head (i.e. no typedefs in the scope chain), template
10000/// parameters are required to match up with simple template-ids, &c.
10001/// However, unlike when declaring a template specialization, it's
10002/// okay to refer to a template specialization without an empty
10003/// template parameter declaration, e.g.
10004/// friend class A<T>::B<unsigned>;
10005/// We permit this as a special case; if there are any template
10006/// parameters present at all, require proper matching, i.e.
10007/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010008Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010009 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010010 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010011
10012 assert(DS.isFriendSpecified());
10013 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10014
John McCalldd4a3b02009-09-16 22:47:08 +000010015 // Try to convert the decl specifier to a type. This works for
10016 // friend templates because ActOnTag never produces a ClassTemplateDecl
10017 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010018 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010019 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10020 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010021 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010022 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010023
Douglas Gregor6ccab972010-12-16 01:14:37 +000010024 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10025 return 0;
10026
John McCalldd4a3b02009-09-16 22:47:08 +000010027 // This is definitely an error in C++98. It's probably meant to
10028 // be forbidden in C++0x, too, but the specification is just
10029 // poorly written.
10030 //
10031 // The problem is with declarations like the following:
10032 // template <T> friend A<T>::foo;
10033 // where deciding whether a class C is a friend or not now hinges
10034 // on whether there exists an instantiation of A that causes
10035 // 'foo' to equal C. There are restrictions on class-heads
10036 // (which we declare (by fiat) elaborated friend declarations to
10037 // be) that makes this tractable.
10038 //
10039 // FIXME: handle "template <> friend class A<T>;", which
10040 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010041 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010042 Diag(Loc, diag::err_tagless_friend_type_template)
10043 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010044 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010045 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010046
John McCall02cace72009-08-28 07:59:38 +000010047 // C++98 [class.friend]p1: A friend of a class is a function
10048 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010049 // This is fixed in DR77, which just barely didn't make the C++03
10050 // deadline. It's also a very silly restriction that seriously
10051 // affects inner classes and which nobody else seems to implement;
10052 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010053 //
10054 // But note that we could warn about it: it's always useless to
10055 // friend one of your own members (it's not, however, worthless to
10056 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010057
John McCalldd4a3b02009-09-16 22:47:08 +000010058 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010059 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010060 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010061 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010062 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010063 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010064 DS.getFriendSpecLoc());
10065 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010066 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010067
10068 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010069 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010070
John McCalldd4a3b02009-09-16 22:47:08 +000010071 D->setAccess(AS_public);
10072 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010073
John McCalld226f652010-08-21 09:40:31 +000010074 return D;
John McCall02cace72009-08-28 07:59:38 +000010075}
10076
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010077Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010078 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010079 const DeclSpec &DS = D.getDeclSpec();
10080
10081 assert(DS.isFriendSpecified());
10082 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10083
10084 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010085 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010086
10087 // C++ [class.friend]p1
10088 // A friend of a class is a function or class....
10089 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010090 // It *doesn't* see through dependent types, which is correct
10091 // according to [temp.arg.type]p3:
10092 // If a declaration acquires a function type through a
10093 // type dependent on a template-parameter and this causes
10094 // a declaration that does not use the syntactic form of a
10095 // function declarator to have a function type, the program
10096 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010097 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010098 Diag(Loc, diag::err_unexpected_friend);
10099
10100 // It might be worthwhile to try to recover by creating an
10101 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010102 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010103 }
10104
10105 // C++ [namespace.memdef]p3
10106 // - If a friend declaration in a non-local class first declares a
10107 // class or function, the friend class or function is a member
10108 // of the innermost enclosing namespace.
10109 // - The name of the friend is not found by simple name lookup
10110 // until a matching declaration is provided in that namespace
10111 // scope (either before or after the class declaration granting
10112 // friendship).
10113 // - If a friend function is called, its name may be found by the
10114 // name lookup that considers functions from namespaces and
10115 // classes associated with the types of the function arguments.
10116 // - When looking for a prior declaration of a class or a function
10117 // declared as a friend, scopes outside the innermost enclosing
10118 // namespace scope are not considered.
10119
John McCall337ec3d2010-10-12 23:13:28 +000010120 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010121 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10122 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010123 assert(Name);
10124
Douglas Gregor6ccab972010-12-16 01:14:37 +000010125 // Check for unexpanded parameter packs.
10126 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10127 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10128 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10129 return 0;
10130
John McCall67d1a672009-08-06 02:15:43 +000010131 // The context we found the declaration in, or in which we should
10132 // create the declaration.
10133 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010134 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010135 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010136 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010137
John McCall337ec3d2010-10-12 23:13:28 +000010138 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010139
John McCall337ec3d2010-10-12 23:13:28 +000010140 // There are four cases here.
10141 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010142 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010143 // there as appropriate.
10144 // Recover from invalid scope qualifiers as if they just weren't there.
10145 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010146 // C++0x [namespace.memdef]p3:
10147 // If the name in a friend declaration is neither qualified nor
10148 // a template-id and the declaration is a function or an
10149 // elaborated-type-specifier, the lookup to determine whether
10150 // the entity has been previously declared shall not consider
10151 // any scopes outside the innermost enclosing namespace.
10152 // C++0x [class.friend]p11:
10153 // If a friend declaration appears in a local class and the name
10154 // specified is an unqualified name, a prior declaration is
10155 // looked up without considering scopes that are outside the
10156 // innermost enclosing non-class scope. For a friend function
10157 // declaration, if there is no prior declaration, the program is
10158 // ill-formed.
10159 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010160 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010161
John McCall29ae6e52010-10-13 05:45:15 +000010162 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010163 DC = CurContext;
10164 while (true) {
10165 // Skip class contexts. If someone can cite chapter and verse
10166 // for this behavior, that would be nice --- it's what GCC and
10167 // EDG do, and it seems like a reasonable intent, but the spec
10168 // really only says that checks for unqualified existing
10169 // declarations should stop at the nearest enclosing namespace,
10170 // not that they should only consider the nearest enclosing
10171 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010172 while (DC->isRecord())
10173 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010174
John McCall68263142009-11-18 22:49:29 +000010175 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010176
10177 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010178 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010179 break;
John McCall29ae6e52010-10-13 05:45:15 +000010180
John McCall8a407372010-10-14 22:22:28 +000010181 if (isTemplateId) {
10182 if (isa<TranslationUnitDecl>(DC)) break;
10183 } else {
10184 if (DC->isFileContext()) break;
10185 }
John McCall67d1a672009-08-06 02:15:43 +000010186 DC = DC->getParent();
10187 }
10188
10189 // C++ [class.friend]p1: A friend of a class is a function or
10190 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010191 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010192 // Most C++ 98 compilers do seem to give an error here, so
10193 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010194 if (!Previous.empty() && DC->Equals(CurContext))
10195 Diag(DS.getFriendSpecLoc(),
10196 getLangOptions().CPlusPlus0x ?
10197 diag::warn_cxx98_compat_friend_is_member :
10198 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010199
John McCall380aaa42010-10-13 06:22:15 +000010200 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010201
Douglas Gregor883af832011-10-10 01:11:59 +000010202 // C++ [class.friend]p6:
10203 // A function can be defined in a friend declaration of a class if and
10204 // only if the class is a non-local class (9.8), the function name is
10205 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010206 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010207 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10208 }
10209
John McCall337ec3d2010-10-12 23:13:28 +000010210 // - There's a non-dependent scope specifier, in which case we
10211 // compute it and do a previous lookup there for a function
10212 // or function template.
10213 } else if (!SS.getScopeRep()->isDependent()) {
10214 DC = computeDeclContext(SS);
10215 if (!DC) return 0;
10216
10217 if (RequireCompleteDeclContext(SS, DC)) return 0;
10218
10219 LookupQualifiedName(Previous, DC);
10220
10221 // Ignore things found implicitly in the wrong scope.
10222 // TODO: better diagnostics for this case. Suggesting the right
10223 // qualified scope would be nice...
10224 LookupResult::Filter F = Previous.makeFilter();
10225 while (F.hasNext()) {
10226 NamedDecl *D = F.next();
10227 if (!DC->InEnclosingNamespaceSetOf(
10228 D->getDeclContext()->getRedeclContext()))
10229 F.erase();
10230 }
10231 F.done();
10232
10233 if (Previous.empty()) {
10234 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010235 Diag(Loc, diag::err_qualified_friend_not_found)
10236 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010237 return 0;
10238 }
10239
10240 // C++ [class.friend]p1: A friend of a class is a function or
10241 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010242 if (DC->Equals(CurContext))
10243 Diag(DS.getFriendSpecLoc(),
10244 getLangOptions().CPlusPlus0x ?
10245 diag::warn_cxx98_compat_friend_is_member :
10246 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010247
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010248 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010249 // C++ [class.friend]p6:
10250 // A function can be defined in a friend declaration of a class if and
10251 // only if the class is a non-local class (9.8), the function name is
10252 // unqualified, and the function has namespace scope.
10253 SemaDiagnosticBuilder DB
10254 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10255
10256 DB << SS.getScopeRep();
10257 if (DC->isFileContext())
10258 DB << FixItHint::CreateRemoval(SS.getRange());
10259 SS.clear();
10260 }
John McCall337ec3d2010-10-12 23:13:28 +000010261
10262 // - There's a scope specifier that does not match any template
10263 // parameter lists, in which case we use some arbitrary context,
10264 // create a method or method template, and wait for instantiation.
10265 // - There's a scope specifier that does match some template
10266 // parameter lists, which we don't handle right now.
10267 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010268 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010269 // C++ [class.friend]p6:
10270 // A function can be defined in a friend declaration of a class if and
10271 // only if the class is a non-local class (9.8), the function name is
10272 // unqualified, and the function has namespace scope.
10273 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10274 << SS.getScopeRep();
10275 }
10276
John McCall337ec3d2010-10-12 23:13:28 +000010277 DC = CurContext;
10278 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010279 }
Douglas Gregor883af832011-10-10 01:11:59 +000010280
John McCall29ae6e52010-10-13 05:45:15 +000010281 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010282 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010283 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10284 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10285 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010286 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010287 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10288 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010289 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010290 }
John McCall67d1a672009-08-06 02:15:43 +000010291 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010292
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010293 // FIXME: This is an egregious hack to cope with cases where the scope stack
10294 // does not contain the declaration context, i.e., in an out-of-line
10295 // definition of a class.
10296 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10297 if (!DCScope) {
10298 FakeDCScope.setEntity(DC);
10299 DCScope = &FakeDCScope;
10300 }
10301
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010302 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010303 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10304 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010305 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010306
Douglas Gregor182ddf02009-09-28 00:08:27 +000010307 assert(ND->getDeclContext() == DC);
10308 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010309
John McCallab88d972009-08-31 22:39:49 +000010310 // Add the function declaration to the appropriate lookup tables,
10311 // adjusting the redeclarations list as necessary. We don't
10312 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010313 //
John McCallab88d972009-08-31 22:39:49 +000010314 // Also update the scope-based lookup if the target context's
10315 // lookup context is in lexical scope.
10316 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010317 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010318 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010320 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010321 }
John McCall02cace72009-08-28 07:59:38 +000010322
10323 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010324 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010325 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010326 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010327 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010328
John McCall337ec3d2010-10-12 23:13:28 +000010329 if (ND->isInvalidDecl())
10330 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010331 else {
10332 FunctionDecl *FD;
10333 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10334 FD = FTD->getTemplatedDecl();
10335 else
10336 FD = cast<FunctionDecl>(ND);
10337
10338 // Mark templated-scope function declarations as unsupported.
10339 if (FD->getNumTemplateParameterLists())
10340 FrD->setUnsupportedFriend(true);
10341 }
John McCall337ec3d2010-10-12 23:13:28 +000010342
John McCalld226f652010-08-21 09:40:31 +000010343 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010344}
10345
John McCalld226f652010-08-21 09:40:31 +000010346void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10347 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010348
Sebastian Redl50de12f2009-03-24 22:27:57 +000010349 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10350 if (!Fn) {
10351 Diag(DelLoc, diag::err_deleted_non_function);
10352 return;
10353 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010354 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010355 Diag(DelLoc, diag::err_deleted_decl_not_first);
10356 Diag(Prev->getLocation(), diag::note_previous_declaration);
10357 // If the declaration wasn't the first, we delete the function anyway for
10358 // recovery.
10359 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010360 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010361}
Sebastian Redl13e88542009-04-27 21:33:24 +000010362
Sean Hunte4246a62011-05-12 06:15:49 +000010363void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10364 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10365
10366 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010367 if (MD->getParent()->isDependentType()) {
10368 MD->setDefaulted();
10369 MD->setExplicitlyDefaulted();
10370 return;
10371 }
10372
Sean Hunte4246a62011-05-12 06:15:49 +000010373 CXXSpecialMember Member = getSpecialMember(MD);
10374 if (Member == CXXInvalid) {
10375 Diag(DefaultLoc, diag::err_default_special_members);
10376 return;
10377 }
10378
10379 MD->setDefaulted();
10380 MD->setExplicitlyDefaulted();
10381
Sean Huntcd10dec2011-05-23 23:14:04 +000010382 // If this definition appears within the record, do the checking when
10383 // the record is complete.
10384 const FunctionDecl *Primary = MD;
10385 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10386 // Find the uninstantiated declaration that actually had the '= default'
10387 // on it.
10388 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10389
10390 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010391 return;
10392
10393 switch (Member) {
10394 case CXXDefaultConstructor: {
10395 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10396 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010397 if (!CD->isInvalidDecl())
10398 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10399 break;
10400 }
10401
10402 case CXXCopyConstructor: {
10403 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10404 CheckExplicitlyDefaultedCopyConstructor(CD);
10405 if (!CD->isInvalidDecl())
10406 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010407 break;
10408 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010409
Sean Hunt2b188082011-05-14 05:23:28 +000010410 case CXXCopyAssignment: {
10411 CheckExplicitlyDefaultedCopyAssignment(MD);
10412 if (!MD->isInvalidDecl())
10413 DefineImplicitCopyAssignment(DefaultLoc, MD);
10414 break;
10415 }
10416
Sean Huntcb45a0f2011-05-12 22:46:25 +000010417 case CXXDestructor: {
10418 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10419 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010420 if (!DD->isInvalidDecl())
10421 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010422 break;
10423 }
10424
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010425 case CXXMoveConstructor: {
10426 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10427 CheckExplicitlyDefaultedMoveConstructor(CD);
10428 if (!CD->isInvalidDecl())
10429 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010430 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010431 }
Sean Hunt82713172011-05-25 23:16:36 +000010432
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010433 case CXXMoveAssignment: {
10434 CheckExplicitlyDefaultedMoveAssignment(MD);
10435 if (!MD->isInvalidDecl())
10436 DefineImplicitMoveAssignment(DefaultLoc, MD);
10437 break;
10438 }
10439
10440 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010441 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010442 }
10443 } else {
10444 Diag(DefaultLoc, diag::err_default_special_members);
10445 }
10446}
10447
Sebastian Redl13e88542009-04-27 21:33:24 +000010448static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010449 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010450 Stmt *SubStmt = *CI;
10451 if (!SubStmt)
10452 continue;
10453 if (isa<ReturnStmt>(SubStmt))
10454 Self.Diag(SubStmt->getSourceRange().getBegin(),
10455 diag::err_return_in_constructor_handler);
10456 if (!isa<Expr>(SubStmt))
10457 SearchForReturnInStmt(Self, SubStmt);
10458 }
10459}
10460
10461void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10462 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10463 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10464 SearchForReturnInStmt(*this, Handler);
10465 }
10466}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010467
Mike Stump1eb44332009-09-09 15:08:12 +000010468bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010469 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010470 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10471 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010472
Chandler Carruth73857792010-02-15 11:53:20 +000010473 if (Context.hasSameType(NewTy, OldTy) ||
10474 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010475 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010476
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010477 // Check if the return types are covariant
10478 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010479
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010480 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010481 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10482 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010483 NewClassTy = NewPT->getPointeeType();
10484 OldClassTy = OldPT->getPointeeType();
10485 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010486 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10487 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10488 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10489 NewClassTy = NewRT->getPointeeType();
10490 OldClassTy = OldRT->getPointeeType();
10491 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010492 }
10493 }
Mike Stump1eb44332009-09-09 15:08:12 +000010494
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010495 // The return types aren't either both pointers or references to a class type.
10496 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010497 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010498 diag::err_different_return_type_for_overriding_virtual_function)
10499 << New->getDeclName() << NewTy << OldTy;
10500 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010501
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010502 return true;
10503 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010504
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010505 // C++ [class.virtual]p6:
10506 // If the return type of D::f differs from the return type of B::f, the
10507 // class type in the return type of D::f shall be complete at the point of
10508 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010509 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10510 if (!RT->isBeingDefined() &&
10511 RequireCompleteType(New->getLocation(), NewClassTy,
10512 PDiag(diag::err_covariant_return_incomplete)
10513 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010514 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010515 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010516
Douglas Gregora4923eb2009-11-16 21:35:15 +000010517 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010518 // Check if the new class derives from the old class.
10519 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10520 Diag(New->getLocation(),
10521 diag::err_covariant_return_not_derived)
10522 << New->getDeclName() << NewTy << OldTy;
10523 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10524 return true;
10525 }
Mike Stump1eb44332009-09-09 15:08:12 +000010526
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010527 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010528 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010529 diag::err_covariant_return_inaccessible_base,
10530 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10531 // FIXME: Should this point to the return type?
10532 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010533 // FIXME: this note won't trigger for delayed access control
10534 // diagnostics, and it's impossible to get an undelayed error
10535 // here from access control during the original parse because
10536 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010537 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10538 return true;
10539 }
10540 }
Mike Stump1eb44332009-09-09 15:08:12 +000010541
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010542 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010543 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010544 Diag(New->getLocation(),
10545 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010546 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10548 return true;
10549 };
Mike Stump1eb44332009-09-09 15:08:12 +000010550
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010551
10552 // The new class type must have the same or less qualifiers as the old type.
10553 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10554 Diag(New->getLocation(),
10555 diag::err_covariant_return_type_class_type_more_qualified)
10556 << New->getDeclName() << NewTy << OldTy;
10557 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10558 return true;
10559 };
Mike Stump1eb44332009-09-09 15:08:12 +000010560
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010561 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010562}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010563
Douglas Gregor4ba31362009-12-01 17:24:26 +000010564/// \brief Mark the given method pure.
10565///
10566/// \param Method the method to be marked pure.
10567///
10568/// \param InitRange the source range that covers the "0" initializer.
10569bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010570 SourceLocation EndLoc = InitRange.getEnd();
10571 if (EndLoc.isValid())
10572 Method->setRangeEnd(EndLoc);
10573
Douglas Gregor4ba31362009-12-01 17:24:26 +000010574 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10575 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010576 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010577 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010578
10579 if (!Method->isInvalidDecl())
10580 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10581 << Method->getDeclName() << InitRange;
10582 return true;
10583}
10584
John McCall731ad842009-12-19 09:28:58 +000010585/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10586/// an initializer for the out-of-line declaration 'Dcl'. The scope
10587/// is a fresh scope pushed for just this purpose.
10588///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010589/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10590/// static data member of class X, names should be looked up in the scope of
10591/// class X.
John McCalld226f652010-08-21 09:40:31 +000010592void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010593 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010594 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010595
John McCall731ad842009-12-19 09:28:58 +000010596 // We should only get called for declarations with scope specifiers, like:
10597 // int foo::bar;
10598 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010599 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010600}
10601
10602/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010603/// initializer for the out-of-line declaration 'D'.
10604void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010605 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010606 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010607
John McCall731ad842009-12-19 09:28:58 +000010608 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010609 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010610}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010611
10612/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10613/// C++ if/switch/while/for statement.
10614/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010615DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010616 // C++ 6.4p2:
10617 // The declarator shall not specify a function or an array.
10618 // The type-specifier-seq shall not contain typedef and shall not declare a
10619 // new class or enumeration.
10620 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10621 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010622
10623 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010624 if (!Dcl)
10625 return true;
10626
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010627 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10628 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010629 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010630 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010631 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010632
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010633 return Dcl;
10634}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010635
Douglas Gregordfe65432011-07-28 19:11:31 +000010636void Sema::LoadExternalVTableUses() {
10637 if (!ExternalSource)
10638 return;
10639
10640 SmallVector<ExternalVTableUse, 4> VTables;
10641 ExternalSource->ReadUsedVTables(VTables);
10642 SmallVector<VTableUse, 4> NewUses;
10643 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10644 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10645 = VTablesUsed.find(VTables[I].Record);
10646 // Even if a definition wasn't required before, it may be required now.
10647 if (Pos != VTablesUsed.end()) {
10648 if (!Pos->second && VTables[I].DefinitionRequired)
10649 Pos->second = true;
10650 continue;
10651 }
10652
10653 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10654 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10655 }
10656
10657 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10658}
10659
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010660void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10661 bool DefinitionRequired) {
10662 // Ignore any vtable uses in unevaluated operands or for classes that do
10663 // not have a vtable.
10664 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10665 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010666 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010667 return;
10668
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010669 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010670 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010671 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10672 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10673 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10674 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010675 // If we already had an entry, check to see if we are promoting this vtable
10676 // to required a definition. If so, we need to reappend to the VTableUses
10677 // list, since we may have already processed the first entry.
10678 if (DefinitionRequired && !Pos.first->second) {
10679 Pos.first->second = true;
10680 } else {
10681 // Otherwise, we can early exit.
10682 return;
10683 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010684 }
10685
10686 // Local classes need to have their virtual members marked
10687 // immediately. For all other classes, we mark their virtual members
10688 // at the end of the translation unit.
10689 if (Class->isLocalClass())
10690 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010691 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010692 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010693}
10694
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010695bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010696 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010697 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010698 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010699
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010700 // Note: The VTableUses vector could grow as a result of marking
10701 // the members of a class as "used", so we check the size each
10702 // time through the loop and prefer indices (with are stable) to
10703 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010704 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010705 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010706 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010707 if (!Class)
10708 continue;
10709
10710 SourceLocation Loc = VTableUses[I].second;
10711
10712 // If this class has a key function, but that key function is
10713 // defined in another translation unit, we don't need to emit the
10714 // vtable even though we're using it.
10715 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010716 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010717 switch (KeyFunction->getTemplateSpecializationKind()) {
10718 case TSK_Undeclared:
10719 case TSK_ExplicitSpecialization:
10720 case TSK_ExplicitInstantiationDeclaration:
10721 // The key function is in another translation unit.
10722 continue;
10723
10724 case TSK_ExplicitInstantiationDefinition:
10725 case TSK_ImplicitInstantiation:
10726 // We will be instantiating the key function.
10727 break;
10728 }
10729 } else if (!KeyFunction) {
10730 // If we have a class with no key function that is the subject
10731 // of an explicit instantiation declaration, suppress the
10732 // vtable; it will live with the explicit instantiation
10733 // definition.
10734 bool IsExplicitInstantiationDeclaration
10735 = Class->getTemplateSpecializationKind()
10736 == TSK_ExplicitInstantiationDeclaration;
10737 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10738 REnd = Class->redecls_end();
10739 R != REnd; ++R) {
10740 TemplateSpecializationKind TSK
10741 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10742 if (TSK == TSK_ExplicitInstantiationDeclaration)
10743 IsExplicitInstantiationDeclaration = true;
10744 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10745 IsExplicitInstantiationDeclaration = false;
10746 break;
10747 }
10748 }
10749
10750 if (IsExplicitInstantiationDeclaration)
10751 continue;
10752 }
10753
10754 // Mark all of the virtual members of this class as referenced, so
10755 // that we can build a vtable. Then, tell the AST consumer that a
10756 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010757 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010758 MarkVirtualMembersReferenced(Loc, Class);
10759 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10760 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10761
10762 // Optionally warn if we're emitting a weak vtable.
10763 if (Class->getLinkage() == ExternalLinkage &&
10764 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010765 const FunctionDecl *KeyFunctionDef = 0;
10766 if (!KeyFunction ||
10767 (KeyFunction->hasBody(KeyFunctionDef) &&
10768 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010769 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10770 TSK_ExplicitInstantiationDefinition
10771 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10772 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010773 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010774 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010775 VTableUses.clear();
10776
Douglas Gregor78844032011-04-22 22:25:37 +000010777 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010778}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010779
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010780void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10781 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010782 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10783 e = RD->method_end(); i != e; ++i) {
10784 CXXMethodDecl *MD = *i;
10785
10786 // C++ [basic.def.odr]p2:
10787 // [...] A virtual member function is used if it is not pure. [...]
10788 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010789 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010790 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010791
10792 // Only classes that have virtual bases need a VTT.
10793 if (RD->getNumVBases() == 0)
10794 return;
10795
10796 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10797 e = RD->bases_end(); i != e; ++i) {
10798 const CXXRecordDecl *Base =
10799 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010800 if (Base->getNumVBases() == 0)
10801 continue;
10802 MarkVirtualMembersReferenced(Loc, Base);
10803 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010804}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010805
10806/// SetIvarInitializers - This routine builds initialization ASTs for the
10807/// Objective-C implementation whose ivars need be initialized.
10808void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10809 if (!getLangOptions().CPlusPlus)
10810 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010811 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010812 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010813 CollectIvarsToConstructOrDestruct(OID, ivars);
10814 if (ivars.empty())
10815 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010816 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010817 for (unsigned i = 0; i < ivars.size(); i++) {
10818 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010819 if (Field->isInvalidDecl())
10820 continue;
10821
Sean Huntcbb67482011-01-08 20:30:50 +000010822 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010823 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10824 InitializationKind InitKind =
10825 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10826
10827 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010828 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010829 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010830 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010831 // Note, MemberInit could actually come back empty if no initialization
10832 // is required (e.g., because it would call a trivial default constructor)
10833 if (!MemberInit.get() || MemberInit.isInvalid())
10834 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010835
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010836 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010837 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10838 SourceLocation(),
10839 MemberInit.takeAs<Expr>(),
10840 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010841 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010842
10843 // Be sure that the destructor is accessible and is marked as referenced.
10844 if (const RecordType *RecordTy
10845 = Context.getBaseElementType(Field->getType())
10846 ->getAs<RecordType>()) {
10847 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010848 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010849 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010850 CheckDestructorAccess(Field->getLocation(), Destructor,
10851 PDiag(diag::err_access_dtor_ivar)
10852 << Context.getBaseElementType(Field->getType()));
10853 }
10854 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010855 }
10856 ObjCImplementation->setIvarInitializers(Context,
10857 AllToInit.data(), AllToInit.size());
10858 }
10859}
Sean Huntfe57eef2011-05-04 05:57:24 +000010860
Sean Huntebcbe1d2011-05-04 23:29:54 +000010861static
10862void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10863 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10864 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10865 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10866 Sema &S) {
10867 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10868 CE = Current.end();
10869 if (Ctor->isInvalidDecl())
10870 return;
10871
10872 const FunctionDecl *FNTarget = 0;
10873 CXXConstructorDecl *Target;
10874
10875 // We ignore the result here since if we don't have a body, Target will be
10876 // null below.
10877 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10878 Target
10879= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10880
10881 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10882 // Avoid dereferencing a null pointer here.
10883 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10884
10885 if (!Current.insert(Canonical))
10886 return;
10887
10888 // We know that beyond here, we aren't chaining into a cycle.
10889 if (!Target || !Target->isDelegatingConstructor() ||
10890 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10891 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10892 Valid.insert(*CI);
10893 Current.clear();
10894 // We've hit a cycle.
10895 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10896 Current.count(TCanonical)) {
10897 // If we haven't diagnosed this cycle yet, do so now.
10898 if (!Invalid.count(TCanonical)) {
10899 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010900 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010901 << Ctor;
10902
10903 // Don't add a note for a function delegating directo to itself.
10904 if (TCanonical != Canonical)
10905 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10906
10907 CXXConstructorDecl *C = Target;
10908 while (C->getCanonicalDecl() != Canonical) {
10909 (void)C->getTargetConstructor()->hasBody(FNTarget);
10910 assert(FNTarget && "Ctor cycle through bodiless function");
10911
10912 C
10913 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10914 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10915 }
10916 }
10917
10918 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10919 Invalid.insert(*CI);
10920 Current.clear();
10921 } else {
10922 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10923 }
10924}
10925
10926
Sean Huntfe57eef2011-05-04 05:57:24 +000010927void Sema::CheckDelegatingCtorCycles() {
10928 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10929
Sean Huntebcbe1d2011-05-04 23:29:54 +000010930 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10931 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010932
Douglas Gregor0129b562011-07-27 21:57:17 +000010933 for (DelegatingCtorDeclsType::iterator
10934 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010935 E = DelegatingCtorDecls.end();
10936 I != E; ++I) {
10937 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010938 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010939
10940 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10941 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010942}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010943
10944/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10945Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10946 // Implicitly declared functions (e.g. copy constructors) are
10947 // __host__ __device__
10948 if (D->isImplicit())
10949 return CFT_HostDevice;
10950
10951 if (D->hasAttr<CUDAGlobalAttr>())
10952 return CFT_Global;
10953
10954 if (D->hasAttr<CUDADeviceAttr>()) {
10955 if (D->hasAttr<CUDAHostAttr>())
10956 return CFT_HostDevice;
10957 else
10958 return CFT_Device;
10959 }
10960
10961 return CFT_Host;
10962}
10963
10964bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10965 CUDAFunctionTarget CalleeTarget) {
10966 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10967 // Callable from the device only."
10968 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10969 return true;
10970
10971 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10972 // Callable from the host only."
10973 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10974 // Callable from the host only."
10975 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10976 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10977 return true;
10978
10979 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10980 return true;
10981
10982 return false;
10983}