blob: 624dc5d1e6ff087111dbbf8530101245dab3ee5d [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman25b07422012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000027#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000029#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000030#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000034#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000035#include "llvm/ADT/DenseSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000036#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000037#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000038#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000039#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000040
41using namespace clang;
42
Chris Lattner58258242008-04-10 02:22:51 +000043//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000053 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000054 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 Expr *DefaultArg;
56 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 public:
Mike Stump11289f42009-09-09 15:08:12 +000059 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 bool VisitExpr(Expr *Node);
63 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000064 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000065 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 };
Chris Lattner58258242008-04-10 02:22:51 +000067
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000071 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000072 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000074 }
75
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000080 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000092 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000093 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000094 // C++ [dcl.fct.default]p7
95 // Local variables shall not be used in default argument
96 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000097 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000098 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000100 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101 }
Chris Lattner58258242008-04-10 02:22:51 +0000102
Douglas Gregor8e12c382008-11-04 13:41:56 +0000103 return false;
104 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000112 diag::err_param_default_argument_references_this)
113 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000114 }
Douglas Gregorf0d49512012-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 Lattner58258242008-04-10 02:22:51 +0000126}
127
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000129 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-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)
Alexis Hunt6d5b96c2011-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 Smith938f40b2011-06-11 17:19:42 +0000140 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000141 ClearExceptions();
142 ComputedEST = EST;
143 return;
144 }
145
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000167 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-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)
Alexis Hunt913820d2011-05-13 06:10:58 +0000191 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000192 Exceptions.push_back(*E);
193}
194
Richard Smith938f40b2011-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 Takumi53648472011-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 Smith938f40b2011-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 Carlssonc80a1272009-08-25 02:29:20 +0000224bool
John McCallb268a282010-08-23 23:25:46 +0000225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000226 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000239 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000241 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000243 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000245 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000246 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000247 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000248 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249
John McCallacf0ee52010-10-08 02:01:28 +0000250 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000251 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000252
Anders Carlssonc80a1272009-08-25 02:29:20 +0000253 // Okay: add the default argument to the parameter
254 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000268 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000269}
270
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000274void
John McCall48871652010-08-21 09:40:31 +0000275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000276 Expr *DefaultArg) {
277 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000278 return;
Mike Stump11289f42009-09-09 15:08:12 +0000279
John McCall48871652010-08-21 09:40:31 +0000280 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000281 UnparsedDefaultArgLocs.erase(Param);
282
Chris Lattner199abbc2008-04-08 05:04:30 +0000283 // Default arguments are only permitted in C++
284 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000285 Diag(EqualLoc, diag::err_param_default_argument)
286 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000287 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000288 return;
289 }
290
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000297 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000298 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000300 Param->setInvalidDecl();
301 return;
302 }
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCallb268a282010-08-23 23:25:46 +0000304 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000305}
306
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000312 SourceLocation EqualLoc,
313 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump11289f42009-09-09 15:08:12 +0000316
John McCall48871652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000318 if (Param)
319 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000320
Anders Carlsson84613c42009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000322}
323
Douglas Gregor4d87df52008-12-16 21:30:33 +0000324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000327 if (!param)
328 return;
Mike Stump11289f42009-09-09 15:08:12 +0000329
John McCall48871652010-08-21 09:40:31 +0000330 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Anders Carlsson84613c42009-06-12 16:51:40 +0000332 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000333
Anders Carlsson84613c42009-06-12 16:51:40 +0000334 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000335}
336
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000350 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000351 DeclaratorChunk &chunk = D.getTypeObject(i);
352 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000353 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000355 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000356 if (Param->hasUnparsedDefaultArg()) {
357 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000366 }
367 }
368 }
369 }
370}
371
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000379 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000401 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000402
Francois Pichet53fe2bb2011-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 Pichet0706d202011-09-17 17:15:52 +0000409 if (getLangOptions().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000410 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
411 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000419 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000420 Invalid = false;
421 }
422 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000423
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000429 // int f(int);
430 // void g(int (*fp)(int) = f);
431 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000432 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000433 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregorec9fd132012-01-14 16:38:05 +0000437 for (FunctionDecl *Older = Old->getPreviousDecl();
438 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000447 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000450 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000451 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000452 if (OldParam->hasUninstantiatedDefaultArg())
453 NewParam->setUninstantiatedDefaultArg(
454 OldParam->getUninstantiatedDefaultArg());
455 else
John McCalle61b02b2010-05-04 01:53:42 +0000456 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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();
Alexis Huntd051b872011-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 Gregorc732aba2009-09-11 18:44:32 +0000515 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000516 }
517 }
518
Richard Smitheb3c10c2011-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 Gregorf40863c2010-02-12 07:32:17 +0000533 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000534 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000535
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000536 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000537}
538
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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
Douglas Gregoradb376e2012-02-14 22:28:59 +0000588 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
589 isa<CXXMethodDecl>(FD) &&
590 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
591
Chris Lattner199abbc2008-04-08 05:04:30 +0000592 // Find first parameter with a default argument
593 for (p = 0; p < NumParams; ++p) {
594 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregoradb376e2012-02-14 22:28:59 +0000595 if (Param->hasDefaultArg()) {
596 // C++11 [expr.prim.lambda]p5:
597 // [...] Default arguments (8.3.6) shall not be specified in the
598 // parameter-declaration-clause of a lambda-declarator.
599 //
600 // FIXME: Core issue 974 strikes this sentence, we only provide an
601 // extension warning.
602 if (IsLambda)
603 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
604 << Param->getDefaultArgRange();
Chris Lattner199abbc2008-04-08 05:04:30 +0000605 break;
Douglas Gregoradb376e2012-02-14 22:28:59 +0000606 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000607 }
608
609 // C++ [dcl.fct.default]p4:
610 // In a given function declaration, all parameters
611 // subsequent to a parameter with a default argument shall
612 // have default arguments supplied in this or previous
613 // declarations. A default argument shall not be redefined
614 // by a later declaration (not even to the same value).
615 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000616 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000617 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000618 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000619 if (Param->isInvalidDecl())
620 /* We already complained about this parameter. */;
621 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000622 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000623 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000624 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000625 else
Mike Stump11289f42009-09-09 15:08:12 +0000626 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000627 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner199abbc2008-04-08 05:04:30 +0000629 LastMissingDefaultArg = p;
630 }
631 }
632
633 if (LastMissingDefaultArg > 0) {
634 // Some default arguments were missing. Clear out all of the
635 // default arguments up to (and including) the last missing
636 // default argument, so that we leave the function parameters
637 // in a semantically valid state.
638 for (p = 0; p <= LastMissingDefaultArg; ++p) {
639 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000640 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000641 Param->setDefaultArg(0);
642 }
643 }
644 }
645}
Douglas Gregor556877c2008-04-13 21:30:24 +0000646
Richard Smitheb3c10c2011-10-01 02:31:28 +0000647// CheckConstexprParameterTypes - Check whether a function's parameter types
648// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000649// diagnostic and return false.
650static bool CheckConstexprParameterTypes(Sema &SemaRef,
651 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000652 unsigned ArgIndex = 0;
653 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
654 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
655 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
656 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
657 SourceLocation ParamLoc = PD->getLocation();
658 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000659 SemaRef.RequireLiteralType(ParamLoc, *i,
Richard Smitheb3c10c2011-10-01 02:31:28 +0000660 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
661 << ArgIndex+1 << PD->getSourceRange()
Richard Smith3607ffe2012-02-13 03:54:03 +0000662 << isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000663 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000664 }
665 return true;
666}
667
668// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith3607ffe2012-02-13 03:54:03 +0000669// the requirements of a constexpr function definition or a constexpr
670// constructor definition. If so, return true. If not, produce appropriate
671// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000672//
Richard Smith3607ffe2012-02-13 03:54:03 +0000673// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
674bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000675 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
676 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000677 // C++11 [dcl.constexpr]p4:
678 // The definition of a constexpr constructor shall satisfy the following
679 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000680 // - the class shall not have any virtual base classes;
Richard Smith7971b692012-01-13 04:54:00 +0000681 const CXXRecordDecl *RD = MD->getParent();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000682 if (RD->getNumVBases()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000683 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
684 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
685 << RD->getNumVBases();
686 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
687 E = RD->vbases_end(); I != E; ++I)
688 Diag(I->getSourceRange().getBegin(),
689 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000690 return false;
691 }
Richard Smith7971b692012-01-13 04:54:00 +0000692 }
693
694 if (!isa<CXXConstructorDecl>(NewFD)) {
695 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000696 // The definition of a constexpr function shall satisfy the following
697 // constraints:
698 // - it shall not be virtual;
699 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
700 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000701 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000702
Richard Smith3607ffe2012-02-13 03:54:03 +0000703 // If it's not obvious why this function is virtual, find an overridden
704 // function which uses the 'virtual' keyword.
705 const CXXMethodDecl *WrittenVirtual = Method;
706 while (!WrittenVirtual->isVirtualAsWritten())
707 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
708 if (WrittenVirtual != Method)
709 Diag(WrittenVirtual->getLocation(),
710 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000717 RequireLiteralType(NewFD->getLocation(), RT,
718 PDiag(diag::err_constexpr_non_literal_return)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000719 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 }
721
Richard Smith7971b692012-01-13 04:54:00 +0000722 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000723 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000724 return false;
725
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 return true;
727}
728
729/// Check the given declaration statement is legal within a constexpr function
730/// body. C++0x [dcl.constexpr]p3,p4.
731///
732/// \return true if the body is OK, false if we have diagnosed a problem.
733static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
734 DeclStmt *DS) {
735 // C++0x [dcl.constexpr]p3 and p4:
736 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
737 // contain only
738 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
739 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
740 switch ((*DclIt)->getKind()) {
741 case Decl::StaticAssert:
742 case Decl::Using:
743 case Decl::UsingShadow:
744 case Decl::UsingDirective:
745 case Decl::UnresolvedUsingTypename:
746 // - static_assert-declarations
747 // - using-declarations,
748 // - using-directives,
749 continue;
750
751 case Decl::Typedef:
752 case Decl::TypeAlias: {
753 // - typedef declarations and alias-declarations that do not define
754 // classes or enumerations,
755 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
756 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
757 // Don't allow variably-modified types in constexpr functions.
758 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
759 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
760 << TL.getSourceRange() << TL.getType()
761 << isa<CXXConstructorDecl>(Dcl);
762 return false;
763 }
764 continue;
765 }
766
767 case Decl::Enum:
768 case Decl::CXXRecord:
769 // As an extension, we allow the declaration (but not the definition) of
770 // classes and enumerations in all declarations, not just in typedef and
771 // alias declarations.
772 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
773 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
774 << isa<CXXConstructorDecl>(Dcl);
775 return false;
776 }
777 continue;
778
779 case Decl::Var:
780 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
781 << isa<CXXConstructorDecl>(Dcl);
782 return false;
783
784 default:
785 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
786 << isa<CXXConstructorDecl>(Dcl);
787 return false;
788 }
789 }
790
791 return true;
792}
793
794/// Check that the given field is initialized within a constexpr constructor.
795///
796/// \param Dcl The constexpr constructor being checked.
797/// \param Field The field being checked. This may be a member of an anonymous
798/// struct or union nested within the class being checked.
799/// \param Inits All declarations, including anonymous struct/union members and
800/// indirect members, for which any initialization was provided.
801/// \param Diagnosed Set to true if an error is produced.
802static void CheckConstexprCtorInitializer(Sema &SemaRef,
803 const FunctionDecl *Dcl,
804 FieldDecl *Field,
805 llvm::SmallSet<Decl*, 16> &Inits,
806 bool &Diagnosed) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000807 if (Field->isUnnamedBitfield())
808 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000809
810 if (Field->isAnonymousStructOrUnion() &&
811 Field->getType()->getAsCXXRecordDecl()->isEmpty())
812 return;
813
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814 if (!Inits.count(Field)) {
815 if (!Diagnosed) {
816 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
817 Diagnosed = true;
818 }
819 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
820 } else if (Field->isAnonymousStructOrUnion()) {
821 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
822 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
823 I != E; ++I)
824 // If an anonymous union contains an anonymous struct of which any member
825 // is initialized, all members must be initialized.
826 if (!RD->isUnion() || Inits.count(*I))
827 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
828 }
829}
830
831/// Check the body for the given constexpr function declaration only contains
832/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
833///
834/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +0000835bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000836 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +0000837 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000838 // The definition of a constexpr function shall satisfy the following
839 // constraints: [...]
840 // - its function-body shall be = delete, = default, or a
841 // compound-statement
842 //
Richard Smith74388b42012-02-04 00:33:54 +0000843 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000844 // In the definition of a constexpr constructor, [...]
845 // - its function-body shall not be a function-try-block;
846 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
847 << isa<CXXConstructorDecl>(Dcl);
848 return false;
849 }
850
851 // - its function-body shall be [...] a compound-statement that contains only
852 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
853
854 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
855 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
856 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
857 switch ((*BodyIt)->getStmtClass()) {
858 case Stmt::NullStmtClass:
859 // - null statements,
860 continue;
861
862 case Stmt::DeclStmtClass:
863 // - static_assert-declarations
864 // - using-declarations,
865 // - using-directives,
866 // - typedef declarations and alias-declarations that do not define
867 // classes or enumerations,
868 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
869 return false;
870 continue;
871
872 case Stmt::ReturnStmtClass:
873 // - and exactly one return statement;
874 if (isa<CXXConstructorDecl>(Dcl))
875 break;
876
877 ReturnStmts.push_back((*BodyIt)->getLocStart());
878 // FIXME
879 // - every constructor call and implicit conversion used in initializing
880 // the return value shall be one of those allowed in a constant
881 // expression.
882 // Deal with this as part of a general check that the function can produce
883 // a constant expression (for [dcl.constexpr]p5).
884 continue;
885
886 default:
887 break;
888 }
889
890 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894
895 if (const CXXConstructorDecl *Constructor
896 = dyn_cast<CXXConstructorDecl>(Dcl)) {
897 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +0000898 // DR1359:
899 // - every non-variant non-static data member and base class sub-object
900 // shall be initialized;
901 // - if the class is a non-empty union, or for each non-empty anonymous
902 // union member of a non-union class, exactly one non-static data member
903 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000904 if (RD->isUnion()) {
Richard Smith4d59eeb2012-02-09 06:40:58 +0000905 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
907 return false;
908 }
Richard Smithf368fb42011-10-10 16:38:04 +0000909 } else if (!Constructor->isDependentContext() &&
910 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
912
913 // Skip detailed checking if we have enough initializers, and we would
914 // allow at most one initializer per member.
915 bool AnyAnonStructUnionMembers = false;
916 unsigned Fields = 0;
917 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
918 E = RD->field_end(); I != E; ++I, ++Fields) {
919 if ((*I)->isAnonymousStructOrUnion()) {
920 AnyAnonStructUnionMembers = true;
921 break;
922 }
923 }
924 if (AnyAnonStructUnionMembers ||
925 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
926 // Check initialization of non-static data members. Base classes are
927 // always initialized so do not need to be checked. Dependent bases
928 // might not have initializers in the member initializer list.
929 llvm::SmallSet<Decl*, 16> Inits;
930 for (CXXConstructorDecl::init_const_iterator
931 I = Constructor->init_begin(), E = Constructor->init_end();
932 I != E; ++I) {
933 if (FieldDecl *FD = (*I)->getMember())
934 Inits.insert(FD);
935 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
936 Inits.insert(ID->chain_begin(), ID->chain_end());
937 }
938
939 bool Diagnosed = false;
940 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941 E = RD->field_end(); I != E; ++I)
942 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
943 if (Diagnosed)
944 return false;
945 }
946 }
947
948 // FIXME
949 // - every constructor involved in initializing non-static data members
950 // and base class sub-objects shall be a constexpr constructor;
951 // - every assignment-expression that is an initializer-clause appearing
952 // directly or indirectly within a brace-or-equal-initializer for
953 // a non-static data member that is not named by a mem-initializer-id
954 // shall be a constant expression; and
955 // - every implicit conversion used in converting a constructor argument
956 // to the corresponding parameter type and converting
957 // a full-expression to the corresponding member type shall be one of
958 // those allowed in a constant expression.
959 // Deal with these as part of a general check that the function can produce
960 // a constant expression (for [dcl.constexpr]p5).
961 } else {
962 if (ReturnStmts.empty()) {
963 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
964 return false;
965 }
966 if (ReturnStmts.size() > 1) {
967 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
968 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
969 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
970 return false;
971 }
972 }
973
Richard Smith74388b42012-02-04 00:33:54 +0000974 // C++11 [dcl.constexpr]p5:
975 // if no function argument values exist such that the function invocation
976 // substitution would produce a constant expression, the program is
977 // ill-formed; no diagnostic required.
978 // C++11 [dcl.constexpr]p3:
979 // - every constructor call and implicit conversion used in initializing the
980 // return value shall be one of those allowed in a constant expression.
981 // C++11 [dcl.constexpr]p4:
982 // - every constructor involved in initializing non-static data members and
983 // base class sub-objects shall be a constexpr constructor.
Richard Smith253c2a32012-01-27 01:14:48 +0000984 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +0000985 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith253c2a32012-01-27 01:14:48 +0000986 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
987 << isa<CXXConstructorDecl>(Dcl);
988 for (size_t I = 0, N = Diags.size(); I != N; ++I)
989 Diag(Diags[I].first, Diags[I].second);
990 return false;
991 }
992
Richard Smitheb3c10c2011-10-01 02:31:28 +0000993 return true;
994}
995
Douglas Gregor61956c42008-10-31 09:07:45 +0000996/// isCurrentClassName - Determine whether the identifier II is the
997/// name of the class type currently being defined. In the case of
998/// nested classes, this will only return true if II is the name of
999/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001000bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1001 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001002 assert(getLangOptions().CPlusPlus && "No class names in C!");
1003
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001004 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001005 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001006 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001007 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1008 } else
1009 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1010
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001011 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001012 return &II == CurDecl->getIdentifier();
1013 else
1014 return false;
1015}
1016
Mike Stump11289f42009-09-09 15:08:12 +00001017/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001018///
1019/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1020/// and returns NULL otherwise.
1021CXXBaseSpecifier *
1022Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1023 SourceRange SpecifierRange,
1024 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001025 TypeSourceInfo *TInfo,
1026 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001027 QualType BaseType = TInfo->getType();
1028
Douglas Gregor463421d2009-03-03 04:44:36 +00001029 // C++ [class.union]p1:
1030 // A union shall not have base classes.
1031 if (Class->isUnion()) {
1032 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1033 << SpecifierRange;
1034 return 0;
1035 }
1036
Douglas Gregor752a5952011-01-03 22:36:02 +00001037 if (EllipsisLoc.isValid() &&
1038 !TInfo->getType()->containsUnexpandedParameterPack()) {
1039 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1040 << TInfo->getTypeLoc().getSourceRange();
1041 EllipsisLoc = SourceLocation();
1042 }
1043
Douglas Gregor463421d2009-03-03 04:44:36 +00001044 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001045 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001046 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001047 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001048
1049 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001050
1051 // Base specifiers must be record types.
1052 if (!BaseType->isRecordType()) {
1053 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1054 return 0;
1055 }
1056
1057 // C++ [class.union]p1:
1058 // A union shall not be used as a base class.
1059 if (BaseType->isUnionType()) {
1060 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1061 return 0;
1062 }
1063
1064 // C++ [class.derived]p2:
1065 // The class-name in a base-specifier shall not be an incompletely
1066 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001067 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001068 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001069 << SpecifierRange)) {
1070 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001071 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001072 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001073
Eli Friedmanc96d4962009-08-15 21:55:26 +00001074 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001075 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001076 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001077 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001078 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001079 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1080 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001081
Anders Carlsson65c76d32011-03-25 14:55:14 +00001082 // C++ [class]p3:
1083 // If a class is marked final and it appears as a base-type-specifier in
1084 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001085 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001086 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1087 << CXXBaseDecl->getDeclName();
1088 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1089 << CXXBaseDecl->getDeclName();
1090 return 0;
1091 }
1092
John McCall3696dcb2010-08-17 07:23:57 +00001093 if (BaseDecl->isInvalidDecl())
1094 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001095
1096 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001097 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001098 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001099 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001100}
1101
Douglas Gregor556877c2008-04-13 21:30:24 +00001102/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1103/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001104/// example:
1105/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001106/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001107BaseResult
John McCall48871652010-08-21 09:40:31 +00001108Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001109 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001110 ParsedType basetype, SourceLocation BaseLoc,
1111 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001112 if (!classdecl)
1113 return true;
1114
Douglas Gregorc40290e2009-03-09 23:48:35 +00001115 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001116 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001117 if (!Class)
1118 return true;
1119
Nick Lewycky19b9f952010-07-26 16:56:01 +00001120 TypeSourceInfo *TInfo = 0;
1121 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001122
Douglas Gregor752a5952011-01-03 22:36:02 +00001123 if (EllipsisLoc.isInvalid() &&
1124 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001125 UPPC_BaseType))
1126 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001127
Douglas Gregor463421d2009-03-03 04:44:36 +00001128 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001129 Virtual, Access, TInfo,
1130 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001131 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregor463421d2009-03-03 04:44:36 +00001133 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001134}
Douglas Gregor556877c2008-04-13 21:30:24 +00001135
Douglas Gregor463421d2009-03-03 04:44:36 +00001136/// \brief Performs the actual work of attaching the given base class
1137/// specifiers to a C++ class.
1138bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1139 unsigned NumBases) {
1140 if (NumBases == 0)
1141 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001142
1143 // Used to keep track of which base types we have already seen, so
1144 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001145 // that the key is always the unqualified canonical type of the base
1146 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001147 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1148
1149 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001150 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001151 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001152 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001153 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001154 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001155 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001156 if (KnownBaseTypes[NewBaseType]) {
1157 // C++ [class.mi]p3:
1158 // A class shall not be specified as a direct base class of a
1159 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001160 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001161 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001162 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001163 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001164
1165 // Delete the duplicate base class specifier; we're going to
1166 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001167 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001168
1169 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001170 } else {
1171 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001172 KnownBaseTypes[NewBaseType] = Bases[idx];
1173 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian28f5fb92011-10-24 17:30:45 +00001174 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian47f9a732011-10-21 22:27:12 +00001175 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1176 if (RD->hasAttr<WeakAttr>())
1177 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregor29a92472008-10-22 17:49:05 +00001178 }
1179 }
1180
1181 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001182 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001183
1184 // Delete the remaining (good) base class specifiers, since their
1185 // data has been copied into the CXXRecordDecl.
1186 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001187 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001188
1189 return Invalid;
1190}
1191
1192/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1193/// class, after checking whether there are any duplicate base
1194/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001195void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001196 unsigned NumBases) {
1197 if (!ClassDecl || !Bases || !NumBases)
1198 return;
1199
1200 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001201 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001202 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001203}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001204
John McCalle78aac42010-03-10 03:28:59 +00001205static CXXRecordDecl *GetClassForType(QualType T) {
1206 if (const RecordType *RT = T->getAs<RecordType>())
1207 return cast<CXXRecordDecl>(RT->getDecl());
1208 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1209 return ICT->getDecl();
1210 else
1211 return 0;
1212}
1213
Douglas Gregor36d1b142009-10-06 17:59:45 +00001214/// \brief Determine whether the type \p Derived is a C++ class that is
1215/// derived from the type \p Base.
1216bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1217 if (!getLangOptions().CPlusPlus)
1218 return false;
John McCalle78aac42010-03-10 03:28:59 +00001219
1220 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1221 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001222 return false;
1223
John McCalle78aac42010-03-10 03:28:59 +00001224 CXXRecordDecl *BaseRD = GetClassForType(Base);
1225 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001226 return false;
1227
John McCall67da35c2010-02-04 22:26:26 +00001228 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1229 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001230}
1231
1232/// \brief Determine whether the type \p Derived is a C++ class that is
1233/// derived from the type \p Base.
1234bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1235 if (!getLangOptions().CPlusPlus)
1236 return false;
1237
John McCalle78aac42010-03-10 03:28:59 +00001238 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1239 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001240 return false;
1241
John McCalle78aac42010-03-10 03:28:59 +00001242 CXXRecordDecl *BaseRD = GetClassForType(Base);
1243 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001244 return false;
1245
Douglas Gregor36d1b142009-10-06 17:59:45 +00001246 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1247}
1248
Anders Carlssona70cff62010-04-24 19:06:50 +00001249void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001250 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001251 assert(BasePathArray.empty() && "Base path array must be empty!");
1252 assert(Paths.isRecordingPaths() && "Must record paths!");
1253
1254 const CXXBasePath &Path = Paths.front();
1255
1256 // We first go backward and check if we have a virtual base.
1257 // FIXME: It would be better if CXXBasePath had the base specifier for
1258 // the nearest virtual base.
1259 unsigned Start = 0;
1260 for (unsigned I = Path.size(); I != 0; --I) {
1261 if (Path[I - 1].Base->isVirtual()) {
1262 Start = I - 1;
1263 break;
1264 }
1265 }
1266
1267 // Now add all bases.
1268 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001269 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001270}
1271
Douglas Gregor88d292c2010-05-13 16:44:06 +00001272/// \brief Determine whether the given base path includes a virtual
1273/// base class.
John McCallcf142162010-08-07 06:22:56 +00001274bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1275 for (CXXCastPath::const_iterator B = BasePath.begin(),
1276 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001277 B != BEnd; ++B)
1278 if ((*B)->isVirtual())
1279 return true;
1280
1281 return false;
1282}
1283
Douglas Gregor36d1b142009-10-06 17:59:45 +00001284/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1285/// conversion (where Derived and Base are class types) is
1286/// well-formed, meaning that the conversion is unambiguous (and
1287/// that all of the base classes are accessible). Returns true
1288/// and emits a diagnostic if the code is ill-formed, returns false
1289/// otherwise. Loc is the location where this routine should point to
1290/// if there is an error, and Range is the source range to highlight
1291/// if there is an error.
1292bool
1293Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001294 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001295 unsigned AmbigiousBaseConvID,
1296 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001297 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001298 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001299 // First, determine whether the path from Derived to Base is
1300 // ambiguous. This is slightly more expensive than checking whether
1301 // the Derived to Base conversion exists, because here we need to
1302 // explore multiple paths to determine if there is an ambiguity.
1303 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1304 /*DetectVirtual=*/false);
1305 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1306 assert(DerivationOkay &&
1307 "Can only be used with a derived-to-base conversion");
1308 (void)DerivationOkay;
1309
1310 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001311 if (InaccessibleBaseID) {
1312 // Check that the base class can be accessed.
1313 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1314 InaccessibleBaseID)) {
1315 case AR_inaccessible:
1316 return true;
1317 case AR_accessible:
1318 case AR_dependent:
1319 case AR_delayed:
1320 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001321 }
John McCall5b0829a2010-02-10 09:31:12 +00001322 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001323
1324 // Build a base path if necessary.
1325 if (BasePath)
1326 BuildBasePathArray(Paths, *BasePath);
1327 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001328 }
1329
1330 // We know that the derived-to-base conversion is ambiguous, and
1331 // we're going to produce a diagnostic. Perform the derived-to-base
1332 // search just one more time to compute all of the possible paths so
1333 // that we can print them out. This is more expensive than any of
1334 // the previous derived-to-base checks we've done, but at this point
1335 // performance isn't as much of an issue.
1336 Paths.clear();
1337 Paths.setRecordingPaths(true);
1338 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1339 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1340 (void)StillOkay;
1341
1342 // Build up a textual representation of the ambiguous paths, e.g.,
1343 // D -> B -> A, that will be used to illustrate the ambiguous
1344 // conversions in the diagnostic. We only print one of the paths
1345 // to each base class subobject.
1346 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1347
1348 Diag(Loc, AmbigiousBaseConvID)
1349 << Derived << Base << PathDisplayStr << Range << Name;
1350 return true;
1351}
1352
1353bool
1354Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001355 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001356 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001357 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001358 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001359 IgnoreAccess ? 0
1360 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001361 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001362 Loc, Range, DeclarationName(),
1363 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001364}
1365
1366
1367/// @brief Builds a string representing ambiguous paths from a
1368/// specific derived class to different subobjects of the same base
1369/// class.
1370///
1371/// This function builds a string that can be used in error messages
1372/// to show the different paths that one can take through the
1373/// inheritance hierarchy to go from the derived class to different
1374/// subobjects of a base class. The result looks something like this:
1375/// @code
1376/// struct D -> struct B -> struct A
1377/// struct D -> struct C -> struct A
1378/// @endcode
1379std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1380 std::string PathDisplayStr;
1381 std::set<unsigned> DisplayedPaths;
1382 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1383 Path != Paths.end(); ++Path) {
1384 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1385 // We haven't displayed a path to this particular base
1386 // class subobject yet.
1387 PathDisplayStr += "\n ";
1388 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1389 for (CXXBasePath::const_iterator Element = Path->begin();
1390 Element != Path->end(); ++Element)
1391 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1392 }
1393 }
1394
1395 return PathDisplayStr;
1396}
1397
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001398//===----------------------------------------------------------------------===//
1399// C++ class member Handling
1400//===----------------------------------------------------------------------===//
1401
Abramo Bagnarad7340582010-06-05 05:09:32 +00001402/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001403bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1404 SourceLocation ASLoc,
1405 SourceLocation ColonLoc,
1406 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001407 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001408 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001409 ASLoc, ColonLoc);
1410 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001411 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001412}
1413
Anders Carlssonfd835532011-01-20 05:57:14 +00001414/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001415void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001416 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001417 if (!MD || !MD->isVirtual())
1418 return;
1419
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001420 if (MD->isDependentContext())
1421 return;
1422
Anders Carlssonfd835532011-01-20 05:57:14 +00001423 // C++0x [class.virtual]p3:
1424 // If a virtual function is marked with the virt-specifier override and does
1425 // not override a member function of a base class,
1426 // the program is ill-formed.
1427 bool HasOverriddenMethods =
1428 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001429 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001430 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001431 diag::err_function_marked_override_not_overriding)
1432 << MD->getDeclName();
1433 return;
1434 }
1435}
1436
Anders Carlsson3f610c72011-01-20 16:25:36 +00001437/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1438/// function overrides a virtual member function marked 'final', according to
1439/// C++0x [class.virtual]p3.
1440bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1441 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001442 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001443 return false;
1444
1445 Diag(New->getLocation(), diag::err_final_function_overridden)
1446 << New->getDeclName();
1447 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1448 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001449}
1450
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001451/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1452/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001453/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1454/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1455/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001456Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001457Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001458 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001459 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001460 bool HasDeferredInit) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001461 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001462 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1463 DeclarationName Name = NameInfo.getName();
1464 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001465
1466 // For anonymous bitfields, the location should point to the type.
1467 if (Loc.isInvalid())
1468 Loc = D.getSourceRange().getBegin();
1469
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001470 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001471
John McCallb1cd7da2010-06-04 08:34:12 +00001472 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001473 assert(!DS.isFriendSpecified());
1474
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001475 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001476
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001477 // C++ 9.2p6: A member shall not be declared to have automatic storage
1478 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001479 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1480 // data members and cannot be applied to names declared const or static,
1481 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001482 switch (DS.getStorageClassSpec()) {
1483 case DeclSpec::SCS_unspecified:
1484 case DeclSpec::SCS_typedef:
1485 case DeclSpec::SCS_static:
1486 // FALL THROUGH.
1487 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001488 case DeclSpec::SCS_mutable:
1489 if (isFunc) {
1490 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001491 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001492 else
Chris Lattner3b054132008-11-19 05:08:23 +00001493 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001494
Sebastian Redl8071edb2008-11-17 23:24:37 +00001495 // FIXME: It would be nicer if the keyword was ignored only for this
1496 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001497 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001498 }
1499 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001500 default:
1501 if (DS.getStorageClassSpecLoc().isValid())
1502 Diag(DS.getStorageClassSpecLoc(),
1503 diag::err_storageclass_invalid_for_member);
1504 else
1505 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1506 D.getMutableDeclSpec().ClearStorageClassSpecs();
1507 }
1508
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001509 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1510 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001511 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001512
1513 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001514 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001515 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001516
1517 // Data members must have identifiers for names.
1518 if (Name.getNameKind() != DeclarationName::Identifier) {
1519 Diag(Loc, diag::err_bad_variable_name)
1520 << Name;
1521 return 0;
1522 }
Douglas Gregora007d362010-10-13 22:19:53 +00001523
Douglas Gregor7c26c042011-09-21 14:40:46 +00001524 IdentifierInfo *II = Name.getAsIdentifierInfo();
1525
1526 // Member field could not be with "template" keyword.
1527 // So TemplateParameterLists should be empty in this case.
1528 if (TemplateParameterLists.size()) {
1529 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1530 if (TemplateParams->size()) {
1531 // There is no such thing as a member field template.
1532 Diag(D.getIdentifierLoc(), diag::err_template_member)
1533 << II
1534 << SourceRange(TemplateParams->getTemplateLoc(),
1535 TemplateParams->getRAngleLoc());
1536 } else {
1537 // There is an extraneous 'template<>' for this member.
1538 Diag(TemplateParams->getTemplateLoc(),
1539 diag::err_template_member_noparams)
1540 << II
1541 << SourceRange(TemplateParams->getTemplateLoc(),
1542 TemplateParams->getRAngleLoc());
1543 }
1544 return 0;
1545 }
1546
Douglas Gregora007d362010-10-13 22:19:53 +00001547 if (SS.isSet() && !SS.isInvalid()) {
1548 // The user provided a superfluous scope specifier inside a class
1549 // definition:
1550 //
1551 // class X {
1552 // int X::member;
1553 // };
1554 DeclContext *DC = 0;
1555 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1556 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001557 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregora007d362010-10-13 22:19:53 +00001558 else
1559 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1560 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001561
Douglas Gregora007d362010-10-13 22:19:53 +00001562 SS.clear();
1563 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001564
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001565 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001566 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001567 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001568 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001569 assert(!HasDeferredInit);
1570
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001571 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner97e277e2009-03-05 23:03:49 +00001572 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001573 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001574 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001575
1576 // Non-instance-fields can't have a bitfield.
1577 if (BitWidth) {
1578 if (Member->isInvalidDecl()) {
1579 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001580 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001581 // C++ 9.6p3: A bit-field shall not be a static member.
1582 // "static member 'A' cannot be a bit-field"
1583 Diag(Loc, diag::err_static_not_bitfield)
1584 << Name << BitWidth->getSourceRange();
1585 } else if (isa<TypedefDecl>(Member)) {
1586 // "typedef member 'x' cannot be a bit-field"
1587 Diag(Loc, diag::err_typedef_not_bitfield)
1588 << Name << BitWidth->getSourceRange();
1589 } else {
1590 // A function typedef ("typedef int f(); f a;").
1591 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1592 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001593 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001594 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001595 }
Mike Stump11289f42009-09-09 15:08:12 +00001596
Chris Lattnerd26760a2009-03-05 23:01:03 +00001597 BitWidth = 0;
1598 Member->setInvalidDecl();
1599 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001600
1601 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregor3447e762009-08-20 22:52:58 +00001603 // If we have declared a member function template, set the access of the
1604 // templated declaration as well.
1605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1606 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001607 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001608
Anders Carlsson13a69102011-01-20 04:34:22 +00001609 if (VS.isOverrideSpecified()) {
1610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1611 if (!MD || !MD->isVirtual()) {
1612 Diag(Member->getLocStart(),
1613 diag::override_keyword_only_allowed_on_virtual_member_functions)
1614 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001615 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001616 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001617 }
1618 if (VS.isFinalSpecified()) {
1619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1620 if (!MD || !MD->isVirtual()) {
1621 Diag(Member->getLocStart(),
1622 diag::override_keyword_only_allowed_on_virtual_member_functions)
1623 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001624 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001625 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001626 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001627
Douglas Gregorf2f08062011-03-08 17:10:18 +00001628 if (VS.getLastLocation().isValid()) {
1629 // Update the end location of a method that has a virt-specifiers.
1630 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1631 MD->setRangeEnd(VS.getLastLocation());
1632 }
1633
Anders Carlssonc87f8612011-01-20 06:29:02 +00001634 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001635
Douglas Gregor92751d42008-11-17 22:58:34 +00001636 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001637
John McCall25849ca2011-02-15 07:12:36 +00001638 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001639 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001640 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001641}
1642
Richard Smith938f40b2011-06-11 17:19:42 +00001643/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001644/// in-class initializer for a non-static C++ class member, and after
1645/// instantiating an in-class initializer in a class template. Such actions
1646/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001647void
1648Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1649 Expr *InitExpr) {
1650 FieldDecl *FD = cast<FieldDecl>(D);
1651
1652 if (!InitExpr) {
1653 FD->setInvalidDecl();
1654 FD->removeInClassInitializer();
1655 return;
1656 }
1657
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00001658 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1659 FD->setInvalidDecl();
1660 FD->removeInClassInitializer();
1661 return;
1662 }
1663
Richard Smith938f40b2011-06-11 17:19:42 +00001664 ExprResult Init = InitExpr;
1665 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1666 // FIXME: if there is no EqualLoc, this is list-initialization.
1667 Init = PerformCopyInitialization(
1668 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1669 if (Init.isInvalid()) {
1670 FD->setInvalidDecl();
1671 return;
1672 }
1673
1674 CheckImplicitConversions(Init.get(), EqualLoc);
1675 }
1676
1677 // C++0x [class.base.init]p7:
1678 // The initialization of each base and member constitutes a
1679 // full-expression.
1680 Init = MaybeCreateExprWithCleanups(Init);
1681 if (Init.isInvalid()) {
1682 FD->setInvalidDecl();
1683 return;
1684 }
1685
1686 InitExpr = Init.release();
1687
1688 FD->setInClassInitializer(InitExpr);
1689}
1690
Douglas Gregor15e77a22009-12-31 09:10:24 +00001691/// \brief Find the direct and/or virtual base specifiers that
1692/// correspond to the given base type, for use in base initialization
1693/// within a constructor.
1694static bool FindBaseInitializer(Sema &SemaRef,
1695 CXXRecordDecl *ClassDecl,
1696 QualType BaseType,
1697 const CXXBaseSpecifier *&DirectBaseSpec,
1698 const CXXBaseSpecifier *&VirtualBaseSpec) {
1699 // First, check for a direct base class.
1700 DirectBaseSpec = 0;
1701 for (CXXRecordDecl::base_class_const_iterator Base
1702 = ClassDecl->bases_begin();
1703 Base != ClassDecl->bases_end(); ++Base) {
1704 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1705 // We found a direct base of this type. That's what we're
1706 // initializing.
1707 DirectBaseSpec = &*Base;
1708 break;
1709 }
1710 }
1711
1712 // Check for a virtual base class.
1713 // FIXME: We might be able to short-circuit this if we know in advance that
1714 // there are no virtual bases.
1715 VirtualBaseSpec = 0;
1716 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1717 // We haven't found a base yet; search the class hierarchy for a
1718 // virtual base class.
1719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1720 /*DetectVirtual=*/false);
1721 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1722 BaseType, Paths)) {
1723 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724 Path != Paths.end(); ++Path) {
1725 if (Path->back().Base->isVirtual()) {
1726 VirtualBaseSpec = Path->back().Base;
1727 break;
1728 }
1729 }
1730 }
1731 }
1732
1733 return DirectBaseSpec || VirtualBaseSpec;
1734}
1735
Sebastian Redla74948d2011-09-24 17:48:25 +00001736/// \brief Handle a C++ member initializer using braced-init-list syntax.
1737MemInitResult
1738Sema::ActOnMemInitializer(Decl *ConstructorD,
1739 Scope *S,
1740 CXXScopeSpec &SS,
1741 IdentifierInfo *MemberOrBase,
1742 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001743 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001744 SourceLocation IdLoc,
1745 Expr *InitList,
1746 SourceLocation EllipsisLoc) {
1747 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00001748 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00001749 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001750}
1751
1752/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001753MemInitResult
John McCall48871652010-08-21 09:40:31 +00001754Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001755 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001756 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001757 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001758 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001759 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001760 SourceLocation IdLoc,
1761 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001762 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001763 SourceLocation RParenLoc,
1764 SourceLocation EllipsisLoc) {
Sebastian Redla9351792012-02-11 23:51:47 +00001765 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1766 RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001767 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00001768 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001769}
1770
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001771namespace {
1772
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00001773// Callback to only accept typo corrections that can be a valid C++ member
1774// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001775class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1776 public:
1777 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1778 : ClassDecl(ClassDecl) {}
1779
1780 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1781 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1782 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1783 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1784 else
1785 return isa<TypeDecl>(ND);
1786 }
1787 return false;
1788 }
1789
1790 private:
1791 CXXRecordDecl *ClassDecl;
1792};
1793
1794}
1795
Sebastian Redla74948d2011-09-24 17:48:25 +00001796/// \brief Handle a C++ member initializer.
1797MemInitResult
1798Sema::BuildMemInitializer(Decl *ConstructorD,
1799 Scope *S,
1800 CXXScopeSpec &SS,
1801 IdentifierInfo *MemberOrBase,
1802 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001803 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001804 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00001805 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00001806 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001807 if (!ConstructorD)
1808 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001810 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001811
1812 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001813 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001814 if (!Constructor) {
1815 // The user wrote a constructor initializer on a function that is
1816 // not a C++ constructor. Ignore the error for now, because we may
1817 // have more member initializers coming; we'll diagnose it just
1818 // once in ActOnMemInitializers.
1819 return true;
1820 }
1821
1822 CXXRecordDecl *ClassDecl = Constructor->getParent();
1823
1824 // C++ [class.base.init]p2:
1825 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001826 // constructor's class and, if not found in that scope, are looked
1827 // up in the scope containing the constructor's definition.
1828 // [Note: if the constructor's class contains a member with the
1829 // same name as a direct or virtual base class of the class, a
1830 // mem-initializer-id naming the member or base class and composed
1831 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001832 // mem-initializer-id for the hidden base class may be specified
1833 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001834 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001835 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00001836 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001837 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001838 if (Result.first != Result.second) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00001839 ValueDecl *Member;
1840 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1841 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00001842 if (EllipsisLoc.isValid())
1843 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00001844 << MemberOrBase
1845 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00001846
Sebastian Redla9351792012-02-11 23:51:47 +00001847 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001848 }
Francois Pichetd583da02010-12-04 09:14:42 +00001849 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001850 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001851 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001852 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001853 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001854
1855 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001856 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00001857 } else if (DS.getTypeSpecType() == TST_decltype) {
1858 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00001859 } else {
1860 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1861 LookupParsedName(R, S, &SS);
1862
1863 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1864 if (!TyD) {
1865 if (R.isAmbiguous()) return true;
1866
John McCallda6841b2010-04-09 19:01:14 +00001867 // We don't want access-control diagnostics here.
1868 R.suppressDiagnostics();
1869
Douglas Gregora3b624a2010-01-19 06:46:48 +00001870 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1871 bool NotUnknownSpecialization = false;
1872 DeclContext *DC = computeDeclContext(SS, false);
1873 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1874 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1875
1876 if (!NotUnknownSpecialization) {
1877 // When the scope specifier can refer to a member of an unknown
1878 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001879 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1880 SS.getWithLocInContext(Context),
1881 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001882 if (BaseType.isNull())
1883 return true;
1884
Douglas Gregora3b624a2010-01-19 06:46:48 +00001885 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001886 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001887 }
1888 }
1889
Douglas Gregor15e77a22009-12-31 09:10:24 +00001890 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001891 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001892 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001893 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001894 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001895 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001896 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1897 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1898 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001899 // We have found a non-static data member with a similar
1900 // name to what was typed; complain and initialize that
1901 // member.
1902 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1903 << MemberOrBase << true << CorrectedQuotedStr
1904 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1905 Diag(Member->getLocation(), diag::note_previous_decl)
1906 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001907
Sebastian Redla9351792012-02-11 23:51:47 +00001908 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001909 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001910 const CXXBaseSpecifier *DirectBaseSpec;
1911 const CXXBaseSpecifier *VirtualBaseSpec;
1912 if (FindBaseInitializer(*this, ClassDecl,
1913 Context.getTypeDeclType(Type),
1914 DirectBaseSpec, VirtualBaseSpec)) {
1915 // We have found a direct or virtual base class with a
1916 // similar name to what was typed; complain and initialize
1917 // that base class.
1918 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001919 << MemberOrBase << false << CorrectedQuotedStr
1920 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001921
1922 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1923 : VirtualBaseSpec;
1924 Diag(BaseSpec->getSourceRange().getBegin(),
1925 diag::note_base_class_specified_here)
1926 << BaseSpec->getType()
1927 << BaseSpec->getSourceRange();
1928
Douglas Gregor15e77a22009-12-31 09:10:24 +00001929 TyD = Type;
1930 }
1931 }
1932 }
1933
Douglas Gregora3b624a2010-01-19 06:46:48 +00001934 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001935 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00001936 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001937 return true;
1938 }
John McCallb5a0d312009-12-21 10:41:20 +00001939 }
1940
Douglas Gregora3b624a2010-01-19 06:46:48 +00001941 if (BaseType.isNull()) {
1942 BaseType = Context.getTypeDeclType(TyD);
1943 if (SS.isSet()) {
1944 NestedNameSpecifier *Qualifier =
1945 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001946
Douglas Gregora3b624a2010-01-19 06:46:48 +00001947 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001948 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001949 }
John McCallb5a0d312009-12-21 10:41:20 +00001950 }
1951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCallbcd03502009-12-07 02:54:59 +00001953 if (!TInfo)
1954 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001955
Sebastian Redla9351792012-02-11 23:51:47 +00001956 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001957}
1958
Chandler Carruth599deef2011-09-03 01:14:15 +00001959/// Checks a member initializer expression for cases where reference (or
1960/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001961static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1962 Expr *Init,
1963 SourceLocation IdLoc) {
1964 QualType MemberTy = Member->getType();
1965
1966 // We only handle pointers and references currently.
1967 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1968 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1969 return;
1970
1971 const bool IsPointer = MemberTy->isPointerType();
1972 if (IsPointer) {
1973 if (const UnaryOperator *Op
1974 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1975 // The only case we're worried about with pointers requires taking the
1976 // address.
1977 if (Op->getOpcode() != UO_AddrOf)
1978 return;
1979
1980 Init = Op->getSubExpr();
1981 } else {
1982 // We only handle address-of expression initializers for pointers.
1983 return;
1984 }
1985 }
1986
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001987 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1988 // Taking the address of a temporary will be diagnosed as a hard error.
1989 if (IsPointer)
1990 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001991
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001992 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1993 << Member << Init->getSourceRange();
1994 } else if (const DeclRefExpr *DRE
1995 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1996 // We only warn when referring to a non-reference parameter declaration.
1997 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1998 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001999 return;
2000
2001 S.Diag(Init->getExprLoc(),
2002 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2003 : diag::warn_bind_ref_member_to_parameter)
2004 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002005 } else {
2006 // Other initializers are fine.
2007 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002008 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002009
2010 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2011 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002012}
2013
John McCalle22a04a2009-11-04 23:02:40 +00002014/// Checks an initializer expression for use of uninitialized fields, such as
2015/// containing the field that is being initialized. Returns true if there is an
2016/// uninitialized field was used an updates the SourceLocation parameter; false
2017/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002018static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00002019 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002020 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00002021 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2022
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002023 if (isa<CallExpr>(S)) {
2024 // Do not descend into function calls or constructors, as the use
2025 // of an uninitialized field may be valid. One would have to inspect
2026 // the contents of the function/ctor to determine if it is safe or not.
2027 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2028 // may be safe, depending on what the function/ctor does.
2029 return false;
2030 }
2031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2032 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002033
2034 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2035 // The member expression points to a static data member.
2036 assert(VD->isStaticDataMember() &&
2037 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00002038 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002039 return false;
2040 }
2041
2042 if (isa<EnumConstantDecl>(RhsField)) {
2043 // The member expression points to an enum.
2044 return false;
2045 }
2046
John McCalle22a04a2009-11-04 23:02:40 +00002047 if (RhsField == LhsField) {
2048 // Initializing a field with itself. Throw a warning.
2049 // But wait; there are exceptions!
2050 // Exception #1: The field may not belong to this record.
2051 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002052 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002053 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2054 // Even though the field matches, it does not belong to this record.
2055 return false;
2056 }
2057 // None of the exceptions triggered; return true to indicate an
2058 // uninitialized field was used.
2059 *L = ME->getMemberLoc();
2060 return true;
2061 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002062 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002063 // sizeof/alignof doesn't reference contents, do not warn.
2064 return false;
2065 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2066 // address-of doesn't reference contents (the pointer may be dereferenced
2067 // in the same expression but it would be rare; and weird).
2068 if (UOE->getOpcode() == UO_AddrOf)
2069 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002070 }
John McCall8322c3a2011-02-13 04:07:26 +00002071 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002072 if (!*it) {
2073 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002074 continue;
2075 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002076 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2077 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002078 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002079 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002080}
2081
John McCallfaf5fb42010-08-26 23:41:50 +00002082MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002083Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002084 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002085 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2086 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2087 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002088 "Member must be a FieldDecl or IndirectFieldDecl");
2089
Sebastian Redla9351792012-02-11 23:51:47 +00002090 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002091 return true;
2092
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002093 if (Member->isInvalidDecl())
2094 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002095
John McCalle22a04a2009-11-04 23:02:40 +00002096 // Diagnose value-uses of fields to initialize themselves, e.g.
2097 // foo(foo)
2098 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002099 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla9351792012-02-11 23:51:47 +00002100 Expr **Args;
2101 unsigned NumArgs;
2102 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2103 Args = ParenList->getExprs();
2104 NumArgs = ParenList->getNumExprs();
2105 } else {
2106 InitListExpr *InitList = cast<InitListExpr>(Init);
2107 Args = InitList->getInits();
2108 NumArgs = InitList->getNumInits();
2109 }
2110 for (unsigned i = 0; i < NumArgs; ++i) {
John McCalle22a04a2009-11-04 23:02:40 +00002111 SourceLocation L;
Sebastian Redla9351792012-02-11 23:51:47 +00002112 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002113 // FIXME: Return true in the case when other fields are used before being
2114 // uninitialized. For example, let this field be the i'th field. When
2115 // initializing the i'th field, throw a warning if any of the >= i'th
2116 // fields are used, as they are not yet initialized.
2117 // Right now we are only handling the case where the i'th field uses
2118 // itself in its initializer.
2119 Diag(L, diag::warn_field_is_uninit);
2120 }
2121 }
2122
Sebastian Redla9351792012-02-11 23:51:47 +00002123 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002124
Sebastian Redla9351792012-02-11 23:51:47 +00002125 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002126 // Can't check initialization for a member of dependent type or when
2127 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002128 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002129 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002130 bool InitList = false;
2131 if (isa<InitListExpr>(Init)) {
2132 InitList = true;
2133 Args = &Init;
2134 NumArgs = 1;
2135 }
2136
Chandler Carruthd44c3102010-12-06 09:23:57 +00002137 // Initialize the member.
2138 InitializedEntity MemberEntity =
2139 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2140 : InitializedEntity::InitializeMember(IndirectMember, 0);
2141 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002142 InitList ? InitializationKind::CreateDirectList(IdLoc)
2143 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2144 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002145
Sebastian Redla9351792012-02-11 23:51:47 +00002146 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2147 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2148 MultiExprArg(*this, Args, NumArgs),
2149 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002150 if (MemberInit.isInvalid())
2151 return true;
2152
Sebastian Redla9351792012-02-11 23:51:47 +00002153 CheckImplicitConversions(MemberInit.get(),
2154 InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002155
2156 // C++0x [class.base.init]p7:
2157 // The initialization of each base and member constitutes a
2158 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002159 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002160 if (MemberInit.isInvalid())
2161 return true;
2162
2163 // If we are in a dependent context, template instantiation will
2164 // perform this type-checking again. Just save the arguments that we
Sebastian Redla9351792012-02-11 23:51:47 +00002165 // received.
Chandler Carruthd44c3102010-12-06 09:23:57 +00002166 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2167 // of the information that we have about the member
2168 // initializer. However, deconstructing the ASTs is a dicey process,
2169 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002170 if (CurContext->isDependentContext()) {
Sebastian Redla9351792012-02-11 23:51:47 +00002171 // The existing Init will do fine.
Chandler Carruth599deef2011-09-03 01:14:15 +00002172 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002173 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002174 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2175 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002176 }
2177
Chandler Carruthd44c3102010-12-06 09:23:57 +00002178 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002179 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2180 InitRange.getBegin(), Init,
2181 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002182 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002183 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2184 InitRange.getBegin(), Init,
2185 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002186 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002187}
2188
John McCallfaf5fb42010-08-26 23:41:50 +00002189MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002190Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002191 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002192 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002193 if (!LangOpts.CPlusPlus0x)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002194 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002195 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002196 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002197
Sebastian Redl0501c632012-02-12 16:37:36 +00002198 bool InitList = true;
2199 Expr **Args = &Init;
2200 unsigned NumArgs = 1;
2201 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2202 InitList = false;
2203 Args = ParenList->getExprs();
2204 NumArgs = ParenList->getNumExprs();
2205 }
2206
Sebastian Redla9351792012-02-11 23:51:47 +00002207 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002208 // Initialize the object.
2209 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2210 QualType(ClassDecl->getTypeForDecl(), 0));
2211 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002212 InitList ? InitializationKind::CreateDirectList(NameLoc)
2213 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2214 InitRange.getEnd());
Sebastian Redla9351792012-02-11 23:51:47 +00002215 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2216 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2217 MultiExprArg(*this, Args,NumArgs),
2218 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002219 if (DelegationInit.isInvalid())
2220 return true;
2221
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002222 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2223 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002224
Sebastian Redla9351792012-02-11 23:51:47 +00002225 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002226
2227 // C++0x [class.base.init]p7:
2228 // The initialization of each base and member constitutes a
2229 // full-expression.
2230 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2231 if (DelegationInit.isInvalid())
2232 return true;
2233
Sebastian Redla9351792012-02-11 23:51:47 +00002234 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002235 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002236 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002237}
2238
2239MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002240Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002241 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002242 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002243 SourceLocation BaseLoc
2244 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002245
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002246 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2247 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2248 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2249
2250 // C++ [class.base.init]p2:
2251 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002252 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002253 // of that class, the mem-initializer is ill-formed. A
2254 // mem-initializer-list can initialize a base class using any
2255 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002256 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002257
Sebastian Redla9351792012-02-11 23:51:47 +00002258 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002259 if (EllipsisLoc.isValid()) {
2260 // This is a pack expansion.
2261 if (!BaseType->containsUnexpandedParameterPack()) {
2262 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002263 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002264
Douglas Gregor44e7df62011-01-04 00:32:56 +00002265 EllipsisLoc = SourceLocation();
2266 }
2267 } else {
2268 // Check for any unexpanded parameter packs.
2269 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2270 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002271
Sebastian Redla9351792012-02-11 23:51:47 +00002272 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002273 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002274 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002275
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002276 // Check for direct and virtual base classes.
2277 const CXXBaseSpecifier *DirectBaseSpec = 0;
2278 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2279 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002280 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2281 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002282 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002283
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002284 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2285 VirtualBaseSpec);
2286
2287 // C++ [base.class.init]p2:
2288 // Unless the mem-initializer-id names a nonstatic data member of the
2289 // constructor's class or a direct or virtual base of that class, the
2290 // mem-initializer is ill-formed.
2291 if (!DirectBaseSpec && !VirtualBaseSpec) {
2292 // If the class has any dependent bases, then it's possible that
2293 // one of those types will resolve to the same type as
2294 // BaseType. Therefore, just treat this as a dependent base
2295 // class initialization. FIXME: Should we try to check the
2296 // initialization anyway? It seems odd.
2297 if (ClassDecl->hasAnyDependentBases())
2298 Dependent = true;
2299 else
2300 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2301 << BaseType << Context.getTypeDeclType(ClassDecl)
2302 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2303 }
2304 }
2305
2306 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002307 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002308
Sebastian Redla74948d2011-09-24 17:48:25 +00002309 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2310 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002311 InitRange.getBegin(), Init,
2312 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002313 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002314
2315 // C++ [base.class.init]p2:
2316 // If a mem-initializer-id is ambiguous because it designates both
2317 // a direct non-virtual base class and an inherited virtual base
2318 // class, the mem-initializer is ill-formed.
2319 if (DirectBaseSpec && VirtualBaseSpec)
2320 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002321 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002322
Sebastian Redla9351792012-02-11 23:51:47 +00002323 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002324 if (!BaseSpec)
2325 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2326
2327 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002328 bool InitList = true;
Sebastian Redla9351792012-02-11 23:51:47 +00002329 Expr **Args = &Init;
2330 unsigned NumArgs = 1;
2331 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002332 InitList = false;
Sebastian Redla9351792012-02-11 23:51:47 +00002333 Args = ParenList->getExprs();
2334 NumArgs = ParenList->getNumExprs();
2335 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002336
2337 InitializedEntity BaseEntity =
2338 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2339 InitializationKind Kind =
2340 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2341 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2342 InitRange.getEnd());
Sebastian Redla9351792012-02-11 23:51:47 +00002343 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2344 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2345 MultiExprArg(*this, Args, NumArgs),
2346 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002347 if (BaseInit.isInvalid())
2348 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002349
Sebastian Redla9351792012-02-11 23:51:47 +00002350 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redla74948d2011-09-24 17:48:25 +00002351
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002352 // C++0x [class.base.init]p7:
2353 // The initialization of each base and member constitutes a
2354 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002355 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002356 if (BaseInit.isInvalid())
2357 return true;
2358
2359 // If we are in a dependent context, template instantiation will
2360 // perform this type-checking again. Just save the arguments that we
2361 // received in a ParenListExpr.
2362 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2363 // of the information that we have about the base
2364 // initializer. However, deconstructing the ASTs is a dicey process,
2365 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002366 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002367 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002368
Alexis Hunt1d792652011-01-08 20:30:50 +00002369 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002370 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002371 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002372 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002373 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002374}
2375
Sebastian Redl22653ba2011-08-30 19:58:05 +00002376// Create a static_cast\<T&&>(expr).
2377static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2378 QualType ExprType = E->getType();
2379 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2380 SourceLocation ExprLoc = E->getLocStart();
2381 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2382 TargetType, ExprLoc);
2383
2384 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2385 SourceRange(ExprLoc, ExprLoc),
2386 E->getSourceRange()).take();
2387}
2388
Anders Carlsson1b00e242010-04-23 03:10:23 +00002389/// ImplicitInitializerKind - How an implicit base or member initializer should
2390/// initialize its base or member.
2391enum ImplicitInitializerKind {
2392 IIK_Default,
2393 IIK_Copy,
2394 IIK_Move
2395};
2396
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002397static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002398BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002399 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002400 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002401 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002402 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002403 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002404 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2405 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002406
John McCalldadc5752010-08-24 06:29:42 +00002407 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002408
2409 switch (ImplicitInitKind) {
2410 case IIK_Default: {
2411 InitializationKind InitKind
2412 = InitializationKind::CreateDefault(Constructor->getLocation());
2413 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002415 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002416 break;
2417 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002418
Sebastian Redl22653ba2011-08-30 19:58:05 +00002419 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002420 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002421 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002422 ParmVarDecl *Param = Constructor->getParamDecl(0);
2423 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002424
Anders Carlsson1b00e242010-04-23 03:10:23 +00002425 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002426 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2427 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002428 Constructor->getLocation(), ParamType,
2429 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002430
Eli Friedmanfa0df832012-02-02 03:46:19 +00002431 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2432
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002433 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002434 QualType ArgTy =
2435 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2436 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002437
Sebastian Redl22653ba2011-08-30 19:58:05 +00002438 if (Moving) {
2439 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2440 }
2441
John McCallcf142162010-08-07 06:22:56 +00002442 CXXCastPath BasePath;
2443 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002444 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2445 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002446 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002447 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002448
Anders Carlsson1b00e242010-04-23 03:10:23 +00002449 InitializationKind InitKind
2450 = InitializationKind::CreateDirect(Constructor->getLocation(),
2451 SourceLocation(), SourceLocation());
2452 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2453 &CopyCtorArg, 1);
2454 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002455 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002456 break;
2457 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002458 }
John McCallb268a282010-08-23 23:25:46 +00002459
Douglas Gregora40433a2010-12-07 00:41:46 +00002460 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002461 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002462 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002463
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002464 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002465 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002466 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2467 SourceLocation()),
2468 BaseSpec->isVirtual(),
2469 SourceLocation(),
2470 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002471 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002472 SourceLocation());
2473
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002474 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002475}
2476
Sebastian Redl22653ba2011-08-30 19:58:05 +00002477static bool RefersToRValueRef(Expr *MemRef) {
2478 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2479 return Referenced->getType()->isRValueReferenceType();
2480}
2481
Anders Carlsson3c1db572010-04-23 02:15:47 +00002482static bool
2483BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002484 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002485 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002486 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002487 if (Field->isInvalidDecl())
2488 return true;
2489
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002490 SourceLocation Loc = Constructor->getLocation();
2491
Sebastian Redl22653ba2011-08-30 19:58:05 +00002492 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2493 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002494 ParmVarDecl *Param = Constructor->getParamDecl(0);
2495 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002496
2497 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002498 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2499 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002500
Anders Carlsson423f5d82010-04-23 16:04:08 +00002501 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002502 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2503 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002504 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002505
Eli Friedmanfa0df832012-02-02 03:46:19 +00002506 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2507
Sebastian Redl22653ba2011-08-30 19:58:05 +00002508 if (Moving) {
2509 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2510 }
2511
Douglas Gregor94f9a482010-05-05 05:51:00 +00002512 // Build a reference to this field within the parameter.
2513 CXXScopeSpec SS;
2514 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2515 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002516 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2517 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002518 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002519 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002520 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002521 ParamType, Loc,
2522 /*IsArrow=*/false,
2523 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002524 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002525 /*FirstQualifierInScope=*/0,
2526 MemberLookup,
2527 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002528 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002529 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002530
2531 // C++11 [class.copy]p15:
2532 // - if a member m has rvalue reference type T&&, it is direct-initialized
2533 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002534 if (RefersToRValueRef(CtorArg.get())) {
2535 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002536 }
2537
Douglas Gregor94f9a482010-05-05 05:51:00 +00002538 // When the field we are copying is an array, create index variables for
2539 // each dimension of the array. We use these index variables to subscript
2540 // the source array, and other clients (e.g., CodeGen) will perform the
2541 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002542 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002543 QualType BaseType = Field->getType();
2544 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002545 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002546 while (const ConstantArrayType *Array
2547 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002548 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002549 // Create the iteration variable for this array index.
2550 IdentifierInfo *IterationVarName = 0;
2551 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002552 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002553 llvm::raw_svector_ostream OS(Str);
2554 OS << "__i" << IndexVariables.size();
2555 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2556 }
2557 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002558 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002559 IterationVarName, SizeType,
2560 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002561 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002562 IndexVariables.push_back(IterationVar);
2563
2564 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002565 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00002566 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002567 assert(!IterationVarRef.isInvalid() &&
2568 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00002569 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2570 assert(!IterationVarRef.isInvalid() &&
2571 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002572
Douglas Gregor94f9a482010-05-05 05:51:00 +00002573 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002574 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002575 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002576 Loc);
2577 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002578 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002579
Douglas Gregor94f9a482010-05-05 05:51:00 +00002580 BaseType = Array->getElementType();
2581 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002582
2583 // The array subscript expression is an lvalue, which is wrong for moving.
2584 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002585 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002586
Douglas Gregor94f9a482010-05-05 05:51:00 +00002587 // Construct the entity that we will be initializing. For an array, this
2588 // will be first element in the array, which may require several levels
2589 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002590 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002591 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002592 if (Indirect)
2593 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2594 else
2595 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002596 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2597 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2598 0,
2599 Entities.back()));
2600
2601 // Direct-initialize to use the copy constructor.
2602 InitializationKind InitKind =
2603 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2604
Sebastian Redle9c4e842011-09-04 18:14:28 +00002605 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002606 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002607 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002608
John McCalldadc5752010-08-24 06:29:42 +00002609 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002610 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002611 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002612 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002613 if (MemberInit.isInvalid())
2614 return true;
2615
Douglas Gregor493627b2011-08-10 15:22:55 +00002616 if (Indirect) {
2617 assert(IndexVariables.size() == 0 &&
2618 "Indirect field improperly initialized");
2619 CXXMemberInit
2620 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2621 Loc, Loc,
2622 MemberInit.takeAs<Expr>(),
2623 Loc);
2624 } else
2625 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2626 Loc, MemberInit.takeAs<Expr>(),
2627 Loc,
2628 IndexVariables.data(),
2629 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002630 return false;
2631 }
2632
Anders Carlsson423f5d82010-04-23 16:04:08 +00002633 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2634
Anders Carlsson3c1db572010-04-23 02:15:47 +00002635 QualType FieldBaseElementType =
2636 SemaRef.Context.getBaseElementType(Field->getType());
2637
Anders Carlsson3c1db572010-04-23 02:15:47 +00002638 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002639 InitializedEntity InitEntity
2640 = Indirect? InitializedEntity::InitializeMember(Indirect)
2641 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002642 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002643 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002644
2645 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002646 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002647 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002648
Douglas Gregora40433a2010-12-07 00:41:46 +00002649 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002650 if (MemberInit.isInvalid())
2651 return true;
2652
Douglas Gregor493627b2011-08-10 15:22:55 +00002653 if (Indirect)
2654 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2655 Indirect, Loc,
2656 Loc,
2657 MemberInit.get(),
2658 Loc);
2659 else
2660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2661 Field, Loc, Loc,
2662 MemberInit.get(),
2663 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002664 return false;
2665 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002666
Alexis Hunt8b455182011-05-17 00:19:05 +00002667 if (!Field->getParent()->isUnion()) {
2668 if (FieldBaseElementType->isReferenceType()) {
2669 SemaRef.Diag(Constructor->getLocation(),
2670 diag::err_uninitialized_member_in_ctor)
2671 << (int)Constructor->isImplicit()
2672 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2673 << 0 << Field->getDeclName();
2674 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2675 return true;
2676 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002677
Alexis Hunt8b455182011-05-17 00:19:05 +00002678 if (FieldBaseElementType.isConstQualified()) {
2679 SemaRef.Diag(Constructor->getLocation(),
2680 diag::err_uninitialized_member_in_ctor)
2681 << (int)Constructor->isImplicit()
2682 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2683 << 1 << Field->getDeclName();
2684 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2685 return true;
2686 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002687 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002688
John McCall31168b02011-06-15 23:02:42 +00002689 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2690 FieldBaseElementType->isObjCRetainableType() &&
2691 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2692 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2693 // Instant objects:
2694 // Default-initialize Objective-C pointers to NULL.
2695 CXXMemberInit
2696 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2697 Loc, Loc,
2698 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2699 Loc);
2700 return false;
2701 }
2702
Anders Carlsson3c1db572010-04-23 02:15:47 +00002703 // Nothing to initialize.
2704 CXXMemberInit = 0;
2705 return false;
2706}
John McCallbc83b3f2010-05-20 23:23:51 +00002707
2708namespace {
2709struct BaseAndFieldInfo {
2710 Sema &S;
2711 CXXConstructorDecl *Ctor;
2712 bool AnyErrorsInInits;
2713 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002714 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002715 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002716
2717 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2718 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002719 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2720 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002721 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002722 else if (Generated && Ctor->isMoveConstructor())
2723 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002724 else
2725 IIK = IIK_Default;
2726 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00002727
2728 bool isImplicitCopyOrMove() const {
2729 switch (IIK) {
2730 case IIK_Copy:
2731 case IIK_Move:
2732 return true;
2733
2734 case IIK_Default:
2735 return false;
2736 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002737
2738 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00002739 }
John McCallbc83b3f2010-05-20 23:23:51 +00002740};
2741}
2742
Richard Smithc94ec842011-09-19 13:34:43 +00002743/// \brief Determine whether the given indirect field declaration is somewhere
2744/// within an anonymous union.
2745static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2746 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2747 CEnd = F->chain_end();
2748 C != CEnd; ++C)
2749 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2750 if (Record->isUnion())
2751 return true;
2752
2753 return false;
2754}
2755
Douglas Gregor10f939c2011-11-02 23:04:16 +00002756/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2757/// array type.
2758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2759 if (T->isIncompleteArrayType())
2760 return true;
2761
2762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2763 if (!ArrayT->getSize())
2764 return true;
2765
2766 T = ArrayT->getElementType();
2767 }
2768
2769 return false;
2770}
2771
Richard Smith938f40b2011-06-11 17:19:42 +00002772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002773 FieldDecl *Field,
2774 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002775
Chandler Carruth139e9622010-06-30 02:59:29 +00002776 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002777 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002778 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002779 return false;
2780 }
2781
Richard Smith938f40b2011-06-11 17:19:42 +00002782 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2783 // has a brace-or-equal-initializer, the entity is initialized as specified
2784 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00002785 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002786 CXXCtorInitializer *Init;
2787 if (Indirect)
2788 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2789 SourceLocation(),
2790 SourceLocation(), 0,
2791 SourceLocation());
2792 else
2793 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2794 SourceLocation(),
2795 SourceLocation(), 0,
2796 SourceLocation());
2797 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002798 return false;
2799 }
2800
Richard Smith12d5ed82011-09-18 11:14:50 +00002801 // Don't build an implicit initializer for union members if none was
2802 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002803 if (Field->getParent()->isUnion() ||
2804 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002805 return false;
2806
Douglas Gregor10f939c2011-11-02 23:04:16 +00002807 // Don't initialize incomplete or zero-length arrays.
2808 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2809 return false;
2810
John McCallbc83b3f2010-05-20 23:23:51 +00002811 // Don't try to build an implicit initializer if there were semantic
2812 // errors in any of the initializers (and therefore we might be
2813 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002814 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002815 return false;
2816
Alexis Hunt1d792652011-01-08 20:30:50 +00002817 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002818 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2819 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002820 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002821
Francois Pichetd583da02010-12-04 09:14:42 +00002822 if (Init)
2823 Info.AllToInit.push_back(Init);
2824
John McCallbc83b3f2010-05-20 23:23:51 +00002825 return false;
2826}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002827
2828bool
2829Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2830 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002831 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002832 Constructor->setNumCtorInitializers(1);
2833 CXXCtorInitializer **initializer =
2834 new (Context) CXXCtorInitializer*[1];
2835 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2836 Constructor->setCtorInitializers(initializer);
2837
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002838 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002839 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002840 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2841 }
2842
Alexis Hunte2622992011-05-05 00:05:47 +00002843 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002844
Alexis Hunt61bc1732011-05-01 07:04:31 +00002845 return false;
2846}
Douglas Gregor493627b2011-08-10 15:22:55 +00002847
John McCall1b1a1db2011-06-17 00:18:42 +00002848bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2849 CXXCtorInitializer **Initializers,
2850 unsigned NumInitializers,
2851 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002852 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002853 // Just store the initializers as written, they will be checked during
2854 // instantiation.
2855 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002856 Constructor->setNumCtorInitializers(NumInitializers);
2857 CXXCtorInitializer **baseOrMemberInitializers =
2858 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002859 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002860 NumInitializers * sizeof(CXXCtorInitializer*));
2861 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002862 }
2863
2864 return false;
2865 }
2866
John McCallbc83b3f2010-05-20 23:23:51 +00002867 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002868
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002869 // We need to build the initializer AST according to order of construction
2870 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002871 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002872 if (!ClassDecl)
2873 return true;
2874
Eli Friedman9cf6b592009-11-09 19:20:36 +00002875 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002876
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002877 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002878 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002879
2880 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002881 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002882 else
Francois Pichetd583da02010-12-04 09:14:42 +00002883 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002884 }
2885
Anders Carlsson43c64af2010-04-21 19:52:01 +00002886 // Keep track of the direct virtual bases.
2887 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2888 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2889 E = ClassDecl->bases_end(); I != E; ++I) {
2890 if (I->isVirtual())
2891 DirectVBases.insert(I);
2892 }
2893
Anders Carlssondb0a9652010-04-02 06:26:44 +00002894 // Push virtual bases before others.
2895 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2896 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2897
Alexis Hunt1d792652011-01-08 20:30:50 +00002898 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002899 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2900 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002901 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002902 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002903 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002904 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002905 VBase, IsInheritedVirtualBase,
2906 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002907 HadError = true;
2908 continue;
2909 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002910
John McCallbc83b3f2010-05-20 23:23:51 +00002911 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002912 }
2913 }
Mike Stump11289f42009-09-09 15:08:12 +00002914
John McCallbc83b3f2010-05-20 23:23:51 +00002915 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002916 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2917 E = ClassDecl->bases_end(); Base != E; ++Base) {
2918 // Virtuals are in the virtual base list and already constructed.
2919 if (Base->isVirtual())
2920 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002921
Alexis Hunt1d792652011-01-08 20:30:50 +00002922 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002923 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2924 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002925 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002926 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002927 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002928 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002929 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002930 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002931 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002932 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002933
John McCallbc83b3f2010-05-20 23:23:51 +00002934 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002935 }
2936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
John McCallbc83b3f2010-05-20 23:23:51 +00002938 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002939 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2940 MemEnd = ClassDecl->decls_end();
2941 Mem != MemEnd; ++Mem) {
2942 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00002943 // C++ [class.bit]p2:
2944 // A declaration for a bit-field that omits the identifier declares an
2945 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2946 // initialized.
2947 if (F->isUnnamedBitfield())
2948 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002949
Sebastian Redl22653ba2011-08-30 19:58:05 +00002950 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002951 // handle anonymous struct/union fields based on their individual
2952 // indirect fields.
2953 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2954 continue;
2955
2956 if (CollectFieldInitializer(*this, Info, F))
2957 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002958 continue;
2959 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002960
2961 // Beyond this point, we only consider default initialization.
2962 if (Info.IIK != IIK_Default)
2963 continue;
2964
2965 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2966 if (F->getType()->isIncompleteArrayType()) {
2967 assert(ClassDecl->hasFlexibleArrayMember() &&
2968 "Incomplete array type is not valid");
2969 continue;
2970 }
2971
Douglas Gregor493627b2011-08-10 15:22:55 +00002972 // Initialize each field of an anonymous struct individually.
2973 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2974 HadError = true;
2975
2976 continue;
2977 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979
John McCallbc83b3f2010-05-20 23:23:51 +00002980 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002981 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002982 Constructor->setNumCtorInitializers(NumInitializers);
2983 CXXCtorInitializer **baseOrMemberInitializers =
2984 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002985 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002986 NumInitializers * sizeof(CXXCtorInitializer*));
2987 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002988
John McCalla6309952010-03-16 21:39:52 +00002989 // Constructors implicitly reference the base and member
2990 // destructors.
2991 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2992 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002993 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002994
2995 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002996}
2997
Eli Friedman952c15d2009-07-21 19:28:10 +00002998static void *GetKeyForTopLevelField(FieldDecl *Field) {
2999 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003000 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00003001 if (RT->getDecl()->isAnonymousStructOrUnion())
3002 return static_cast<void *>(RT->getDecl());
3003 }
3004 return static_cast<void *>(Field);
3005}
3006
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003007static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00003008 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003009}
3010
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003011static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00003012 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003013 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003014 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003015
Eli Friedman952c15d2009-07-21 19:28:10 +00003016 // For fields injected into the class via declaration of an anonymous union,
3017 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00003018 FieldDecl *Field = Member->getAnyMember();
3019
John McCall23eebd92010-04-10 09:28:51 +00003020 // If the field is a member of an anonymous struct or union, our key
3021 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00003022 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003023 if (RD->isAnonymousStructOrUnion()) {
3024 while (true) {
3025 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3026 if (Parent->isAnonymousStructOrUnion())
3027 RD = Parent;
3028 else
3029 break;
3030 }
3031
Anders Carlsson83ac3122010-03-30 16:19:37 +00003032 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00003033 }
Mike Stump11289f42009-09-09 15:08:12 +00003034
Anders Carlssona942dcd2010-03-30 15:39:27 +00003035 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003036}
3037
Anders Carlssone857b292010-04-02 03:37:03 +00003038static void
3039DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003040 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00003041 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00003042 unsigned NumInits) {
3043 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003044 return;
Mike Stump11289f42009-09-09 15:08:12 +00003045
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003046 // Don't check initializers order unless the warning is enabled at the
3047 // location of at least one initializer.
3048 bool ShouldCheckOrder = false;
3049 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003050 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003051 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3052 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003053 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003054 ShouldCheckOrder = true;
3055 break;
3056 }
3057 }
3058 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003059 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003060
John McCallbb7b6582010-04-10 07:37:23 +00003061 // Build the list of bases and members in the order that they'll
3062 // actually be initialized. The explicit initializers should be in
3063 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003064 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003065
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003066 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3067
John McCallbb7b6582010-04-10 07:37:23 +00003068 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003069 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003070 ClassDecl->vbases_begin(),
3071 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003072 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003073
John McCallbb7b6582010-04-10 07:37:23 +00003074 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003075 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003076 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003077 if (Base->isVirtual())
3078 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003079 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003080 }
Mike Stump11289f42009-09-09 15:08:12 +00003081
John McCallbb7b6582010-04-10 07:37:23 +00003082 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003083 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003084 E = ClassDecl->field_end(); Field != E; ++Field) {
3085 if (Field->isUnnamedBitfield())
3086 continue;
3087
John McCallbb7b6582010-04-10 07:37:23 +00003088 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregor556e5862011-10-10 17:22:13 +00003089 }
3090
John McCallbb7b6582010-04-10 07:37:23 +00003091 unsigned NumIdealInits = IdealInitKeys.size();
3092 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003093
Alexis Hunt1d792652011-01-08 20:30:50 +00003094 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00003095 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003096 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00003097 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003098
3099 // Scan forward to try to find this initializer in the idealized
3100 // initializers list.
3101 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3102 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003103 break;
John McCallbb7b6582010-04-10 07:37:23 +00003104
3105 // If we didn't find this initializer, it must be because we
3106 // scanned past it on a previous iteration. That can only
3107 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003108 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003109 Sema::SemaDiagnosticBuilder D =
3110 SemaRef.Diag(PrevInit->getSourceLocation(),
3111 diag::warn_initializer_out_of_order);
3112
Francois Pichetd583da02010-12-04 09:14:42 +00003113 if (PrevInit->isAnyMemberInitializer())
3114 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003115 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003116 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003117
Francois Pichetd583da02010-12-04 09:14:42 +00003118 if (Init->isAnyMemberInitializer())
3119 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003120 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003121 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003122
3123 // Move back to the initializer's location in the ideal list.
3124 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3125 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003126 break;
John McCallbb7b6582010-04-10 07:37:23 +00003127
3128 assert(IdealIndex != NumIdealInits &&
3129 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003130 }
John McCallbb7b6582010-04-10 07:37:23 +00003131
3132 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003133 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003134}
3135
John McCall23eebd92010-04-10 09:28:51 +00003136namespace {
3137bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003138 CXXCtorInitializer *Init,
3139 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003140 if (!PrevInit) {
3141 PrevInit = Init;
3142 return false;
3143 }
3144
3145 if (FieldDecl *Field = Init->getMember())
3146 S.Diag(Init->getSourceLocation(),
3147 diag::err_multiple_mem_initialization)
3148 << Field->getDeclName()
3149 << Init->getSourceRange();
3150 else {
John McCall424cec92011-01-19 06:33:43 +00003151 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003152 assert(BaseClass && "neither field nor base");
3153 S.Diag(Init->getSourceLocation(),
3154 diag::err_multiple_base_initialization)
3155 << QualType(BaseClass, 0)
3156 << Init->getSourceRange();
3157 }
3158 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3159 << 0 << PrevInit->getSourceRange();
3160
3161 return true;
3162}
3163
Alexis Hunt1d792652011-01-08 20:30:50 +00003164typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003165typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3166
3167bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003168 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003169 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003170 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003171 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003172 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003173
3174 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003175 if (Parent->isUnion()) {
3176 UnionEntry &En = Unions[Parent];
3177 if (En.first && En.first != Child) {
3178 S.Diag(Init->getSourceLocation(),
3179 diag::err_multiple_mem_union_initialization)
3180 << Field->getDeclName()
3181 << Init->getSourceRange();
3182 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3183 << 0 << En.second->getSourceRange();
3184 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003185 }
3186 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003187 En.first = Child;
3188 En.second = Init;
3189 }
David Blaikie0f65d592011-11-17 06:01:57 +00003190 if (!Parent->isAnonymousStructOrUnion())
3191 return false;
John McCall23eebd92010-04-10 09:28:51 +00003192 }
3193
3194 Child = Parent;
3195 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003196 }
John McCall23eebd92010-04-10 09:28:51 +00003197
3198 return false;
3199}
3200}
3201
Anders Carlssone857b292010-04-02 03:37:03 +00003202/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003203void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003204 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003205 CXXCtorInitializer **meminits,
3206 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003207 bool AnyErrors) {
3208 if (!ConstructorDecl)
3209 return;
3210
3211 AdjustDeclIfTemplate(ConstructorDecl);
3212
3213 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003214 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003215
3216 if (!Constructor) {
3217 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3218 return;
3219 }
3220
Alexis Hunt1d792652011-01-08 20:30:50 +00003221 CXXCtorInitializer **MemInits =
3222 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003223
3224 // Mapping for the duplicate initializers check.
3225 // For member initializers, this is keyed with a FieldDecl*.
3226 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003227 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003228
3229 // Mapping for the inconsistent anonymous-union initializers check.
3230 RedundantUnionMap MemberUnions;
3231
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003232 bool HadError = false;
3233 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003234 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003235
Abramo Bagnara341d7832010-05-26 18:09:23 +00003236 // Set the source order index.
3237 Init->setSourceOrder(i);
3238
Francois Pichetd583da02010-12-04 09:14:42 +00003239 if (Init->isAnyMemberInitializer()) {
3240 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003241 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3242 CheckRedundantUnionInit(*this, Init, MemberUnions))
3243 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003244 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003245 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3246 if (CheckRedundantInit(*this, Init, Members[Key]))
3247 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003248 } else {
3249 assert(Init->isDelegatingInitializer());
3250 // This must be the only initializer
3251 if (i != 0 || NumMemInits > 1) {
3252 Diag(MemInits[0]->getSourceLocation(),
3253 diag::err_delegating_initializer_alone)
3254 << MemInits[0]->getSourceRange();
3255 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003256 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003257 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003258 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003259 // Return immediately as the initializer is set.
3260 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003261 }
Anders Carlssone857b292010-04-02 03:37:03 +00003262 }
3263
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003264 if (HadError)
3265 return;
3266
Anders Carlssone857b292010-04-02 03:37:03 +00003267 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003268
Alexis Hunt1d792652011-01-08 20:30:50 +00003269 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003270}
3271
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003272void
John McCalla6309952010-03-16 21:39:52 +00003273Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3274 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003275 // Ignore dependent contexts. Also ignore unions, since their members never
3276 // have destructors implicitly called.
3277 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003278 return;
John McCall1064d7e2010-03-16 05:22:47 +00003279
3280 // FIXME: all the access-control diagnostics are positioned on the
3281 // field/base declaration. That's probably good; that said, the
3282 // user might reasonably want to know why the destructor is being
3283 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003284
Anders Carlssondee9a302009-11-17 04:44:12 +00003285 // Non-static data members.
3286 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3287 E = ClassDecl->field_end(); I != E; ++I) {
3288 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003289 if (Field->isInvalidDecl())
3290 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003291
3292 // Don't destroy incomplete or zero-length arrays.
3293 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3294 continue;
3295
Anders Carlssondee9a302009-11-17 04:44:12 +00003296 QualType FieldType = Context.getBaseElementType(Field->getType());
3297
3298 const RecordType* RT = FieldType->getAs<RecordType>();
3299 if (!RT)
3300 continue;
3301
3302 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003303 if (FieldClassDecl->isInvalidDecl())
3304 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003305 if (FieldClassDecl->hasTrivialDestructor())
3306 continue;
3307
Douglas Gregore71edda2010-07-01 22:47:18 +00003308 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003309 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003310 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003311 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003312 << Field->getDeclName()
3313 << FieldType);
3314
Eli Friedmanfa0df832012-02-02 03:46:19 +00003315 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003316 }
3317
John McCall1064d7e2010-03-16 05:22:47 +00003318 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3319
Anders Carlssondee9a302009-11-17 04:44:12 +00003320 // Bases.
3321 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3322 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003323 // Bases are always records in a well-formed non-dependent class.
3324 const RecordType *RT = Base->getType()->getAs<RecordType>();
3325
3326 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003327 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003328 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003329
John McCall1064d7e2010-03-16 05:22:47 +00003330 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003331 // If our base class is invalid, we probably can't get its dtor anyway.
3332 if (BaseClassDecl->isInvalidDecl())
3333 continue;
3334 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003335 if (BaseClassDecl->hasTrivialDestructor())
3336 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003337
Douglas Gregore71edda2010-07-01 22:47:18 +00003338 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003339 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003340
3341 // FIXME: caret should be on the start of the class name
3342 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003343 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003344 << Base->getType()
3345 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003346
Eli Friedmanfa0df832012-02-02 03:46:19 +00003347 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003348 }
3349
3350 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003353
3354 // Bases are always records in a well-formed non-dependent class.
3355 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3356
3357 // Ignore direct virtual bases.
3358 if (DirectVirtualBases.count(RT))
3359 continue;
3360
John McCall1064d7e2010-03-16 05:22:47 +00003361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003362 // If our base class is invalid, we probably can't get its dtor anyway.
3363 if (BaseClassDecl->isInvalidDecl())
3364 continue;
3365 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003366 if (BaseClassDecl->hasTrivialDestructor())
3367 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003368
Douglas Gregore71edda2010-07-01 22:47:18 +00003369 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003370 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003371 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003372 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003373 << VBase->getType());
3374
Eli Friedmanfa0df832012-02-02 03:46:19 +00003375 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003376 }
3377}
3378
John McCall48871652010-08-21 09:40:31 +00003379void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003380 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003381 return;
Mike Stump11289f42009-09-09 15:08:12 +00003382
Mike Stump11289f42009-09-09 15:08:12 +00003383 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003384 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003385 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003386}
3387
Mike Stump11289f42009-09-09 15:08:12 +00003388bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003389 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003390 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003391 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003392 else
John McCall02db245d2010-08-18 09:41:07 +00003393 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003394}
3395
Anders Carlssoneabf7702009-08-27 00:13:57 +00003396bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003397 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003398 if (!getLangOptions().CPlusPlus)
3399 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003401 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003402 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003403
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003404 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003405 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003406 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003407 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003408
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003409 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003410 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003413 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003414 if (!RT)
3415 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003416
John McCall67da35c2010-02-04 22:26:26 +00003417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003418
John McCall02db245d2010-08-18 09:41:07 +00003419 // We can't answer whether something is abstract until it has a
3420 // definition. If it's currently being defined, we'll walk back
3421 // over all the declarations when we have a full definition.
3422 const CXXRecordDecl *Def = RD->getDefinition();
3423 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003424 return false;
3425
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003426 if (!RD->isAbstract())
3427 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003428
Anders Carlssoneabf7702009-08-27 00:13:57 +00003429 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003430 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003431
John McCall02db245d2010-08-18 09:41:07 +00003432 return true;
3433}
3434
3435void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3436 // Check if we've already emitted the list of pure virtual functions
3437 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003438 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003439 return;
Mike Stump11289f42009-09-09 15:08:12 +00003440
Douglas Gregor4165bd62010-03-23 23:47:56 +00003441 CXXFinalOverriderMap FinalOverriders;
3442 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003443
Anders Carlssona2f74f32010-06-03 01:00:02 +00003444 // Keep a set of seen pure methods so we won't diagnose the same method
3445 // more than once.
3446 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3447
Douglas Gregor4165bd62010-03-23 23:47:56 +00003448 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3449 MEnd = FinalOverriders.end();
3450 M != MEnd;
3451 ++M) {
3452 for (OverridingMethods::iterator SO = M->second.begin(),
3453 SOEnd = M->second.end();
3454 SO != SOEnd; ++SO) {
3455 // C++ [class.abstract]p4:
3456 // A class is abstract if it contains or inherits at least one
3457 // pure virtual function for which the final overrider is pure
3458 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003459
Douglas Gregor4165bd62010-03-23 23:47:56 +00003460 //
3461 if (SO->second.size() != 1)
3462 continue;
3463
3464 if (!SO->second.front().Method->isPure())
3465 continue;
3466
Anders Carlssona2f74f32010-06-03 01:00:02 +00003467 if (!SeenPureMethods.insert(SO->second.front().Method))
3468 continue;
3469
Douglas Gregor4165bd62010-03-23 23:47:56 +00003470 Diag(SO->second.front().Method->getLocation(),
3471 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003472 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003473 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003474 }
3475
3476 if (!PureVirtualClassDiagSet)
3477 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3478 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003479}
3480
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003481namespace {
John McCall02db245d2010-08-18 09:41:07 +00003482struct AbstractUsageInfo {
3483 Sema &S;
3484 CXXRecordDecl *Record;
3485 CanQualType AbstractType;
3486 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003487
John McCall02db245d2010-08-18 09:41:07 +00003488 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3489 : S(S), Record(Record),
3490 AbstractType(S.Context.getCanonicalType(
3491 S.Context.getTypeDeclType(Record))),
3492 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003493
John McCall02db245d2010-08-18 09:41:07 +00003494 void DiagnoseAbstractType() {
3495 if (Invalid) return;
3496 S.DiagnoseAbstractType(Record);
3497 Invalid = true;
3498 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003499
John McCall02db245d2010-08-18 09:41:07 +00003500 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3501};
3502
3503struct CheckAbstractUsage {
3504 AbstractUsageInfo &Info;
3505 const NamedDecl *Ctx;
3506
3507 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3508 : Info(Info), Ctx(Ctx) {}
3509
3510 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3511 switch (TL.getTypeLocClass()) {
3512#define ABSTRACT_TYPELOC(CLASS, PARENT)
3513#define TYPELOC(CLASS, PARENT) \
3514 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3515#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003516 }
John McCall02db245d2010-08-18 09:41:07 +00003517 }
Mike Stump11289f42009-09-09 15:08:12 +00003518
John McCall02db245d2010-08-18 09:41:07 +00003519 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3520 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3521 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003522 if (!TL.getArg(I))
3523 continue;
3524
John McCall02db245d2010-08-18 09:41:07 +00003525 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3526 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003527 }
John McCall02db245d2010-08-18 09:41:07 +00003528 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003529
John McCall02db245d2010-08-18 09:41:07 +00003530 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3531 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3532 }
Mike Stump11289f42009-09-09 15:08:12 +00003533
John McCall02db245d2010-08-18 09:41:07 +00003534 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3535 // Visit the type parameters from a permissive context.
3536 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3537 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3538 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3539 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3540 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3541 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003542 }
John McCall02db245d2010-08-18 09:41:07 +00003543 }
Mike Stump11289f42009-09-09 15:08:12 +00003544
John McCall02db245d2010-08-18 09:41:07 +00003545 // Visit pointee types from a permissive context.
3546#define CheckPolymorphic(Type) \
3547 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3548 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3549 }
3550 CheckPolymorphic(PointerTypeLoc)
3551 CheckPolymorphic(ReferenceTypeLoc)
3552 CheckPolymorphic(MemberPointerTypeLoc)
3553 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003554 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003555
John McCall02db245d2010-08-18 09:41:07 +00003556 /// Handle all the types we haven't given a more specific
3557 /// implementation for above.
3558 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3559 // Every other kind of type that we haven't called out already
3560 // that has an inner type is either (1) sugar or (2) contains that
3561 // inner type in some way as a subobject.
3562 if (TypeLoc Next = TL.getNextTypeLoc())
3563 return Visit(Next, Sel);
3564
3565 // If there's no inner type and we're in a permissive context,
3566 // don't diagnose.
3567 if (Sel == Sema::AbstractNone) return;
3568
3569 // Check whether the type matches the abstract type.
3570 QualType T = TL.getType();
3571 if (T->isArrayType()) {
3572 Sel = Sema::AbstractArrayType;
3573 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003574 }
John McCall02db245d2010-08-18 09:41:07 +00003575 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3576 if (CT != Info.AbstractType) return;
3577
3578 // It matched; do some magic.
3579 if (Sel == Sema::AbstractArrayType) {
3580 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3581 << T << TL.getSourceRange();
3582 } else {
3583 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3584 << Sel << T << TL.getSourceRange();
3585 }
3586 Info.DiagnoseAbstractType();
3587 }
3588};
3589
3590void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3591 Sema::AbstractDiagSelID Sel) {
3592 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3593}
3594
3595}
3596
3597/// Check for invalid uses of an abstract type in a method declaration.
3598static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3599 CXXMethodDecl *MD) {
3600 // No need to do the check on definitions, which require that
3601 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003602 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003603 return;
3604
3605 // For safety's sake, just ignore it if we don't have type source
3606 // information. This should never happen for non-implicit methods,
3607 // but...
3608 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3609 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3610}
3611
3612/// Check for invalid uses of an abstract type within a class definition.
3613static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3614 CXXRecordDecl *RD) {
3615 for (CXXRecordDecl::decl_iterator
3616 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3617 Decl *D = *I;
3618 if (D->isImplicit()) continue;
3619
3620 // Methods and method templates.
3621 if (isa<CXXMethodDecl>(D)) {
3622 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3623 } else if (isa<FunctionTemplateDecl>(D)) {
3624 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3626
3627 // Fields and static variables.
3628 } else if (isa<FieldDecl>(D)) {
3629 FieldDecl *FD = cast<FieldDecl>(D);
3630 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3631 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3632 } else if (isa<VarDecl>(D)) {
3633 VarDecl *VD = cast<VarDecl>(D);
3634 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3635 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3636
3637 // Nested classes and class templates.
3638 } else if (isa<CXXRecordDecl>(D)) {
3639 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3640 } else if (isa<ClassTemplateDecl>(D)) {
3641 CheckAbstractClassUsage(Info,
3642 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3643 }
3644 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003645}
3646
Douglas Gregorc99f1552009-12-03 18:33:45 +00003647/// \brief Perform semantic checks on a class definition that has been
3648/// completing, introducing implicitly-declared members, checking for
3649/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003650void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003651 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003652 return;
3653
John McCall02db245d2010-08-18 09:41:07 +00003654 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3655 AbstractUsageInfo Info(*this, Record);
3656 CheckAbstractClassUsage(Info, Record);
3657 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003658
3659 // If this is not an aggregate type and has no user-declared constructor,
3660 // complain about any non-static data members of reference or const scalar
3661 // type, since they will never get initializers.
3662 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00003663 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3664 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003665 bool Complained = false;
3666 for (RecordDecl::field_iterator F = Record->field_begin(),
3667 FEnd = Record->field_end();
3668 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003669 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00003670 continue;
3671
Douglas Gregor454a5b62010-04-15 00:00:53 +00003672 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003673 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003674 if (!Complained) {
3675 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3676 << Record->getTagKind() << Record;
3677 Complained = true;
3678 }
3679
3680 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3681 << F->getType()->isReferenceType()
3682 << F->getDeclName();
3683 }
3684 }
3685 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003686
Anders Carlssone771e762011-01-25 18:08:22 +00003687 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003688 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003689
3690 if (Record->getIdentifier()) {
3691 // C++ [class.mem]p13:
3692 // If T is the name of a class, then each of the following shall have a
3693 // name different from T:
3694 // - every member of every anonymous union that is a member of class T.
3695 //
3696 // C++ [class.mem]p14:
3697 // In addition, if class T has a user-declared constructor (12.1), every
3698 // non-static data member of class T shall have a name different from T.
3699 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003700 R.first != R.second; ++R.first) {
3701 NamedDecl *D = *R.first;
3702 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3703 isa<IndirectFieldDecl>(D)) {
3704 Diag(D->getLocation(), diag::err_member_name_of_class)
3705 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003706 break;
3707 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003708 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003709 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003710
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003711 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003712 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003713 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003714 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003715 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3716 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3717 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003718
3719 // See if a method overloads virtual methods in a base
3720 /// class without overriding any.
3721 if (!Record->isDependentType()) {
3722 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3723 MEnd = Record->method_end();
3724 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003725 if (!(*M)->isStatic())
3726 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003727 }
3728 }
Sebastian Redl08905022011-02-05 19:23:19 +00003729
Richard Smitheb3c10c2011-10-01 02:31:28 +00003730 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3731 // function that is not a constructor declares that member function to be
3732 // const. [...] The class of which that function is a member shall be
3733 // a literal type.
3734 //
Richard Smitheb3c10c2011-10-01 02:31:28 +00003735 // If the class has virtual bases, any constexpr members will already have
3736 // been diagnosed by the checks performed on the member declaration, so
3737 // suppress this (less useful) diagnostic.
3738 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3739 !Record->isLiteral() && !Record->getNumVBases()) {
3740 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3741 MEnd = Record->method_end();
3742 M != MEnd; ++M) {
Richard Smith3607ffe2012-02-13 03:54:03 +00003743 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00003744 switch (Record->getTemplateSpecializationKind()) {
3745 case TSK_ImplicitInstantiation:
3746 case TSK_ExplicitInstantiationDeclaration:
3747 case TSK_ExplicitInstantiationDefinition:
3748 // If a template instantiates to a non-literal type, but its members
3749 // instantiate to constexpr functions, the template is technically
Richard Smith3607ffe2012-02-13 03:54:03 +00003750 // ill-formed, but we allow it for sanity.
Richard Smitheb3c10c2011-10-01 02:31:28 +00003751 continue;
3752
3753 case TSK_Undeclared:
3754 case TSK_ExplicitSpecialization:
3755 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3756 PDiag(diag::err_constexpr_method_non_literal));
3757 break;
3758 }
3759
3760 // Only produce one error per class.
3761 break;
3762 }
3763 }
3764 }
3765
Sebastian Redl08905022011-02-05 19:23:19 +00003766 // Declare inherited constructors. We do this eagerly here because:
3767 // - The standard requires an eager diagnostic for conflicting inherited
3768 // constructors from different classes.
3769 // - The lazy declaration of the other implicit constructors is so as to not
3770 // waste space and performance on classes that are not meant to be
3771 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3772 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003773 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003774
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003775 if (!Record->isDependentType())
3776 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003777}
3778
3779void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003780 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3781 ME = Record->method_end();
3782 MI != ME; ++MI) {
3783 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3784 switch (getSpecialMember(*MI)) {
3785 case CXXDefaultConstructor:
3786 CheckExplicitlyDefaultedDefaultConstructor(
3787 cast<CXXConstructorDecl>(*MI));
3788 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003789
Alexis Huntf91729462011-05-12 22:46:25 +00003790 case CXXDestructor:
3791 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3792 break;
3793
3794 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003795 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3796 break;
3797
Alexis Huntf91729462011-05-12 22:46:25 +00003798 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003799 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003800 break;
3801
Alexis Hunt119c10e2011-05-25 23:16:36 +00003802 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003803 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003804 break;
3805
Sebastian Redl22653ba2011-08-30 19:58:05 +00003806 case CXXMoveAssignment:
3807 CheckExplicitlyDefaultedMoveAssignment(*MI);
3808 break;
3809
3810 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003811 llvm_unreachable("non-special member explicitly defaulted!");
3812 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003813 }
3814 }
3815
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003816}
3817
3818void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3819 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3820
3821 // Whether this was the first-declared instance of the constructor.
3822 // This affects whether we implicitly add an exception spec (and, eventually,
3823 // constexpr). It is also ill-formed to explicitly default a constructor such
3824 // that it would be deleted. (C++0x [decl.fct.def.default])
3825 bool First = CD == CD->getCanonicalDecl();
3826
Alexis Hunt913820d2011-05-13 06:10:58 +00003827 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003828 if (CD->getNumParams() != 0) {
3829 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3830 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003831 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003832 }
3833
3834 ImplicitExceptionSpecification Spec
3835 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3836 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003837 if (EPI.ExceptionSpecType == EST_Delayed) {
3838 // Exception specification depends on some deferred part of the class. We'll
3839 // try again when the class's definition has been fully processed.
3840 return;
3841 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003842 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3843 *ExceptionType = Context.getFunctionType(
3844 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3845
Richard Smithcc36f692011-12-22 02:22:31 +00003846 // C++11 [dcl.fct.def.default]p2:
3847 // An explicitly-defaulted function may be declared constexpr only if it
3848 // would have been implicitly declared as constexpr,
Richard Smithe7f5de42012-02-14 02:33:50 +00003849 // Do not apply this rule to templates, since core issue 1358 makes such
3850 // functions always instantiate to constexpr functions.
3851 if (CD->isConstexpr() &&
3852 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smithcc36f692011-12-22 02:22:31 +00003853 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3854 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3855 << CXXDefaultConstructor;
3856 HadError = true;
3857 }
3858 }
3859 // and may have an explicit exception-specification only if it is compatible
3860 // with the exception-specification on the implicit declaration.
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003861 if (CtorType->hasExceptionSpec()) {
3862 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003863 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003864 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003865 PDiag(),
3866 ExceptionType, SourceLocation(),
3867 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003868 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003869 }
Richard Smithcc36f692011-12-22 02:22:31 +00003870 }
3871
3872 // If a function is explicitly defaulted on its first declaration,
3873 if (First) {
3874 // -- it is implicitly considered to be constexpr if the implicit
3875 // definition would be,
3876 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3877
3878 // -- it is implicitly considered to have the same
3879 // exception-specification as if it had been implicitly declared
3880 //
3881 // FIXME: a compatible, but different, explicit exception specification
3882 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003883 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003884 }
Alexis Huntb3153022011-05-12 03:51:48 +00003885
Alexis Hunt913820d2011-05-13 06:10:58 +00003886 if (HadError) {
3887 CD->setInvalidDecl();
3888 return;
3889 }
3890
Alexis Huntd6da8762011-10-10 06:18:57 +00003891 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003892 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003893 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003894 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003895 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003896 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003897 CD->setInvalidDecl();
3898 }
3899 }
3900}
3901
3902void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3903 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3904
3905 // Whether this was the first-declared instance of the constructor.
3906 bool First = CD == CD->getCanonicalDecl();
3907
3908 bool HadError = false;
3909 if (CD->getNumParams() != 1) {
3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3911 << CD->getSourceRange();
3912 HadError = true;
3913 }
3914
3915 ImplicitExceptionSpecification Spec(Context);
3916 bool Const;
3917 llvm::tie(Spec, Const) =
3918 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3919
3920 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3921 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3922 *ExceptionType = Context.getFunctionType(
3923 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3924
3925 // Check for parameter type matching.
3926 // This is a copy ctor so we know it's a cv-qualified reference to T.
3927 QualType ArgType = CtorType->getArgType(0);
3928 if (ArgType->getPointeeType().isVolatileQualified()) {
3929 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3930 HadError = true;
3931 }
3932 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3933 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3934 HadError = true;
3935 }
3936
Richard Smithcc36f692011-12-22 02:22:31 +00003937 // C++11 [dcl.fct.def.default]p2:
3938 // An explicitly-defaulted function may be declared constexpr only if it
3939 // would have been implicitly declared as constexpr,
Richard Smithe7f5de42012-02-14 02:33:50 +00003940 // Do not apply this rule to templates, since core issue 1358 makes such
3941 // functions always instantiate to constexpr functions.
3942 if (CD->isConstexpr() &&
3943 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smithcc36f692011-12-22 02:22:31 +00003944 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3945 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3946 << CXXCopyConstructor;
3947 HadError = true;
3948 }
3949 }
3950 // and may have an explicit exception-specification only if it is compatible
3951 // with the exception-specification on the implicit declaration.
Alexis Hunt913820d2011-05-13 06:10:58 +00003952 if (CtorType->hasExceptionSpec()) {
3953 if (CheckEquivalentExceptionSpec(
3954 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003955 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003956 PDiag(),
3957 ExceptionType, SourceLocation(),
3958 CtorType, CD->getLocation())) {
3959 HadError = true;
3960 }
Richard Smithcc36f692011-12-22 02:22:31 +00003961 }
3962
3963 // If a function is explicitly defaulted on its first declaration,
3964 if (First) {
3965 // -- it is implicitly considered to be constexpr if the implicit
3966 // definition would be,
3967 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3968
3969 // -- it is implicitly considered to have the same
3970 // exception-specification as if it had been implicitly declared, and
3971 //
3972 // FIXME: a compatible, but different, explicit exception specification
3973 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003974 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00003975
3976 // -- [...] it shall have the same parameter type as if it had been
3977 // implicitly declared.
Alexis Hunt913820d2011-05-13 06:10:58 +00003978 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3979 }
3980
3981 if (HadError) {
3982 CD->setInvalidDecl();
3983 return;
3984 }
3985
Alexis Hunt1bc6f712011-10-11 04:55:36 +00003986 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003987 if (First) {
3988 CD->setDeletedAsWritten();
3989 } else {
3990 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003991 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003992 CD->setInvalidDecl();
3993 }
Alexis Huntb3153022011-05-12 03:51:48 +00003994 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003995}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003996
Alexis Huntc9a55732011-05-14 05:23:28 +00003997void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3998 assert(MD->isExplicitlyDefaulted());
3999
4000 // Whether this was the first-declared instance of the operator
4001 bool First = MD == MD->getCanonicalDecl();
4002
4003 bool HadError = false;
4004 if (MD->getNumParams() != 1) {
4005 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4006 << MD->getSourceRange();
4007 HadError = true;
4008 }
4009
4010 QualType ReturnType =
4011 MD->getType()->getAs<FunctionType>()->getResultType();
4012 if (!ReturnType->isLValueReferenceType() ||
4013 !Context.hasSameType(
4014 Context.getCanonicalType(ReturnType->getPointeeType()),
4015 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4016 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4017 HadError = true;
4018 }
4019
4020 ImplicitExceptionSpecification Spec(Context);
4021 bool Const;
4022 llvm::tie(Spec, Const) =
4023 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4024
4025 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4026 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4027 *ExceptionType = Context.getFunctionType(
4028 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4029
Alexis Huntc9a55732011-05-14 05:23:28 +00004030 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004031 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00004032 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004033 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00004034 } else {
4035 if (ArgType->getPointeeType().isVolatileQualified()) {
4036 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4037 HadError = true;
4038 }
4039 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4040 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4041 HadError = true;
4042 }
Alexis Huntc9a55732011-05-14 05:23:28 +00004043 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004044
Alexis Huntc9a55732011-05-14 05:23:28 +00004045 if (OperType->getTypeQuals()) {
4046 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4047 HadError = true;
4048 }
4049
4050 if (OperType->hasExceptionSpec()) {
4051 if (CheckEquivalentExceptionSpec(
4052 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004053 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00004054 PDiag(),
4055 ExceptionType, SourceLocation(),
4056 OperType, MD->getLocation())) {
4057 HadError = true;
4058 }
Richard Smithcc36f692011-12-22 02:22:31 +00004059 }
4060 if (First) {
Alexis Huntc9a55732011-05-14 05:23:28 +00004061 // We set the declaration to have the computed exception spec here.
4062 // We duplicate the one parameter type.
4063 EPI.RefQualifier = OperType->getRefQualifier();
4064 EPI.ExtInfo = OperType->getExtInfo();
4065 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4066 }
4067
4068 if (HadError) {
4069 MD->setInvalidDecl();
4070 return;
4071 }
4072
4073 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4074 if (First) {
4075 MD->setDeletedAsWritten();
4076 } else {
4077 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004078 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00004079 MD->setInvalidDecl();
4080 }
4081 }
4082}
4083
Sebastian Redl22653ba2011-08-30 19:58:05 +00004084void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4085 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4086
4087 // Whether this was the first-declared instance of the constructor.
4088 bool First = CD == CD->getCanonicalDecl();
4089
4090 bool HadError = false;
4091 if (CD->getNumParams() != 1) {
4092 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4093 << CD->getSourceRange();
4094 HadError = true;
4095 }
4096
4097 ImplicitExceptionSpecification Spec(
4098 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4099
4100 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4101 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4102 *ExceptionType = Context.getFunctionType(
4103 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4104
4105 // Check for parameter type matching.
4106 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4107 QualType ArgType = CtorType->getArgType(0);
4108 if (ArgType->getPointeeType().isVolatileQualified()) {
4109 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4110 HadError = true;
4111 }
4112 if (ArgType->getPointeeType().isConstQualified()) {
4113 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4114 HadError = true;
4115 }
4116
Richard Smithcc36f692011-12-22 02:22:31 +00004117 // C++11 [dcl.fct.def.default]p2:
4118 // An explicitly-defaulted function may be declared constexpr only if it
4119 // would have been implicitly declared as constexpr,
Richard Smithe7f5de42012-02-14 02:33:50 +00004120 // Do not apply this rule to templates, since core issue 1358 makes such
4121 // functions always instantiate to constexpr functions.
4122 if (CD->isConstexpr() &&
4123 CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
Richard Smithcc36f692011-12-22 02:22:31 +00004124 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4125 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4126 << CXXMoveConstructor;
4127 HadError = true;
4128 }
4129 }
4130 // and may have an explicit exception-specification only if it is compatible
4131 // with the exception-specification on the implicit declaration.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004132 if (CtorType->hasExceptionSpec()) {
4133 if (CheckEquivalentExceptionSpec(
4134 PDiag(diag::err_incorrect_defaulted_exception_spec)
4135 << CXXMoveConstructor,
4136 PDiag(),
4137 ExceptionType, SourceLocation(),
4138 CtorType, CD->getLocation())) {
4139 HadError = true;
4140 }
Richard Smithcc36f692011-12-22 02:22:31 +00004141 }
4142
4143 // If a function is explicitly defaulted on its first declaration,
4144 if (First) {
4145 // -- it is implicitly considered to be constexpr if the implicit
4146 // definition would be,
4147 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4148
4149 // -- it is implicitly considered to have the same
4150 // exception-specification as if it had been implicitly declared, and
4151 //
4152 // FIXME: a compatible, but different, explicit exception specification
4153 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004154 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00004155
4156 // -- [...] it shall have the same parameter type as if it had been
4157 // implicitly declared.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004158 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4159 }
4160
4161 if (HadError) {
4162 CD->setInvalidDecl();
4163 return;
4164 }
4165
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004166 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004167 if (First) {
4168 CD->setDeletedAsWritten();
4169 } else {
4170 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4171 << CXXMoveConstructor;
4172 CD->setInvalidDecl();
4173 }
4174 }
4175}
4176
4177void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4178 assert(MD->isExplicitlyDefaulted());
4179
4180 // Whether this was the first-declared instance of the operator
4181 bool First = MD == MD->getCanonicalDecl();
4182
4183 bool HadError = false;
4184 if (MD->getNumParams() != 1) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4186 << MD->getSourceRange();
4187 HadError = true;
4188 }
4189
4190 QualType ReturnType =
4191 MD->getType()->getAs<FunctionType>()->getResultType();
4192 if (!ReturnType->isLValueReferenceType() ||
4193 !Context.hasSameType(
4194 Context.getCanonicalType(ReturnType->getPointeeType()),
4195 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4196 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4197 HadError = true;
4198 }
4199
4200 ImplicitExceptionSpecification Spec(
4201 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4202
4203 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4204 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4205 *ExceptionType = Context.getFunctionType(
4206 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4207
4208 QualType ArgType = OperType->getArgType(0);
4209 if (!ArgType->isRValueReferenceType()) {
4210 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4211 HadError = true;
4212 } else {
4213 if (ArgType->getPointeeType().isVolatileQualified()) {
4214 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4215 HadError = true;
4216 }
4217 if (ArgType->getPointeeType().isConstQualified()) {
4218 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4219 HadError = true;
4220 }
4221 }
4222
4223 if (OperType->getTypeQuals()) {
4224 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4225 HadError = true;
4226 }
4227
4228 if (OperType->hasExceptionSpec()) {
4229 if (CheckEquivalentExceptionSpec(
4230 PDiag(diag::err_incorrect_defaulted_exception_spec)
4231 << CXXMoveAssignment,
4232 PDiag(),
4233 ExceptionType, SourceLocation(),
4234 OperType, MD->getLocation())) {
4235 HadError = true;
4236 }
Richard Smithcc36f692011-12-22 02:22:31 +00004237 }
4238 if (First) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004239 // We set the declaration to have the computed exception spec here.
4240 // We duplicate the one parameter type.
4241 EPI.RefQualifier = OperType->getRefQualifier();
4242 EPI.ExtInfo = OperType->getExtInfo();
4243 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4244 }
4245
4246 if (HadError) {
4247 MD->setInvalidDecl();
4248 return;
4249 }
4250
4251 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4252 if (First) {
4253 MD->setDeletedAsWritten();
4254 } else {
4255 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4256 << CXXMoveAssignment;
4257 MD->setInvalidDecl();
4258 }
4259 }
4260}
4261
Alexis Huntf91729462011-05-12 22:46:25 +00004262void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4263 assert(DD->isExplicitlyDefaulted());
4264
4265 // Whether this was the first-declared instance of the destructor.
4266 bool First = DD == DD->getCanonicalDecl();
4267
4268 ImplicitExceptionSpecification Spec
4269 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4270 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4271 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4272 *ExceptionType = Context.getFunctionType(
4273 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4274
4275 if (DtorType->hasExceptionSpec()) {
4276 if (CheckEquivalentExceptionSpec(
4277 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004278 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004279 PDiag(),
4280 ExceptionType, SourceLocation(),
4281 DtorType, DD->getLocation())) {
4282 DD->setInvalidDecl();
4283 return;
4284 }
Richard Smithcc36f692011-12-22 02:22:31 +00004285 }
4286 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004287 // We set the declaration to have the computed exception spec here.
4288 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004289 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004290 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4291 }
4292
4293 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004294 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004295 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004296 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004297 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004298 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004299 DD->setInvalidDecl();
4300 }
Alexis Huntf91729462011-05-12 22:46:25 +00004301 }
Alexis Huntf91729462011-05-12 22:46:25 +00004302}
4303
Alexis Huntd6da8762011-10-10 06:18:57 +00004304/// This function implements the following C++0x paragraphs:
4305/// - [class.ctor]/5
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004306/// - [class.copy]/11
Alexis Huntd6da8762011-10-10 06:18:57 +00004307bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4308 assert(!MD->isInvalidDecl());
4309 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004310 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004311 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004312 return false;
4313
Alexis Huntd6da8762011-10-10 06:18:57 +00004314 bool IsUnion = RD->isUnion();
4315 bool IsConstructor = false;
4316 bool IsAssignment = false;
4317 bool IsMove = false;
4318
4319 bool ConstArg = false;
4320
4321 switch (CSM) {
4322 case CXXDefaultConstructor:
4323 IsConstructor = true;
Douglas Gregor1a22d282012-02-12 17:34:23 +00004324
4325 // C++11 [expr.lambda.prim]p19:
4326 // The closure type associated with a lambda-expression has a
4327 // deleted (8.4.3) default constructor.
4328 if (RD->isLambda())
4329 return true;
4330
Alexis Huntd6da8762011-10-10 06:18:57 +00004331 break;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004332 case CXXCopyConstructor:
4333 IsConstructor = true;
4334 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4335 break;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004336 case CXXMoveConstructor:
4337 IsConstructor = true;
4338 IsMove = true;
4339 break;
Alexis Huntd6da8762011-10-10 06:18:57 +00004340 default:
4341 llvm_unreachable("function only currently implemented for default ctors");
4342 }
4343
4344 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004345
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004346 // Do access control from the special member function
Alexis Huntd6da8762011-10-10 06:18:57 +00004347 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004348
Alexis Huntea6f0322011-05-11 22:34:38 +00004349 bool AllConst = true;
4350
Alexis Huntea6f0322011-05-11 22:34:38 +00004351 // We do this because we should never actually use an anonymous
4352 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004353 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004354 return false;
4355
4356 // FIXME: We should put some diagnostic logic right into this function.
4357
Alexis Huntea6f0322011-05-11 22:34:38 +00004358 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4359 BE = RD->bases_end();
4360 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004361 // We'll handle this one later
4362 if (BI->isVirtual())
4363 continue;
4364
Alexis Huntea6f0322011-05-11 22:34:38 +00004365 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4366 assert(BaseDecl && "base isn't a CXXRecordDecl");
4367
Alexis Huntd6da8762011-10-10 06:18:57 +00004368 // Unless we have an assignment operator, the base's destructor must
4369 // be accessible and not deleted.
4370 if (!IsAssignment) {
4371 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4372 if (BaseDtor->isDeleted())
4373 return true;
4374 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4375 AR_accessible)
4376 return true;
4377 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004378
Alexis Huntd6da8762011-10-10 06:18:57 +00004379 // Finding the corresponding member in the base should lead to a
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004380 // unique, accessible, non-deleted function. If we are doing
4381 // a destructor, we have already checked this case.
Alexis Huntd6da8762011-10-10 06:18:57 +00004382 if (CSM != CXXDestructor) {
4383 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004384 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004385 false);
4386 if (!SMOR->hasSuccess())
4387 return true;
4388 CXXMethodDecl *BaseMember = SMOR->getMethod();
4389 if (IsConstructor) {
4390 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4391 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4392 PDiag()) != AR_accessible)
4393 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004394
4395 // For a move operation, the corresponding operation must actually
4396 // be a move operation (and not a copy selected by overload
4397 // resolution) unless we are working on a trivially copyable class.
4398 if (IsMove && !BaseCtor->isMoveConstructor() &&
4399 !BaseDecl->isTriviallyCopyable())
4400 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004401 }
4402 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004403 }
4404
4405 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4406 BE = RD->vbases_end();
4407 BI != BE; ++BI) {
4408 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4409 assert(BaseDecl && "base isn't a CXXRecordDecl");
4410
Alexis Huntd6da8762011-10-10 06:18:57 +00004411 // Unless we have an assignment operator, the base's destructor must
4412 // be accessible and not deleted.
4413 if (!IsAssignment) {
4414 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4415 if (BaseDtor->isDeleted())
4416 return true;
4417 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4418 AR_accessible)
4419 return true;
4420 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004421
Alexis Huntd6da8762011-10-10 06:18:57 +00004422 // Finding the corresponding member in the base should lead to a
4423 // unique, accessible, non-deleted function.
4424 if (CSM != CXXDestructor) {
4425 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004426 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004427 false);
4428 if (!SMOR->hasSuccess())
4429 return true;
4430 CXXMethodDecl *BaseMember = SMOR->getMethod();
4431 if (IsConstructor) {
4432 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4433 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4434 PDiag()) != AR_accessible)
4435 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004436
4437 // For a move operation, the corresponding operation must actually
4438 // be a move operation (and not a copy selected by overload
4439 // resolution) unless we are working on a trivially copyable class.
4440 if (IsMove && !BaseCtor->isMoveConstructor() &&
4441 !BaseDecl->isTriviallyCopyable())
4442 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004443 }
4444 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004445 }
4446
4447 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4448 FE = RD->field_end();
4449 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004450 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004451 continue;
4452
Alexis Huntea6f0322011-05-11 22:34:38 +00004453 QualType FieldType = Context.getBaseElementType(FI->getType());
4454 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004455
Alexis Huntd6da8762011-10-10 06:18:57 +00004456 // For a default constructor, all references must be initialized in-class
4457 // and, if a union, it must have a non-const member.
4458 if (CSM == CXXDefaultConstructor) {
4459 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4460 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004461
Alexis Huntd6da8762011-10-10 06:18:57 +00004462 if (IsUnion && !FieldType.isConstQualified())
4463 AllConst = false;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004464 // For a copy constructor, data members must not be of rvalue reference
4465 // type.
4466 } else if (CSM == CXXCopyConstructor) {
4467 if (FieldType->isRValueReferenceType())
4468 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004469 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004470
4471 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004472 // For a default constructor, a const member must have a user-provided
4473 // default constructor or else be explicitly initialized.
4474 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004475 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004476 !FieldRecord->hasUserProvidedDefaultConstructor())
4477 return true;
4478
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004479 // Some additional restrictions exist on the variant members.
4480 if (!IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004481 FieldRecord->isAnonymousStructOrUnion()) {
4482 // We're okay to reuse AllConst here since we only care about the
4483 // value otherwise if we're in a union.
4484 AllConst = true;
4485
4486 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4487 UE = FieldRecord->field_end();
4488 UI != UE; ++UI) {
4489 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4490 CXXRecordDecl *UnionFieldRecord =
4491 UnionFieldType->getAsCXXRecordDecl();
4492
4493 if (!UnionFieldType.isConstQualified())
4494 AllConst = false;
4495
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004496 if (UnionFieldRecord) {
4497 // FIXME: Checking for accessibility and validity of this
4498 // destructor is technically going beyond the
4499 // standard, but this is believed to be a defect.
4500 if (!IsAssignment) {
4501 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4502 if (FieldDtor->isDeleted())
4503 return true;
4504 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4505 AR_accessible)
4506 return true;
4507 if (!FieldDtor->isTrivial())
4508 return true;
4509 }
4510
4511 if (CSM != CXXDestructor) {
4512 SpecialMemberOverloadResult *SMOR =
4513 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004514 false, false, false);
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004515 // FIXME: Checking for accessibility and validity of this
4516 // corresponding member is technically going beyond the
4517 // standard, but this is believed to be a defect.
4518 if (!SMOR->hasSuccess())
4519 return true;
4520
4521 CXXMethodDecl *FieldMember = SMOR->getMethod();
4522 // A member of a union must have a trivial corresponding
4523 // constructor.
4524 if (!FieldMember->isTrivial())
4525 return true;
4526
4527 if (IsConstructor) {
4528 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4529 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4530 PDiag()) != AR_accessible)
4531 return true;
4532 }
4533 }
4534 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004535 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004536
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004537 // At least one member in each anonymous union must be non-const
4538 if (CSM == CXXDefaultConstructor && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004539 return true;
4540
4541 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004542 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004543 continue;
4544 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004545
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004546 // Unless we're doing assignment, the field's destructor must be
4547 // accessible and not deleted.
4548 if (!IsAssignment) {
4549 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4550 if (FieldDtor->isDeleted())
4551 return true;
4552 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4553 AR_accessible)
4554 return true;
4555 }
4556
Alexis Huntd6da8762011-10-10 06:18:57 +00004557 // Check that the corresponding member of the field is accessible,
4558 // unique, and non-deleted. We don't do this if it has an explicit
4559 // initialization when default-constructing.
4560 if (CSM != CXXDestructor &&
4561 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4562 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004563 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004564 false);
4565 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004566 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004567
4568 CXXMethodDecl *FieldMember = SMOR->getMethod();
4569 if (IsConstructor) {
4570 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4571 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4572 PDiag()) != AR_accessible)
4573 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004574
4575 // For a move operation, the corresponding operation must actually
4576 // be a move operation (and not a copy selected by overload
4577 // resolution) unless we are working on a trivially copyable class.
4578 if (IsMove && !FieldCtor->isMoveConstructor() &&
4579 !FieldRecord->isTriviallyCopyable())
4580 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004581 }
4582
4583 // We need the corresponding member of a union to be trivial so that
4584 // we can safely copy them all simultaneously.
4585 // FIXME: Note that performing the check here (where we rely on the lack
4586 // of an in-class initializer) is technically ill-formed. However, this
4587 // seems most obviously to be a bug in the standard.
4588 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004589 return true;
4590 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004591 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4592 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4593 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004594 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004595 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004596 }
4597
Alexis Huntd6da8762011-10-10 06:18:57 +00004598 // We can't have all const members in a union when default-constructing,
4599 // or else they're all nonsensical garbage values that can't be changed.
4600 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004601 return true;
4602
4603 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004604}
4605
Alexis Huntb2f27802011-05-14 05:23:24 +00004606bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4607 CXXRecordDecl *RD = MD->getParent();
4608 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004609 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004610 return false;
4611
Douglas Gregor1a22d282012-02-12 17:34:23 +00004612 // C++11 [expr.lambda.prim]p19:
4613 // The closure type associated with a lambda-expression has a
4614 // [...] deleted copy assignment operator.
4615 if (RD->isLambda())
4616 return true;
4617
Alexis Hunte77a28f2011-05-18 03:41:58 +00004618 SourceLocation Loc = MD->getLocation();
4619
Alexis Huntb2f27802011-05-14 05:23:24 +00004620 // Do access control from the constructor
4621 ContextRAII MethodContext(*this, MD);
4622
4623 bool Union = RD->isUnion();
4624
Alexis Hunt491ec602011-06-21 23:42:56 +00004625 unsigned ArgQuals =
4626 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4627 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004628
4629 // We do this because we should never actually use an anonymous
4630 // union's constructor.
4631 if (Union && RD->isAnonymousStructOrUnion())
4632 return false;
4633
Alexis Huntb2f27802011-05-14 05:23:24 +00004634 // FIXME: We should put some diagnostic logic right into this function.
4635
Sebastian Redl22653ba2011-08-30 19:58:05 +00004636 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004637 // A defaulted [copy] assignment operator for class X is defined as deleted
4638 // if X has:
4639
4640 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4641 BE = RD->bases_end();
4642 BI != BE; ++BI) {
4643 // We'll handle this one later
4644 if (BI->isVirtual())
4645 continue;
4646
4647 QualType BaseType = BI->getType();
4648 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4649 assert(BaseDecl && "base isn't a CXXRecordDecl");
4650
4651 // -- a [direct base class] B that cannot be [copied] because overload
4652 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004653 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004654 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004655 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4656 0);
4657 if (!CopyOper || CopyOper->isDeleted())
4658 return true;
4659 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004660 return true;
4661 }
4662
4663 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4664 BE = RD->vbases_end();
4665 BI != BE; ++BI) {
4666 QualType BaseType = BI->getType();
4667 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4668 assert(BaseDecl && "base isn't a CXXRecordDecl");
4669
Alexis Huntb2f27802011-05-14 05:23:24 +00004670 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004671 // resolution, as applied to B's [copy] assignment operator, results in
4672 // an ambiguity or a function that is deleted or inaccessible from the
4673 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004674 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4675 0);
4676 if (!CopyOper || CopyOper->isDeleted())
4677 return true;
4678 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004679 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004680 }
4681
4682 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4683 FE = RD->field_end();
4684 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004685 if (FI->isUnnamedBitfield())
4686 continue;
4687
Alexis Huntb2f27802011-05-14 05:23:24 +00004688 QualType FieldType = Context.getBaseElementType(FI->getType());
4689
4690 // -- a non-static data member of reference type
4691 if (FieldType->isReferenceType())
4692 return true;
4693
4694 // -- a non-static data member of const non-class type (or array thereof)
4695 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4696 return true;
4697
4698 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4699
4700 if (FieldRecord) {
4701 // This is an anonymous union
4702 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4703 // Anonymous unions inside unions do not variant members create
4704 if (!Union) {
4705 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4706 UE = FieldRecord->field_end();
4707 UI != UE; ++UI) {
4708 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4709 CXXRecordDecl *UnionFieldRecord =
4710 UnionFieldType->getAsCXXRecordDecl();
4711
4712 // -- a variant member with a non-trivial [copy] assignment operator
4713 // and X is a union-like class
4714 if (UnionFieldRecord &&
4715 !UnionFieldRecord->hasTrivialCopyAssignment())
4716 return true;
4717 }
4718 }
4719
4720 // Don't try to initalize an anonymous union
4721 continue;
4722 // -- a variant member with a non-trivial [copy] assignment operator
4723 // and X is a union-like class
4724 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4725 return true;
4726 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004727
Alexis Hunt491ec602011-06-21 23:42:56 +00004728 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4729 false, 0);
4730 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004731 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004732 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004733 return true;
4734 }
4735 }
4736
4737 return false;
4738}
4739
Sebastian Redl22653ba2011-08-30 19:58:05 +00004740bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4741 CXXRecordDecl *RD = MD->getParent();
4742 assert(!RD->isDependentType() && "do deletion after instantiation");
4743 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4744 return false;
4745
4746 SourceLocation Loc = MD->getLocation();
4747
4748 // Do access control from the constructor
4749 ContextRAII MethodContext(*this, MD);
4750
4751 bool Union = RD->isUnion();
4752
4753 // We do this because we should never actually use an anonymous
4754 // union's constructor.
4755 if (Union && RD->isAnonymousStructOrUnion())
4756 return false;
4757
4758 // C++0x [class.copy]/20
4759 // A defaulted [move] assignment operator for class X is defined as deleted
4760 // if X has:
4761
4762 // -- for the move constructor, [...] any direct or indirect virtual base
4763 // class.
4764 if (RD->getNumVBases() != 0)
4765 return true;
4766
4767 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4768 BE = RD->bases_end();
4769 BI != BE; ++BI) {
4770
4771 QualType BaseType = BI->getType();
4772 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4773 assert(BaseDecl && "base isn't a CXXRecordDecl");
4774
4775 // -- a [direct base class] B that cannot be [moved] because overload
4776 // resolution, as applied to B's [move] assignment operator, results in
4777 // an ambiguity or a function that is deleted or inaccessible from the
4778 // assignment operator
4779 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4780 if (!MoveOper || MoveOper->isDeleted())
4781 return true;
4782 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4783 return true;
4784
4785 // -- for the move assignment operator, a [direct base class] with a type
4786 // that does not have a move assignment operator and is not trivially
4787 // copyable.
4788 if (!MoveOper->isMoveAssignmentOperator() &&
4789 !BaseDecl->isTriviallyCopyable())
4790 return true;
4791 }
4792
4793 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4794 FE = RD->field_end();
4795 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004796 if (FI->isUnnamedBitfield())
4797 continue;
4798
Sebastian Redl22653ba2011-08-30 19:58:05 +00004799 QualType FieldType = Context.getBaseElementType(FI->getType());
4800
4801 // -- a non-static data member of reference type
4802 if (FieldType->isReferenceType())
4803 return true;
4804
4805 // -- a non-static data member of const non-class type (or array thereof)
4806 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4807 return true;
4808
4809 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4810
4811 if (FieldRecord) {
4812 // This is an anonymous union
4813 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4814 // Anonymous unions inside unions do not variant members create
4815 if (!Union) {
4816 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4817 UE = FieldRecord->field_end();
4818 UI != UE; ++UI) {
4819 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4820 CXXRecordDecl *UnionFieldRecord =
4821 UnionFieldType->getAsCXXRecordDecl();
4822
4823 // -- a variant member with a non-trivial [move] assignment operator
4824 // and X is a union-like class
4825 if (UnionFieldRecord &&
4826 !UnionFieldRecord->hasTrivialMoveAssignment())
4827 return true;
4828 }
4829 }
4830
4831 // Don't try to initalize an anonymous union
4832 continue;
4833 // -- a variant member with a non-trivial [move] assignment operator
4834 // and X is a union-like class
4835 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4836 return true;
4837 }
4838
4839 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4840 if (!MoveOper || MoveOper->isDeleted())
4841 return true;
4842 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4843 return true;
4844
4845 // -- for the move assignment operator, a [non-static data member] with a
4846 // type that does not have a move assignment operator and is not
4847 // trivially copyable.
4848 if (!MoveOper->isMoveAssignmentOperator() &&
4849 !FieldRecord->isTriviallyCopyable())
4850 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004851 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004852 }
4853
4854 return false;
4855}
4856
Alexis Huntf91729462011-05-12 22:46:25 +00004857bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4858 CXXRecordDecl *RD = DD->getParent();
4859 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004860 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004861 return false;
4862
Alexis Hunte77a28f2011-05-18 03:41:58 +00004863 SourceLocation Loc = DD->getLocation();
4864
Alexis Huntf91729462011-05-12 22:46:25 +00004865 // Do access control from the destructor
4866 ContextRAII CtorContext(*this, DD);
4867
4868 bool Union = RD->isUnion();
4869
Alexis Hunt913820d2011-05-13 06:10:58 +00004870 // We do this because we should never actually use an anonymous
4871 // union's destructor.
4872 if (Union && RD->isAnonymousStructOrUnion())
4873 return false;
4874
Alexis Huntf91729462011-05-12 22:46:25 +00004875 // C++0x [class.dtor]p5
4876 // A defaulted destructor for a class X is defined as deleted if:
4877 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4878 BE = RD->bases_end();
4879 BI != BE; ++BI) {
4880 // We'll handle this one later
4881 if (BI->isVirtual())
4882 continue;
4883
4884 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4885 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4886 assert(BaseDtor && "base has no destructor");
4887
4888 // -- any direct or virtual base class has a deleted destructor or
4889 // a destructor that is inaccessible from the defaulted destructor
4890 if (BaseDtor->isDeleted())
4891 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004892 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004893 AR_accessible)
4894 return true;
4895 }
4896
4897 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4898 BE = RD->vbases_end();
4899 BI != BE; ++BI) {
4900 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4901 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4902 assert(BaseDtor && "base has no destructor");
4903
4904 // -- any direct or virtual base class has a deleted destructor or
4905 // a destructor that is inaccessible from the defaulted destructor
4906 if (BaseDtor->isDeleted())
4907 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004908 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004909 AR_accessible)
4910 return true;
4911 }
4912
4913 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4914 FE = RD->field_end();
4915 FI != FE; ++FI) {
4916 QualType FieldType = Context.getBaseElementType(FI->getType());
4917 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4918 if (FieldRecord) {
4919 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4920 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4921 UE = FieldRecord->field_end();
4922 UI != UE; ++UI) {
4923 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4924 CXXRecordDecl *UnionFieldRecord =
4925 UnionFieldType->getAsCXXRecordDecl();
4926
4927 // -- X is a union-like class that has a variant member with a non-
4928 // trivial destructor.
4929 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4930 return true;
4931 }
4932 // Technically we are supposed to do this next check unconditionally.
4933 // But that makes absolutely no sense.
4934 } else {
4935 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4936
4937 // -- any of the non-static data members has class type M (or array
4938 // thereof) and M has a deleted destructor or a destructor that is
4939 // inaccessible from the defaulted destructor
4940 if (FieldDtor->isDeleted())
4941 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004942 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004943 AR_accessible)
4944 return true;
4945
4946 // -- X is a union-like class that has a variant member with a non-
4947 // trivial destructor.
4948 if (Union && !FieldDtor->isTrivial())
4949 return true;
4950 }
4951 }
4952 }
4953
4954 if (DD->isVirtual()) {
4955 FunctionDecl *OperatorDelete = 0;
4956 DeclarationName Name =
4957 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004958 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004959 false))
4960 return true;
4961 }
4962
4963
4964 return false;
4965}
4966
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004967/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004968namespace {
4969 struct FindHiddenVirtualMethodData {
4970 Sema *S;
4971 CXXMethodDecl *Method;
4972 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004973 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004974 };
4975}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004976
4977/// \brief Member lookup function that determines whether a given C++
4978/// method overloads virtual methods in a base class without overriding any,
4979/// to be used with CXXRecordDecl::lookupInBases().
4980static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4981 CXXBasePath &Path,
4982 void *UserData) {
4983 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4984
4985 FindHiddenVirtualMethodData &Data
4986 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4987
4988 DeclarationName Name = Data.Method->getDeclName();
4989 assert(Name.getNameKind() == DeclarationName::Identifier);
4990
4991 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004992 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004993 for (Path.Decls = BaseRecord->lookup(Name);
4994 Path.Decls.first != Path.Decls.second;
4995 ++Path.Decls.first) {
4996 NamedDecl *D = *Path.Decls.first;
4997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004998 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004999 foundSameNameMethod = true;
5000 // Interested only in hidden virtual methods.
5001 if (!MD->isVirtual())
5002 continue;
5003 // If the method we are checking overrides a method from its base
5004 // don't warn about the other overloaded methods.
5005 if (!Data.S->IsOverload(Data.Method, MD, false))
5006 return true;
5007 // Collect the overload only if its hidden.
5008 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5009 overloadedMethods.push_back(MD);
5010 }
5011 }
5012
5013 if (foundSameNameMethod)
5014 Data.OverloadedMethods.append(overloadedMethods.begin(),
5015 overloadedMethods.end());
5016 return foundSameNameMethod;
5017}
5018
5019/// \brief See if a method overloads virtual methods in a base class without
5020/// overriding any.
5021void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5022 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00005023 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005024 return;
5025 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5026 return;
5027
5028 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5029 /*bool RecordPaths=*/false,
5030 /*bool DetectVirtual=*/false);
5031 FindHiddenVirtualMethodData Data;
5032 Data.Method = MD;
5033 Data.S = this;
5034
5035 // Keep the base methods that were overriden or introduced in the subclass
5036 // by 'using' in a set. A base method not in this set is hidden.
5037 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5038 res.first != res.second; ++res.first) {
5039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5040 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5041 E = MD->end_overridden_methods();
5042 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005043 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005044 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005046 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005047 }
5048
5049 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5050 !Data.OverloadedMethods.empty()) {
5051 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5052 << MD << (Data.OverloadedMethods.size() > 1);
5053
5054 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5055 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5056 Diag(overloadedMD->getLocation(),
5057 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5058 }
5059 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005060}
5061
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005062void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005063 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005064 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005065 SourceLocation RBrac,
5066 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005067 if (!TagDecl)
5068 return;
Mike Stump11289f42009-09-09 15:08:12 +00005069
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005070 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005071
David Blaikie751c5582011-09-22 02:58:26 +00005072 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005073 // strict aliasing violation!
5074 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005075 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005076
Douglas Gregor0be31a22010-07-02 17:43:08 +00005077 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005078 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005079}
5080
Douglas Gregor05379422008-11-03 17:51:48 +00005081/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5082/// special functions, such as the default constructor, copy
5083/// constructor, or destructor, to the given C++ class (C++
5084/// [special]p1). This routine can only be executed just before the
5085/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005086void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005087 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005088 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005089
Douglas Gregor54be3392010-07-01 17:57:27 +00005090 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005091 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005092
Richard Smith966c1fb2011-12-24 21:56:24 +00005093 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5094 ++ASTContext::NumImplicitMoveConstructors;
5095
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005096 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5097 ++ASTContext::NumImplicitCopyAssignmentOperators;
5098
5099 // If we have a dynamic class, then the copy assignment operator may be
5100 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5101 // it shows up in the right place in the vtable and that we diagnose
5102 // problems with the implicit exception specification.
5103 if (ClassDecl->isDynamicClass())
5104 DeclareImplicitCopyAssignment(ClassDecl);
5105 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005106
Richard Smith966c1fb2011-12-24 21:56:24 +00005107 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5108 ++ASTContext::NumImplicitMoveAssignmentOperators;
5109
5110 // Likewise for the move assignment operator.
5111 if (ClassDecl->isDynamicClass())
5112 DeclareImplicitMoveAssignment(ClassDecl);
5113 }
5114
Douglas Gregor7454c562010-07-02 20:37:36 +00005115 if (!ClassDecl->hasUserDeclaredDestructor()) {
5116 ++ASTContext::NumImplicitDestructors;
5117
5118 // If we have a dynamic class, then the destructor may be virtual, so we
5119 // have to declare the destructor immediately. This ensures that, e.g., it
5120 // shows up in the right place in the vtable and that we diagnose problems
5121 // with the implicit exception specification.
5122 if (ClassDecl->isDynamicClass())
5123 DeclareImplicitDestructor(ClassDecl);
5124 }
Douglas Gregor05379422008-11-03 17:51:48 +00005125}
5126
Francois Pichet1c229c02011-04-22 22:18:13 +00005127void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5128 if (!D)
5129 return;
5130
5131 int NumParamList = D->getNumTemplateParameterLists();
5132 for (int i = 0; i < NumParamList; i++) {
5133 TemplateParameterList* Params = D->getTemplateParameterList(i);
5134 for (TemplateParameterList::iterator Param = Params->begin(),
5135 ParamEnd = Params->end();
5136 Param != ParamEnd; ++Param) {
5137 NamedDecl *Named = cast<NamedDecl>(*Param);
5138 if (Named->getDeclName()) {
5139 S->AddDecl(Named);
5140 IdResolver.AddDecl(Named);
5141 }
5142 }
5143 }
5144}
5145
John McCall48871652010-08-21 09:40:31 +00005146void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005147 if (!D)
5148 return;
5149
5150 TemplateParameterList *Params = 0;
5151 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5152 Params = Template->getTemplateParameters();
5153 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5154 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5155 Params = PartialSpec->getTemplateParameters();
5156 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005157 return;
5158
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005159 for (TemplateParameterList::iterator Param = Params->begin(),
5160 ParamEnd = Params->end();
5161 Param != ParamEnd; ++Param) {
5162 NamedDecl *Named = cast<NamedDecl>(*Param);
5163 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005164 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005165 IdResolver.AddDecl(Named);
5166 }
5167 }
5168}
5169
John McCall48871652010-08-21 09:40:31 +00005170void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005171 if (!RecordD) return;
5172 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005173 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005174 PushDeclContext(S, Record);
5175}
5176
John McCall48871652010-08-21 09:40:31 +00005177void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005178 if (!RecordD) return;
5179 PopDeclContext();
5180}
5181
Douglas Gregor4d87df52008-12-16 21:30:33 +00005182/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5183/// parsing a top-level (non-nested) C++ class, and we are now
5184/// parsing those parts of the given Method declaration that could
5185/// not be parsed earlier (C++ [class.mem]p2), such as default
5186/// arguments. This action should enter the scope of the given
5187/// Method declaration as if we had just parsed the qualified method
5188/// name. However, it should not bring the parameters into scope;
5189/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005190void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005191}
5192
5193/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5194/// C++ method declaration. We're (re-)introducing the given
5195/// function parameter into scope for use in parsing later parts of
5196/// the method declaration. For example, we could see an
5197/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005198void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005199 if (!ParamD)
5200 return;
Mike Stump11289f42009-09-09 15:08:12 +00005201
John McCall48871652010-08-21 09:40:31 +00005202 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005203
5204 // If this parameter has an unparsed default argument, clear it out
5205 // to make way for the parsed default argument.
5206 if (Param->hasUnparsedDefaultArg())
5207 Param->setDefaultArg(0);
5208
John McCall48871652010-08-21 09:40:31 +00005209 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005210 if (Param->getDeclName())
5211 IdResolver.AddDecl(Param);
5212}
5213
5214/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5215/// processing the delayed method declaration for Method. The method
5216/// declaration is now considered finished. There may be a separate
5217/// ActOnStartOfFunctionDef action later (not necessarily
5218/// immediately!) for this method, if it was also defined inside the
5219/// class body.
John McCall48871652010-08-21 09:40:31 +00005220void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005221 if (!MethodD)
5222 return;
Mike Stump11289f42009-09-09 15:08:12 +00005223
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005224 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005225
John McCall48871652010-08-21 09:40:31 +00005226 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005227
5228 // Now that we have our default arguments, check the constructor
5229 // again. It could produce additional diagnostics or affect whether
5230 // the class has implicitly-declared destructors, among other
5231 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005232 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5233 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005234
5235 // Check the default arguments, which we may have added.
5236 if (!Method->isInvalidDecl())
5237 CheckCXXDefaultArguments(Method);
5238}
5239
Douglas Gregor831c93f2008-11-05 20:51:48 +00005240/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005241/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005242/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005243/// emit diagnostics and set the invalid bit to true. In any case, the type
5244/// will be updated to reflect a well-formed type for the constructor and
5245/// returned.
5246QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005247 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005248 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005249
5250 // C++ [class.ctor]p3:
5251 // A constructor shall not be virtual (10.3) or static (9.4). A
5252 // constructor can be invoked for a const, volatile or const
5253 // volatile object. A constructor shall not be declared const,
5254 // volatile, or const volatile (9.3.2).
5255 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005256 if (!D.isInvalidType())
5257 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5258 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5259 << SourceRange(D.getIdentifierLoc());
5260 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005261 }
John McCall8e7d6562010-08-26 03:08:43 +00005262 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005263 if (!D.isInvalidType())
5264 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5265 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5266 << SourceRange(D.getIdentifierLoc());
5267 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005268 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005269 }
Mike Stump11289f42009-09-09 15:08:12 +00005270
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005271 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005272 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005273 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005274 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5275 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005276 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005277 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5278 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005279 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005280 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5281 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005282 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005283 }
Mike Stump11289f42009-09-09 15:08:12 +00005284
Douglas Gregordb9d6642011-01-26 05:01:58 +00005285 // C++0x [class.ctor]p4:
5286 // A constructor shall not be declared with a ref-qualifier.
5287 if (FTI.hasRefQualifier()) {
5288 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5289 << FTI.RefQualifierIsLValueRef
5290 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5291 D.setInvalidType();
5292 }
5293
Douglas Gregor831c93f2008-11-05 20:51:48 +00005294 // Rebuild the function type "R" without any type qualifiers (in
5295 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005296 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005297 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005298 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5299 return R;
5300
5301 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5302 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005303 EPI.RefQualifier = RQ_None;
5304
Chris Lattner38378bf2009-04-25 08:28:21 +00005305 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005306 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005307}
5308
Douglas Gregor4d87df52008-12-16 21:30:33 +00005309/// CheckConstructor - Checks a fully-formed constructor for
5310/// well-formedness, issuing any diagnostics required. Returns true if
5311/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005312void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005313 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005314 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5315 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005316 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005317
5318 // C++ [class.copy]p3:
5319 // A declaration of a constructor for a class X is ill-formed if
5320 // its first parameter is of type (optionally cv-qualified) X and
5321 // either there are no other parameters or else all other
5322 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005323 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005324 ((Constructor->getNumParams() == 1) ||
5325 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005326 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5327 Constructor->getTemplateSpecializationKind()
5328 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005329 QualType ParamType = Constructor->getParamDecl(0)->getType();
5330 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5331 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005332 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005333 const char *ConstRef
5334 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5335 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005336 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005337 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005338
5339 // FIXME: Rather that making the constructor invalid, we should endeavor
5340 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005341 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005342 }
5343 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005344}
5345
John McCalldeb646e2010-08-04 01:04:25 +00005346/// CheckDestructor - Checks a fully-formed destructor definition for
5347/// well-formedness, issuing any diagnostics required. Returns true
5348/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005349bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005350 CXXRecordDecl *RD = Destructor->getParent();
5351
5352 if (Destructor->isVirtual()) {
5353 SourceLocation Loc;
5354
5355 if (!Destructor->isImplicit())
5356 Loc = Destructor->getLocation();
5357 else
5358 Loc = RD->getLocation();
5359
5360 // If we have a virtual destructor, look up the deallocation function
5361 FunctionDecl *OperatorDelete = 0;
5362 DeclarationName Name =
5363 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005364 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005365 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005366
Eli Friedmanfa0df832012-02-02 03:46:19 +00005367 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005368
5369 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005370 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005371
5372 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005373}
5374
Mike Stump11289f42009-09-09 15:08:12 +00005375static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005376FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5377 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5378 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005379 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005380}
5381
Douglas Gregor831c93f2008-11-05 20:51:48 +00005382/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5383/// the well-formednes of the destructor declarator @p D with type @p
5384/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005385/// emit diagnostics and set the declarator to invalid. Even if this happens,
5386/// will be updated to reflect a well-formed type for the destructor and
5387/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005388QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005389 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005390 // C++ [class.dtor]p1:
5391 // [...] A typedef-name that names a class is a class-name
5392 // (7.1.3); however, a typedef-name that names a class shall not
5393 // be used as the identifier in the declarator for a destructor
5394 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005395 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005396 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005397 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005398 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005399 else if (const TemplateSpecializationType *TST =
5400 DeclaratorType->getAs<TemplateSpecializationType>())
5401 if (TST->isTypeAlias())
5402 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5403 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005404
5405 // C++ [class.dtor]p2:
5406 // A destructor is used to destroy objects of its class type. A
5407 // destructor takes no parameters, and no return type can be
5408 // specified for it (not even void). The address of a destructor
5409 // shall not be taken. A destructor shall not be static. A
5410 // destructor can be invoked for a const, volatile or const
5411 // volatile object. A destructor shall not be declared const,
5412 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005413 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005414 if (!D.isInvalidType())
5415 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5416 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005417 << SourceRange(D.getIdentifierLoc())
5418 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5419
John McCall8e7d6562010-08-26 03:08:43 +00005420 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005421 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005422 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005423 // Destructors don't have return types, but the parser will
5424 // happily parse something like:
5425 //
5426 // class X {
5427 // float ~X();
5428 // };
5429 //
5430 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005431 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5432 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5433 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005434 }
Mike Stump11289f42009-09-09 15:08:12 +00005435
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005436 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005437 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005438 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005439 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5440 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005441 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005442 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5443 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005444 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5446 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005447 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005448 }
5449
Douglas Gregordb9d6642011-01-26 05:01:58 +00005450 // C++0x [class.dtor]p2:
5451 // A destructor shall not be declared with a ref-qualifier.
5452 if (FTI.hasRefQualifier()) {
5453 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5454 << FTI.RefQualifierIsLValueRef
5455 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5456 D.setInvalidType();
5457 }
5458
Douglas Gregor831c93f2008-11-05 20:51:48 +00005459 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005460 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005461 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5462
5463 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005464 FTI.freeArgs();
5465 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005466 }
5467
Mike Stump11289f42009-09-09 15:08:12 +00005468 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005469 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005470 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005471 D.setInvalidType();
5472 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005473
5474 // Rebuild the function type "R" without any type qualifiers or
5475 // parameters (in case any of the errors above fired) and with
5476 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005477 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005478 if (!D.isInvalidType())
5479 return R;
5480
Douglas Gregor95755162010-07-01 05:10:53 +00005481 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005482 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5483 EPI.Variadic = false;
5484 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005485 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005486 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005487}
5488
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005489/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5490/// well-formednes of the conversion function declarator @p D with
5491/// type @p R. If there are any errors in the declarator, this routine
5492/// will emit diagnostics and return true. Otherwise, it will return
5493/// false. Either way, the type @p R will be updated to reflect a
5494/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005495void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005496 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005497 // C++ [class.conv.fct]p1:
5498 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005499 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005500 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005501 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005502 if (!D.isInvalidType())
5503 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5504 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5505 << SourceRange(D.getIdentifierLoc());
5506 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005507 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005508 }
John McCall212fa2e2010-04-13 00:04:31 +00005509
5510 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5511
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005513 // Conversion functions don't have return types, but the parser will
5514 // happily parse something like:
5515 //
5516 // class X {
5517 // float operator bool();
5518 // };
5519 //
5520 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5523 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005524 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005525 }
5526
John McCall212fa2e2010-04-13 00:04:31 +00005527 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5528
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005529 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005530 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005531 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5532
5533 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005534 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005535 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005536 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005538 D.setInvalidType();
5539 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005540
John McCall212fa2e2010-04-13 00:04:31 +00005541 // Diagnose "&operator bool()" and other such nonsense. This
5542 // is actually a gcc extension which we don't support.
5543 if (Proto->getResultType() != ConvType) {
5544 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5545 << Proto->getResultType();
5546 D.setInvalidType();
5547 ConvType = Proto->getResultType();
5548 }
5549
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005550 // C++ [class.conv.fct]p4:
5551 // The conversion-type-id shall not represent a function type nor
5552 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005553 if (ConvType->isArrayType()) {
5554 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5555 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005556 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005557 } else if (ConvType->isFunctionType()) {
5558 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5559 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005560 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005561 }
5562
5563 // Rebuild the function type "R" without any parameters (in case any
5564 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005565 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005566 if (D.isInvalidType())
5567 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005568
Douglas Gregor5fb53972009-01-14 15:45:31 +00005569 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005570 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00005571 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith0bf8a4922011-10-18 20:49:44 +00005572 getLangOptions().CPlusPlus0x ?
5573 diag::warn_cxx98_compat_explicit_conversion_functions :
5574 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00005575 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005576}
5577
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005578/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5579/// the declaration of the given C++ conversion function. This routine
5580/// is responsible for recording the conversion function in the C++
5581/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005582Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005583 assert(Conversion && "Expected to receive a conversion function declaration");
5584
Douglas Gregor4287b372008-12-12 08:25:50 +00005585 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005586
5587 // Make sure we aren't redeclaring the conversion function.
5588 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005589
5590 // C++ [class.conv.fct]p1:
5591 // [...] A conversion function is never used to convert a
5592 // (possibly cv-qualified) object to the (possibly cv-qualified)
5593 // same object type (or a reference to it), to a (possibly
5594 // cv-qualified) base class of that type (or a reference to it),
5595 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005596 // FIXME: Suppress this warning if the conversion function ends up being a
5597 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005598 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005599 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005600 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005601 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005602 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5603 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005604 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005605 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005606 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5607 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005608 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005609 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005610 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005611 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005612 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005613 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005614 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005615 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005616 }
5617
Douglas Gregor457104e2010-09-29 04:25:11 +00005618 if (FunctionTemplateDecl *ConversionTemplate
5619 = Conversion->getDescribedFunctionTemplate())
5620 return ConversionTemplate;
5621
John McCall48871652010-08-21 09:40:31 +00005622 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005623}
5624
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005625//===----------------------------------------------------------------------===//
5626// Namespace Handling
5627//===----------------------------------------------------------------------===//
5628
John McCallb1be5232010-08-26 09:15:37 +00005629
5630
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005631/// ActOnStartNamespaceDef - This is called at the start of a namespace
5632/// definition.
John McCall48871652010-08-21 09:40:31 +00005633Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005634 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005635 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005636 SourceLocation IdentLoc,
5637 IdentifierInfo *II,
5638 SourceLocation LBrace,
5639 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005640 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5641 // For anonymous namespace, take the location of the left brace.
5642 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00005643 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00005644 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00005645 bool IsStd = false;
5646 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005647 Scope *DeclRegionScope = NamespcScope->getParent();
5648
Douglas Gregore57e7522012-01-07 09:11:48 +00005649 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005650 if (II) {
5651 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005652 // The identifier in an original-namespace-definition shall not
5653 // have been previously defined in the declarative region in
5654 // which the original-namespace-definition appears. The
5655 // identifier in an original-namespace-definition is the name of
5656 // the namespace. Subsequently in that declarative region, it is
5657 // treated as an original-namespace-name.
5658 //
5659 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005660 // look through using directives, just look for any ordinary names.
5661
5662 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00005663 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5664 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005665 NamedDecl *PrevDecl = 0;
5666 for (DeclContext::lookup_result R
Douglas Gregore57e7522012-01-07 09:11:48 +00005667 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005668 R.first != R.second; ++R.first) {
5669 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5670 PrevDecl = *R.first;
5671 break;
5672 }
5673 }
5674
Douglas Gregore57e7522012-01-07 09:11:48 +00005675 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5676
5677 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00005678 // This is an extended namespace definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005679 if (IsInline != PrevNS->isInline()) {
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005680 // inline-ness must match
Douglas Gregore57e7522012-01-07 09:11:48 +00005681 if (PrevNS->isInline()) {
Douglas Gregora9121972011-05-20 15:48:31 +00005682 // The user probably just forgot the 'inline', so suggest that it
5683 // be added back.
Douglas Gregore57e7522012-01-07 09:11:48 +00005684 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregora9121972011-05-20 15:48:31 +00005685 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5686 } else {
Douglas Gregore57e7522012-01-07 09:11:48 +00005687 Diag(Loc, diag::err_inline_namespace_mismatch)
5688 << IsInline;
Douglas Gregora9121972011-05-20 15:48:31 +00005689 }
Douglas Gregore57e7522012-01-07 09:11:48 +00005690 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5691
5692 IsInline = PrevNS->isInline();
5693 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005694 } else if (PrevDecl) {
5695 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005696 Diag(Loc, diag::err_redefinition_different_kind)
5697 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00005698 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005699 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00005700 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00005701 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005702 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005703 // This is the first "real" definition of the namespace "std", so update
5704 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005705 PrevNS = getStdNamespace();
5706 IsStd = true;
5707 AddToKnown = !IsInline;
5708 } else {
5709 // We've seen this namespace for the first time.
5710 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00005711 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005712 } else {
John McCall4fa53422009-10-01 00:25:31 +00005713 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00005714
5715 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00005716 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005717 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00005718 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005719 } else {
5720 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00005721 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005722 }
5723
Douglas Gregore57e7522012-01-07 09:11:48 +00005724 if (PrevNS && IsInline != PrevNS->isInline()) {
5725 // inline-ness must match
5726 Diag(Loc, diag::err_inline_namespace_mismatch)
5727 << IsInline;
5728 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005729
Douglas Gregore57e7522012-01-07 09:11:48 +00005730 // Recover by ignoring the new namespace's inline status.
5731 IsInline = PrevNS->isInline();
5732 }
5733 }
5734
5735 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5736 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005737 if (IsInvalid)
5738 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00005739
5740 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005741
Douglas Gregore57e7522012-01-07 09:11:48 +00005742 // FIXME: Should we be merging attributes?
5743 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005744 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00005745
5746 if (IsStd)
5747 StdNamespace = Namespc;
5748 if (AddToKnown)
5749 KnownNamespaces[Namespc] = false;
5750
5751 if (II) {
5752 PushOnScopeChains(Namespc, DeclRegionScope);
5753 } else {
5754 // Link the anonymous namespace into its parent.
5755 DeclContext *Parent = CurContext->getRedeclContext();
5756 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5757 TU->setAnonymousNamespace(Namespc);
5758 } else {
5759 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00005760 }
John McCall4fa53422009-10-01 00:25:31 +00005761
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005762 CurContext->addDecl(Namespc);
5763
John McCall4fa53422009-10-01 00:25:31 +00005764 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5765 // behaves as if it were replaced by
5766 // namespace unique { /* empty body */ }
5767 // using namespace unique;
5768 // namespace unique { namespace-body }
5769 // where all occurrences of 'unique' in a translation unit are
5770 // replaced by the same identifier and this identifier differs
5771 // from all other identifiers in the entire program.
5772
5773 // We just create the namespace with an empty name and then add an
5774 // implicit using declaration, just like the standard suggests.
5775 //
5776 // CodeGen enforces the "universally unique" aspect by giving all
5777 // declarations semantically contained within an anonymous
5778 // namespace internal linkage.
5779
Douglas Gregore57e7522012-01-07 09:11:48 +00005780 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00005781 UsingDirectiveDecl* UD
5782 = UsingDirectiveDecl::Create(Context, CurContext,
5783 /* 'using' */ LBrace,
5784 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005785 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005786 /* identifier */ SourceLocation(),
5787 Namespc,
5788 /* Ancestor */ CurContext);
5789 UD->setImplicit();
5790 CurContext->addDecl(UD);
5791 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005792 }
5793
5794 // Although we could have an invalid decl (i.e. the namespace name is a
5795 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005796 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5797 // for the namespace has the declarations that showed up in that particular
5798 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005799 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005800 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005801}
5802
Sebastian Redla6602e92009-11-23 15:34:23 +00005803/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5804/// is a namespace alias, returns the namespace it points to.
5805static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5806 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5807 return AD->getNamespace();
5808 return dyn_cast_or_null<NamespaceDecl>(D);
5809}
5810
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005811/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5812/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005813void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005814 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5815 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005816 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005817 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005818 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005819 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005820}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005821
John McCall28a0cf72010-08-25 07:42:41 +00005822CXXRecordDecl *Sema::getStdBadAlloc() const {
5823 return cast_or_null<CXXRecordDecl>(
5824 StdBadAlloc.get(Context.getExternalSource()));
5825}
5826
5827NamespaceDecl *Sema::getStdNamespace() const {
5828 return cast_or_null<NamespaceDecl>(
5829 StdNamespace.get(Context.getExternalSource()));
5830}
5831
Douglas Gregorcdf87022010-06-29 17:53:46 +00005832/// \brief Retrieve the special "std" namespace, which may require us to
5833/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005834NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005835 if (!StdNamespace) {
5836 // The "std" namespace has not yet been defined, so build one implicitly.
5837 StdNamespace = NamespaceDecl::Create(Context,
5838 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005839 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005840 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005841 &PP.getIdentifierTable().get("std"),
5842 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005843 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005844 }
5845
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005846 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005847}
5848
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005849bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5850 assert(getLangOptions().CPlusPlus &&
5851 "Looking for std::initializer_list outside of C++.");
5852
5853 // We're looking for implicit instantiations of
5854 // template <typename E> class std::initializer_list.
5855
5856 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5857 return false;
5858
Sebastian Redl43144e72012-01-17 22:49:58 +00005859 ClassTemplateDecl *Template = 0;
5860 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005861
Sebastian Redl43144e72012-01-17 22:49:58 +00005862 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005863
Sebastian Redl43144e72012-01-17 22:49:58 +00005864 ClassTemplateSpecializationDecl *Specialization =
5865 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5866 if (!Specialization)
5867 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005868
Sebastian Redl43144e72012-01-17 22:49:58 +00005869 Template = Specialization->getSpecializedTemplate();
5870 Arguments = Specialization->getTemplateArgs().data();
5871 } else if (const TemplateSpecializationType *TST =
5872 Ty->getAs<TemplateSpecializationType>()) {
5873 Template = dyn_cast_or_null<ClassTemplateDecl>(
5874 TST->getTemplateName().getAsTemplateDecl());
5875 Arguments = TST->getArgs();
5876 }
5877 if (!Template)
5878 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005879
5880 if (!StdInitializerList) {
5881 // Haven't recognized std::initializer_list yet, maybe this is it.
5882 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5883 if (TemplateClass->getIdentifier() !=
5884 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00005885 !getStdNamespace()->InEnclosingNamespaceSetOf(
5886 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005887 return false;
5888 // This is a template called std::initializer_list, but is it the right
5889 // template?
5890 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005891 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005892 return false;
5893 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5894 return false;
5895
5896 // It's the right template.
5897 StdInitializerList = Template;
5898 }
5899
5900 if (Template != StdInitializerList)
5901 return false;
5902
5903 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00005904 if (Element)
5905 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005906 return true;
5907}
5908
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005909static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5910 NamespaceDecl *Std = S.getStdNamespace();
5911 if (!Std) {
5912 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5913 return 0;
5914 }
5915
5916 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5917 Loc, Sema::LookupOrdinaryName);
5918 if (!S.LookupQualifiedName(Result, Std)) {
5919 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5920 return 0;
5921 }
5922 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5923 if (!Template) {
5924 Result.suppressDiagnostics();
5925 // We found something weird. Complain about the first thing we found.
5926 NamedDecl *Found = *Result.begin();
5927 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5928 return 0;
5929 }
5930
5931 // We found some template called std::initializer_list. Now verify that it's
5932 // correct.
5933 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005934 if (Params->getMinRequiredArguments() != 1 ||
5935 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005936 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5937 return 0;
5938 }
5939
5940 return Template;
5941}
5942
5943QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5944 if (!StdInitializerList) {
5945 StdInitializerList = LookupStdInitializerList(*this, Loc);
5946 if (!StdInitializerList)
5947 return QualType();
5948 }
5949
5950 TemplateArgumentListInfo Args(Loc, Loc);
5951 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5952 Context.getTrivialTypeSourceInfo(Element,
5953 Loc)));
5954 return Context.getCanonicalType(
5955 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5956}
5957
Sebastian Redlbe24ec22012-01-17 22:50:14 +00005958bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5959 // C++ [dcl.init.list]p2:
5960 // A constructor is an initializer-list constructor if its first parameter
5961 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5962 // std::initializer_list<E> for some type E, and either there are no other
5963 // parameters or else all other parameters have default arguments.
5964 if (Ctor->getNumParams() < 1 ||
5965 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5966 return false;
5967
5968 QualType ArgType = Ctor->getParamDecl(0)->getType();
5969 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5970 ArgType = RT->getPointeeType().getUnqualifiedType();
5971
5972 return isStdInitializerList(ArgType, 0);
5973}
5974
Douglas Gregora172e082011-03-26 22:25:30 +00005975/// \brief Determine whether a using statement is in a context where it will be
5976/// apply in all contexts.
5977static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5978 switch (CurContext->getDeclKind()) {
5979 case Decl::TranslationUnit:
5980 return true;
5981 case Decl::LinkageSpec:
5982 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5983 default:
5984 return false;
5985 }
5986}
5987
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005988namespace {
5989
5990// Callback to only accept typo corrections that are namespaces.
5991class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5992 public:
5993 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5994 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5995 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5996 }
5997 return false;
5998 }
5999};
6000
6001}
6002
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006003static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6004 CXXScopeSpec &SS,
6005 SourceLocation IdentLoc,
6006 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006007 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006008 R.clear();
6009 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006010 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006011 Validator)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006012 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
6013 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
6014 if (DeclContext *DC = S.computeDeclContext(SS, false))
6015 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6016 << Ident << DC << CorrectedQuotedStr << SS.getRange()
6017 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6018 else
6019 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6020 << Ident << CorrectedQuotedStr
6021 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006022
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006023 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6024 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006025
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006026 Ident = Corrected.getCorrectionAsIdentifierInfo();
6027 R.addDecl(Corrected.getCorrectionDecl());
6028 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006029 }
6030 return false;
6031}
6032
John McCall48871652010-08-21 09:40:31 +00006033Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006034 SourceLocation UsingLoc,
6035 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006036 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006037 SourceLocation IdentLoc,
6038 IdentifierInfo *NamespcName,
6039 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6041 assert(NamespcName && "Invalid NamespcName.");
6042 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006043
6044 // This can only happen along a recovery path.
6045 while (S->getFlags() & Scope::TemplateParamScope)
6046 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006047 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006048
Douglas Gregor889ceb72009-02-03 19:21:40 +00006049 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006050 NestedNameSpecifier *Qualifier = 0;
6051 if (SS.isSet())
6052 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6053
Douglas Gregor34074322009-01-14 22:20:51 +00006054 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006055 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6056 LookupParsedName(R, S, &SS);
6057 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006058 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006059
Douglas Gregorcdf87022010-06-29 17:53:46 +00006060 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006061 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006062 // Allow "using namespace std;" or "using namespace ::std;" even if
6063 // "std" hasn't been defined yet, for GCC compatibility.
6064 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6065 NamespcName->isStr("std")) {
6066 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006067 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006068 R.resolveKind();
6069 }
6070 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006071 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006072 }
6073
John McCall9f3059a2009-10-09 21:13:30 +00006074 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006075 NamedDecl *Named = R.getFoundDecl();
6076 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6077 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006078 // C++ [namespace.udir]p1:
6079 // A using-directive specifies that the names in the nominated
6080 // namespace can be used in the scope in which the
6081 // using-directive appears after the using-directive. During
6082 // unqualified name lookup (3.4.1), the names appear as if they
6083 // were declared in the nearest enclosing namespace which
6084 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006085 // namespace. [Note: in this context, "contains" means "contains
6086 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006087
6088 // Find enclosing context containing both using-directive and
6089 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006090 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006091 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6092 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6093 CommonAncestor = CommonAncestor->getParent();
6094
Sebastian Redla6602e92009-11-23 15:34:23 +00006095 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006096 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006097 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006098
Douglas Gregora172e082011-03-26 22:25:30 +00006099 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00006100 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006101 Diag(IdentLoc, diag::warn_using_directive_in_header);
6102 }
6103
Douglas Gregor889ceb72009-02-03 19:21:40 +00006104 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006105 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006106 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006107 }
6108
Douglas Gregor889ceb72009-02-03 19:21:40 +00006109 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00006110 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006111}
6112
6113void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6114 // If scope has associated entity, then using directive is at namespace
6115 // or translation unit scope. We add UsingDirectiveDecls, into
6116 // it's lookup structure.
6117 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006118 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006119 else
6120 // Otherwise it is block-sope. using-directives will affect lookup
6121 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00006122 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006123}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006124
Douglas Gregorfec52632009-06-20 00:51:54 +00006125
John McCall48871652010-08-21 09:40:31 +00006126Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006127 AccessSpecifier AS,
6128 bool HasUsingKeyword,
6129 SourceLocation UsingLoc,
6130 CXXScopeSpec &SS,
6131 UnqualifiedId &Name,
6132 AttributeList *AttrList,
6133 bool IsTypeName,
6134 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006135 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006136
Douglas Gregor220f4272009-11-04 16:30:06 +00006137 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006138 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006139 case UnqualifiedId::IK_Identifier:
6140 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006141 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006142 case UnqualifiedId::IK_ConversionFunctionId:
6143 break;
6144
6145 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006146 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00006147 // C++0x inherited constructors.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006148 Diag(Name.getSourceRange().getBegin(),
6149 getLangOptions().CPlusPlus0x ?
6150 diag::warn_cxx98_compat_using_decl_constructor :
6151 diag::err_using_decl_constructor)
6152 << SS.getRange();
6153
John McCall3969e302009-12-08 07:46:18 +00006154 if (getLangOptions().CPlusPlus0x) break;
6155
John McCall48871652010-08-21 09:40:31 +00006156 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006157
6158 case UnqualifiedId::IK_DestructorName:
6159 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6160 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006161 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006162
6163 case UnqualifiedId::IK_TemplateId:
6164 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6165 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006166 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006167 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006168
6169 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6170 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006171 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006172 return 0;
John McCall3969e302009-12-08 07:46:18 +00006173
John McCalla0097262009-12-11 02:10:03 +00006174 // Warn about using declarations.
6175 // TODO: store that the declaration was written without 'using' and
6176 // talk about access decls instead of using decls in the
6177 // diagnostics.
6178 if (!HasUsingKeyword) {
6179 UsingLoc = Name.getSourceRange().getBegin();
6180
6181 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006182 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006183 }
6184
Douglas Gregorc4356532010-12-16 00:46:58 +00006185 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6186 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6187 return 0;
6188
John McCall3f746822009-11-17 05:59:44 +00006189 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006190 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006191 /* IsInstantiation */ false,
6192 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006193 if (UD)
6194 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006195
John McCall48871652010-08-21 09:40:31 +00006196 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006197}
6198
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006199/// \brief Determine whether a using declaration considers the given
6200/// declarations as "equivalent", e.g., if they are redeclarations of
6201/// the same entity or are both typedefs of the same type.
6202static bool
6203IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6204 bool &SuppressRedeclaration) {
6205 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6206 SuppressRedeclaration = false;
6207 return true;
6208 }
6209
Richard Smithdda56e42011-04-15 14:24:37 +00006210 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6211 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006212 SuppressRedeclaration = true;
6213 return Context.hasSameType(TD1->getUnderlyingType(),
6214 TD2->getUnderlyingType());
6215 }
6216
6217 return false;
6218}
6219
6220
John McCall84d87672009-12-10 09:41:52 +00006221/// Determines whether to create a using shadow decl for a particular
6222/// decl, given the set of decls existing prior to this using lookup.
6223bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6224 const LookupResult &Previous) {
6225 // Diagnose finding a decl which is not from a base class of the
6226 // current class. We do this now because there are cases where this
6227 // function will silently decide not to build a shadow decl, which
6228 // will pre-empt further diagnostics.
6229 //
6230 // We don't need to do this in C++0x because we do the check once on
6231 // the qualifier.
6232 //
6233 // FIXME: diagnose the following if we care enough:
6234 // struct A { int foo; };
6235 // struct B : A { using A::foo; };
6236 // template <class T> struct C : A {};
6237 // template <class T> struct D : C<T> { using B::foo; } // <---
6238 // This is invalid (during instantiation) in C++03 because B::foo
6239 // resolves to the using decl in B, which is not a base class of D<T>.
6240 // We can't diagnose it immediately because C<T> is an unknown
6241 // specialization. The UsingShadowDecl in D<T> then points directly
6242 // to A::foo, which will look well-formed when we instantiate.
6243 // The right solution is to not collapse the shadow-decl chain.
6244 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6245 DeclContext *OrigDC = Orig->getDeclContext();
6246
6247 // Handle enums and anonymous structs.
6248 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6249 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6250 while (OrigRec->isAnonymousStructOrUnion())
6251 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6252
6253 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6254 if (OrigDC == CurContext) {
6255 Diag(Using->getLocation(),
6256 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006257 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006258 Diag(Orig->getLocation(), diag::note_using_decl_target);
6259 return true;
6260 }
6261
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006262 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006263 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006264 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006265 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006266 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006267 Diag(Orig->getLocation(), diag::note_using_decl_target);
6268 return true;
6269 }
6270 }
6271
6272 if (Previous.empty()) return false;
6273
6274 NamedDecl *Target = Orig;
6275 if (isa<UsingShadowDecl>(Target))
6276 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6277
John McCalla17e83e2009-12-11 02:33:26 +00006278 // If the target happens to be one of the previous declarations, we
6279 // don't have a conflict.
6280 //
6281 // FIXME: but we might be increasing its access, in which case we
6282 // should redeclare it.
6283 NamedDecl *NonTag = 0, *Tag = 0;
6284 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6285 I != E; ++I) {
6286 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006287 bool Result;
6288 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6289 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006290
6291 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6292 }
6293
John McCall84d87672009-12-10 09:41:52 +00006294 if (Target->isFunctionOrFunctionTemplate()) {
6295 FunctionDecl *FD;
6296 if (isa<FunctionTemplateDecl>(Target))
6297 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6298 else
6299 FD = cast<FunctionDecl>(Target);
6300
6301 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006302 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006303 case Ovl_Overload:
6304 return false;
6305
6306 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006307 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006308 break;
6309
6310 // We found a decl with the exact signature.
6311 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006312 // If we're in a record, we want to hide the target, so we
6313 // return true (without a diagnostic) to tell the caller not to
6314 // build a shadow decl.
6315 if (CurContext->isRecord())
6316 return true;
6317
6318 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006319 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006320 break;
6321 }
6322
6323 Diag(Target->getLocation(), diag::note_using_decl_target);
6324 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6325 return true;
6326 }
6327
6328 // Target is not a function.
6329
John McCall84d87672009-12-10 09:41:52 +00006330 if (isa<TagDecl>(Target)) {
6331 // No conflict between a tag and a non-tag.
6332 if (!Tag) return false;
6333
John McCalle29c5cd2009-12-10 19:51:03 +00006334 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006335 Diag(Target->getLocation(), diag::note_using_decl_target);
6336 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6337 return true;
6338 }
6339
6340 // No conflict between a tag and a non-tag.
6341 if (!NonTag) return false;
6342
John McCalle29c5cd2009-12-10 19:51:03 +00006343 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006344 Diag(Target->getLocation(), diag::note_using_decl_target);
6345 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6346 return true;
6347}
6348
John McCall3f746822009-11-17 05:59:44 +00006349/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006350UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006351 UsingDecl *UD,
6352 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006353
6354 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006355 NamedDecl *Target = Orig;
6356 if (isa<UsingShadowDecl>(Target)) {
6357 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6358 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006359 }
6360
6361 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006362 = UsingShadowDecl::Create(Context, CurContext,
6363 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006364 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006365
6366 Shadow->setAccess(UD->getAccess());
6367 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6368 Shadow->setInvalidDecl();
6369
John McCall3f746822009-11-17 05:59:44 +00006370 if (S)
John McCall3969e302009-12-08 07:46:18 +00006371 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006372 else
John McCall3969e302009-12-08 07:46:18 +00006373 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006374
John McCall3969e302009-12-08 07:46:18 +00006375
John McCall84d87672009-12-10 09:41:52 +00006376 return Shadow;
6377}
John McCall3969e302009-12-08 07:46:18 +00006378
John McCall84d87672009-12-10 09:41:52 +00006379/// Hides a using shadow declaration. This is required by the current
6380/// using-decl implementation when a resolvable using declaration in a
6381/// class is followed by a declaration which would hide or override
6382/// one or more of the using decl's targets; for example:
6383///
6384/// struct Base { void foo(int); };
6385/// struct Derived : Base {
6386/// using Base::foo;
6387/// void foo(int);
6388/// };
6389///
6390/// The governing language is C++03 [namespace.udecl]p12:
6391///
6392/// When a using-declaration brings names from a base class into a
6393/// derived class scope, member functions in the derived class
6394/// override and/or hide member functions with the same name and
6395/// parameter types in a base class (rather than conflicting).
6396///
6397/// There are two ways to implement this:
6398/// (1) optimistically create shadow decls when they're not hidden
6399/// by existing declarations, or
6400/// (2) don't create any shadow decls (or at least don't make them
6401/// visible) until we've fully parsed/instantiated the class.
6402/// The problem with (1) is that we might have to retroactively remove
6403/// a shadow decl, which requires several O(n) operations because the
6404/// decl structures are (very reasonably) not designed for removal.
6405/// (2) avoids this but is very fiddly and phase-dependent.
6406void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006407 if (Shadow->getDeclName().getNameKind() ==
6408 DeclarationName::CXXConversionFunctionName)
6409 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6410
John McCall84d87672009-12-10 09:41:52 +00006411 // Remove it from the DeclContext...
6412 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006413
John McCall84d87672009-12-10 09:41:52 +00006414 // ...and the scope, if applicable...
6415 if (S) {
John McCall48871652010-08-21 09:40:31 +00006416 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006417 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006418 }
6419
John McCall84d87672009-12-10 09:41:52 +00006420 // ...and the using decl.
6421 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6422
6423 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006424 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006425}
6426
John McCalle61f2ba2009-11-18 02:36:19 +00006427/// Builds a using declaration.
6428///
6429/// \param IsInstantiation - Whether this call arises from an
6430/// instantiation of an unresolved using declaration. We treat
6431/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006432NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6433 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006434 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006435 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006436 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006437 bool IsInstantiation,
6438 bool IsTypeName,
6439 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006440 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006441 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006442 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006443
Anders Carlssonf038fc22009-08-28 05:49:21 +00006444 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006445
Anders Carlsson59140b32009-08-28 03:16:11 +00006446 if (SS.isEmpty()) {
6447 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006448 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006449 }
Mike Stump11289f42009-09-09 15:08:12 +00006450
John McCall84d87672009-12-10 09:41:52 +00006451 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006452 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006453 ForRedeclaration);
6454 Previous.setHideTags(false);
6455 if (S) {
6456 LookupName(Previous, S);
6457
6458 // It is really dumb that we have to do this.
6459 LookupResult::Filter F = Previous.makeFilter();
6460 while (F.hasNext()) {
6461 NamedDecl *D = F.next();
6462 if (!isDeclInScope(D, CurContext, S))
6463 F.erase();
6464 }
6465 F.done();
6466 } else {
6467 assert(IsInstantiation && "no scope in non-instantiation");
6468 assert(CurContext->isRecord() && "scope not record in instantiation");
6469 LookupQualifiedName(Previous, CurContext);
6470 }
6471
John McCall84d87672009-12-10 09:41:52 +00006472 // Check for invalid redeclarations.
6473 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6474 return 0;
6475
6476 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006477 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6478 return 0;
6479
John McCall84c16cf2009-11-12 03:15:40 +00006480 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006481 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006482 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006483 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006484 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006485 // FIXME: not all declaration name kinds are legal here
6486 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6487 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006488 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006489 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006490 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006491 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6492 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006493 }
John McCallb96ec562009-12-04 22:46:56 +00006494 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006495 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6496 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006497 }
John McCallb96ec562009-12-04 22:46:56 +00006498 D->setAccess(AS);
6499 CurContext->addDecl(D);
6500
6501 if (!LookupContext) return D;
6502 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006503
John McCall0b66eb32010-05-01 00:40:08 +00006504 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006505 UD->setInvalidDecl();
6506 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006507 }
6508
Sebastian Redl08905022011-02-05 19:23:19 +00006509 // Constructor inheriting using decls get special treatment.
6510 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006511 if (CheckInheritedConstructorUsingDecl(UD))
6512 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006513 return UD;
6514 }
6515
6516 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006517
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006518 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006519
John McCall3969e302009-12-08 07:46:18 +00006520 // Unlike most lookups, we don't always want to hide tag
6521 // declarations: tag names are visible through the using declaration
6522 // even if hidden by ordinary names, *except* in a dependent context
6523 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006524 if (!IsInstantiation)
6525 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006526
John McCall27b18f82009-11-17 02:14:36 +00006527 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006528
John McCall9f3059a2009-10-09 21:13:30 +00006529 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006530 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006531 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006532 UD->setInvalidDecl();
6533 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006534 }
6535
John McCallb96ec562009-12-04 22:46:56 +00006536 if (R.isAmbiguous()) {
6537 UD->setInvalidDecl();
6538 return UD;
6539 }
Mike Stump11289f42009-09-09 15:08:12 +00006540
John McCalle61f2ba2009-11-18 02:36:19 +00006541 if (IsTypeName) {
6542 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006543 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006544 Diag(IdentLoc, diag::err_using_typename_non_type);
6545 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6546 Diag((*I)->getUnderlyingDecl()->getLocation(),
6547 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006548 UD->setInvalidDecl();
6549 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006550 }
6551 } else {
6552 // If we asked for a non-typename and we got a type, error out,
6553 // but only if this is an instantiation of an unresolved using
6554 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006555 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006556 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6557 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006558 UD->setInvalidDecl();
6559 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006560 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006561 }
6562
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006563 // C++0x N2914 [namespace.udecl]p6:
6564 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006565 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006566 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6567 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006568 UD->setInvalidDecl();
6569 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006570 }
Mike Stump11289f42009-09-09 15:08:12 +00006571
John McCall84d87672009-12-10 09:41:52 +00006572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6573 if (!CheckUsingShadowDecl(UD, *I, Previous))
6574 BuildUsingShadowDecl(S, UD, *I);
6575 }
John McCall3f746822009-11-17 05:59:44 +00006576
6577 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006578}
6579
Sebastian Redl08905022011-02-05 19:23:19 +00006580/// Additional checks for a using declaration referring to a constructor name.
6581bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6582 if (UD->isTypeName()) {
6583 // FIXME: Cannot specify typename when specifying constructor
6584 return true;
6585 }
6586
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006587 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006588 assert(SourceType &&
6589 "Using decl naming constructor doesn't have type in scope spec.");
6590 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6591
6592 // Check whether the named type is a direct base class.
6593 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6594 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6595 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6596 BaseIt != BaseE; ++BaseIt) {
6597 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6598 if (CanonicalSourceType == BaseType)
6599 break;
6600 }
6601
6602 if (BaseIt == BaseE) {
6603 // Did not find SourceType in the bases.
6604 Diag(UD->getUsingLocation(),
6605 diag::err_using_decl_constructor_not_in_direct_base)
6606 << UD->getNameInfo().getSourceRange()
6607 << QualType(SourceType, 0) << TargetClass;
6608 return true;
6609 }
6610
6611 BaseIt->setInheritConstructors();
6612
6613 return false;
6614}
6615
John McCall84d87672009-12-10 09:41:52 +00006616/// Checks that the given using declaration is not an invalid
6617/// redeclaration. Note that this is checking only for the using decl
6618/// itself, not for any ill-formedness among the UsingShadowDecls.
6619bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6620 bool isTypeName,
6621 const CXXScopeSpec &SS,
6622 SourceLocation NameLoc,
6623 const LookupResult &Prev) {
6624 // C++03 [namespace.udecl]p8:
6625 // C++0x [namespace.udecl]p10:
6626 // A using-declaration is a declaration and can therefore be used
6627 // repeatedly where (and only where) multiple declarations are
6628 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006629 //
John McCall032092f2010-11-29 18:01:58 +00006630 // That's in non-member contexts.
6631 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006632 return false;
6633
6634 NestedNameSpecifier *Qual
6635 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6636
6637 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6638 NamedDecl *D = *I;
6639
6640 bool DTypename;
6641 NestedNameSpecifier *DQual;
6642 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6643 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006644 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006645 } else if (UnresolvedUsingValueDecl *UD
6646 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6647 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006648 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006649 } else if (UnresolvedUsingTypenameDecl *UD
6650 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6651 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006652 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006653 } else continue;
6654
6655 // using decls differ if one says 'typename' and the other doesn't.
6656 // FIXME: non-dependent using decls?
6657 if (isTypeName != DTypename) continue;
6658
6659 // using decls differ if they name different scopes (but note that
6660 // template instantiation can cause this check to trigger when it
6661 // didn't before instantiation).
6662 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6663 Context.getCanonicalNestedNameSpecifier(DQual))
6664 continue;
6665
6666 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006667 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006668 return true;
6669 }
6670
6671 return false;
6672}
6673
John McCall3969e302009-12-08 07:46:18 +00006674
John McCallb96ec562009-12-04 22:46:56 +00006675/// Checks that the given nested-name qualifier used in a using decl
6676/// in the current context is appropriately related to the current
6677/// scope. If an error is found, diagnoses it and returns true.
6678bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6679 const CXXScopeSpec &SS,
6680 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006681 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006682
John McCall3969e302009-12-08 07:46:18 +00006683 if (!CurContext->isRecord()) {
6684 // C++03 [namespace.udecl]p3:
6685 // C++0x [namespace.udecl]p8:
6686 // A using-declaration for a class member shall be a member-declaration.
6687
6688 // If we weren't able to compute a valid scope, it must be a
6689 // dependent class scope.
6690 if (!NamedContext || NamedContext->isRecord()) {
6691 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6692 << SS.getRange();
6693 return true;
6694 }
6695
6696 // Otherwise, everything is known to be fine.
6697 return false;
6698 }
6699
6700 // The current scope is a record.
6701
6702 // If the named context is dependent, we can't decide much.
6703 if (!NamedContext) {
6704 // FIXME: in C++0x, we can diagnose if we can prove that the
6705 // nested-name-specifier does not refer to a base class, which is
6706 // still possible in some cases.
6707
6708 // Otherwise we have to conservatively report that things might be
6709 // okay.
6710 return false;
6711 }
6712
6713 if (!NamedContext->isRecord()) {
6714 // Ideally this would point at the last name in the specifier,
6715 // but we don't have that level of source info.
6716 Diag(SS.getRange().getBegin(),
6717 diag::err_using_decl_nested_name_specifier_is_not_class)
6718 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6719 return true;
6720 }
6721
Douglas Gregor7c842292010-12-21 07:41:49 +00006722 if (!NamedContext->isDependentContext() &&
6723 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6724 return true;
6725
John McCall3969e302009-12-08 07:46:18 +00006726 if (getLangOptions().CPlusPlus0x) {
6727 // C++0x [namespace.udecl]p3:
6728 // In a using-declaration used as a member-declaration, the
6729 // nested-name-specifier shall name a base class of the class
6730 // being defined.
6731
6732 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6733 cast<CXXRecordDecl>(NamedContext))) {
6734 if (CurContext == NamedContext) {
6735 Diag(NameLoc,
6736 diag::err_using_decl_nested_name_specifier_is_current_class)
6737 << SS.getRange();
6738 return true;
6739 }
6740
6741 Diag(SS.getRange().getBegin(),
6742 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6743 << (NestedNameSpecifier*) SS.getScopeRep()
6744 << cast<CXXRecordDecl>(CurContext)
6745 << SS.getRange();
6746 return true;
6747 }
6748
6749 return false;
6750 }
6751
6752 // C++03 [namespace.udecl]p4:
6753 // A using-declaration used as a member-declaration shall refer
6754 // to a member of a base class of the class being defined [etc.].
6755
6756 // Salient point: SS doesn't have to name a base class as long as
6757 // lookup only finds members from base classes. Therefore we can
6758 // diagnose here only if we can prove that that can't happen,
6759 // i.e. if the class hierarchies provably don't intersect.
6760
6761 // TODO: it would be nice if "definitely valid" results were cached
6762 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6763 // need to be repeated.
6764
6765 struct UserData {
6766 llvm::DenseSet<const CXXRecordDecl*> Bases;
6767
6768 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6769 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6770 Data->Bases.insert(Base);
6771 return true;
6772 }
6773
6774 bool hasDependentBases(const CXXRecordDecl *Class) {
6775 return !Class->forallBases(collect, this);
6776 }
6777
6778 /// Returns true if the base is dependent or is one of the
6779 /// accumulated base classes.
6780 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6781 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6782 return !Data->Bases.count(Base);
6783 }
6784
6785 bool mightShareBases(const CXXRecordDecl *Class) {
6786 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6787 }
6788 };
6789
6790 UserData Data;
6791
6792 // Returns false if we find a dependent base.
6793 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6794 return false;
6795
6796 // Returns false if the class has a dependent base or if it or one
6797 // of its bases is present in the base set of the current context.
6798 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6799 return false;
6800
6801 Diag(SS.getRange().getBegin(),
6802 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6803 << (NestedNameSpecifier*) SS.getScopeRep()
6804 << cast<CXXRecordDecl>(CurContext)
6805 << SS.getRange();
6806
6807 return true;
John McCallb96ec562009-12-04 22:46:56 +00006808}
6809
Richard Smithdda56e42011-04-15 14:24:37 +00006810Decl *Sema::ActOnAliasDeclaration(Scope *S,
6811 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006812 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006813 SourceLocation UsingLoc,
6814 UnqualifiedId &Name,
6815 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006816 // Skip up to the relevant declaration scope.
6817 while (S->getFlags() & Scope::TemplateParamScope)
6818 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006819 assert((S->getFlags() & Scope::DeclScope) &&
6820 "got alias-declaration outside of declaration scope");
6821
6822 if (Type.isInvalid())
6823 return 0;
6824
6825 bool Invalid = false;
6826 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6827 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006828 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006829
6830 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6831 return 0;
6832
6833 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006834 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006835 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006836 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6837 TInfo->getTypeLoc().getBeginLoc());
6838 }
Richard Smithdda56e42011-04-15 14:24:37 +00006839
6840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6841 LookupName(Previous, S);
6842
6843 // Warn about shadowing the name of a template parameter.
6844 if (Previous.isSingleResult() &&
6845 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00006846 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00006847 Previous.clear();
6848 }
6849
6850 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6851 "name in alias declaration must be an identifier");
6852 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6853 Name.StartLocation,
6854 Name.Identifier, TInfo);
6855
6856 NewTD->setAccess(AS);
6857
6858 if (Invalid)
6859 NewTD->setInvalidDecl();
6860
Richard Smith3f1b5d02011-05-05 21:57:07 +00006861 CheckTypedefForVariablyModifiedType(S, NewTD);
6862 Invalid |= NewTD->isInvalidDecl();
6863
Richard Smithdda56e42011-04-15 14:24:37 +00006864 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006865
6866 NamedDecl *NewND;
6867 if (TemplateParamLists.size()) {
6868 TypeAliasTemplateDecl *OldDecl = 0;
6869 TemplateParameterList *OldTemplateParams = 0;
6870
6871 if (TemplateParamLists.size() != 1) {
6872 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6873 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6874 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6875 }
6876 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6877
6878 // Only consider previous declarations in the same scope.
6879 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6880 /*ExplicitInstantiationOrSpecialization*/false);
6881 if (!Previous.empty()) {
6882 Redeclaration = true;
6883
6884 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6885 if (!OldDecl && !Invalid) {
6886 Diag(UsingLoc, diag::err_redefinition_different_kind)
6887 << Name.Identifier;
6888
6889 NamedDecl *OldD = Previous.getRepresentativeDecl();
6890 if (OldD->getLocation().isValid())
6891 Diag(OldD->getLocation(), diag::note_previous_definition);
6892
6893 Invalid = true;
6894 }
6895
6896 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6897 if (TemplateParameterListsAreEqual(TemplateParams,
6898 OldDecl->getTemplateParameters(),
6899 /*Complain=*/true,
6900 TPL_TemplateMatch))
6901 OldTemplateParams = OldDecl->getTemplateParameters();
6902 else
6903 Invalid = true;
6904
6905 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6906 if (!Invalid &&
6907 !Context.hasSameType(OldTD->getUnderlyingType(),
6908 NewTD->getUnderlyingType())) {
6909 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6910 // but we can't reasonably accept it.
6911 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6912 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6913 if (OldTD->getLocation().isValid())
6914 Diag(OldTD->getLocation(), diag::note_previous_definition);
6915 Invalid = true;
6916 }
6917 }
6918 }
6919
6920 // Merge any previous default template arguments into our parameters,
6921 // and check the parameter list.
6922 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6923 TPC_TypeAliasTemplate))
6924 return 0;
6925
6926 TypeAliasTemplateDecl *NewDecl =
6927 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6928 Name.Identifier, TemplateParams,
6929 NewTD);
6930
6931 NewDecl->setAccess(AS);
6932
6933 if (Invalid)
6934 NewDecl->setInvalidDecl();
6935 else if (OldDecl)
6936 NewDecl->setPreviousDeclaration(OldDecl);
6937
6938 NewND = NewDecl;
6939 } else {
6940 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6941 NewND = NewTD;
6942 }
Richard Smithdda56e42011-04-15 14:24:37 +00006943
6944 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006945 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006946
Richard Smith3f1b5d02011-05-05 21:57:07 +00006947 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006948}
6949
John McCall48871652010-08-21 09:40:31 +00006950Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006951 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006952 SourceLocation AliasLoc,
6953 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006954 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006955 SourceLocation IdentLoc,
6956 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006957
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006958 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006959 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6960 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006961
Anders Carlssondca83c42009-03-28 06:23:46 +00006962 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006963 NamedDecl *PrevDecl
6964 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6965 ForRedeclaration);
6966 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6967 PrevDecl = 0;
6968
6969 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006970 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006971 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006972 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006973 // FIXME: At some point, we'll want to create the (redundant)
6974 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006975 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006976 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006977 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006978 }
Mike Stump11289f42009-09-09 15:08:12 +00006979
Anders Carlssondca83c42009-03-28 06:23:46 +00006980 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6981 diag::err_redefinition_different_kind;
6982 Diag(AliasLoc, DiagID) << Alias;
6983 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006984 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006985 }
6986
John McCall27b18f82009-11-17 02:14:36 +00006987 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006988 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006989
John McCall9f3059a2009-10-09 21:13:30 +00006990 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006991 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006992 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006993 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006994 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006995 }
Mike Stump11289f42009-09-09 15:08:12 +00006996
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006997 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006998 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006999 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007000 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007001
John McCalld8d0d432010-02-16 06:53:13 +00007002 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007003 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007004}
7005
Douglas Gregora57478e2010-05-01 15:04:51 +00007006namespace {
7007 /// \brief Scoped object used to handle the state changes required in Sema
7008 /// to implicitly define the body of a C++ member function;
7009 class ImplicitlyDefinedFunctionScope {
7010 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00007011 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00007012
7013 public:
7014 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00007015 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00007016 {
Douglas Gregora57478e2010-05-01 15:04:51 +00007017 S.PushFunctionScope();
7018 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
7019 }
7020
7021 ~ImplicitlyDefinedFunctionScope() {
7022 S.PopExpressionEvaluationContext();
Eli Friedman71c80552012-01-05 03:35:19 +00007023 S.PopFunctionScopeInfo();
Douglas Gregora57478e2010-05-01 15:04:51 +00007024 }
7025 };
7026}
7027
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007028Sema::ImplicitExceptionSpecification
7029Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00007030 // C++ [except.spec]p14:
7031 // An implicitly declared special member function (Clause 12) shall have an
7032 // exception-specification. [...]
7033 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007034 if (ClassDecl->isInvalidDecl())
7035 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007036
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007037 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007038 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7039 BEnd = ClassDecl->bases_end();
7040 B != BEnd; ++B) {
7041 if (B->isVirtual()) // Handled below.
7042 continue;
7043
Douglas Gregor9672f922010-07-03 00:47:00 +00007044 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007046 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7047 // If this is a deleted function, add it anyway. This might be conformant
7048 // with the standard. This might not. I'm not sure. It might not matter.
7049 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007050 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007051 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007052 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007053
7054 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007055 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7056 BEnd = ClassDecl->vbases_end();
7057 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007058 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7061 // If this is a deleted function, add it anyway. This might be conformant
7062 // with the standard. This might not. I'm not sure. It might not matter.
7063 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007064 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007065 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007066 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007067
7068 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007069 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7070 FEnd = ClassDecl->field_end();
7071 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007072 if (F->hasInClassInitializer()) {
7073 if (Expr *E = F->getInClassInitializer())
7074 ExceptSpec.CalledExpr(E);
7075 else if (!F->isInvalidDecl())
7076 ExceptSpec.SetDelayed();
7077 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7081 // If this is a deleted function, add it anyway. This might be conformant
7082 // with the standard. This might not. I'm not sure. It might not matter.
7083 // In particular, the problem is that this function never gets called. It
7084 // might just be ill-formed because this function attempts to refer to
7085 // a deleted function here.
7086 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007087 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007088 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007089 }
John McCalldb40c7f2010-12-14 08:05:40 +00007090
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007091 return ExceptSpec;
7092}
7093
7094CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7095 CXXRecordDecl *ClassDecl) {
7096 // C++ [class.ctor]p5:
7097 // A default constructor for a class X is a constructor of class X
7098 // that can be called without an argument. If there is no
7099 // user-declared constructor for class X, a default constructor is
7100 // implicitly declared. An implicitly-declared default constructor
7101 // is an inline public member of its class.
7102 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7103 "Should not build implicit default constructor!");
7104
7105 ImplicitExceptionSpecification Spec =
7106 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7107 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00007108
Douglas Gregor6d880b12010-07-01 22:31:05 +00007109 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007110 CanQualType ClassType
7111 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007112 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007113 DeclarationName Name
7114 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007115 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00007116 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7117 Context, ClassDecl, ClassLoc, NameInfo,
7118 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7119 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7120 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7121 getLangOptions().CPlusPlus0x);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007122 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007123 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007124 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00007125 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00007126
7127 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007128 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7129
Douglas Gregor0be31a22010-07-02 17:43:08 +00007130 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007131 PushOnScopeChains(DefaultCon, S, false);
7132 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007133
Alexis Huntd6da8762011-10-10 06:18:57 +00007134 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007135 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00007136
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007137 return DefaultCon;
7138}
7139
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007140void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7141 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007142 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007143 !Constructor->doesThisDeclarationHaveABody() &&
7144 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007145 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007146
Anders Carlsson423f5d82010-04-23 16:04:08 +00007147 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007148 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007149
Douglas Gregora57478e2010-05-01 15:04:51 +00007150 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007151 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007152 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007153 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007154 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007155 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007156 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007157 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007158 }
Douglas Gregor73193272010-09-20 16:48:21 +00007159
7160 SourceLocation Loc = Constructor->getLocation();
7161 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7162
7163 Constructor->setUsed();
7164 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007165
7166 if (ASTMutationListener *L = getASTMutationListener()) {
7167 L->CompletedImplicitDefinition(Constructor);
7168 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007169}
7170
Richard Smith938f40b2011-06-11 17:19:42 +00007171/// Get any existing defaulted default constructor for the given class. Do not
7172/// implicitly define one if it does not exist.
7173static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7174 CXXRecordDecl *D) {
7175 ASTContext &Context = Self.Context;
7176 QualType ClassType = Context.getTypeDeclType(D);
7177 DeclarationName ConstructorName
7178 = Context.DeclarationNames.getCXXConstructorName(
7179 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7180
7181 DeclContext::lookup_const_iterator Con, ConEnd;
7182 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7183 Con != ConEnd; ++Con) {
7184 // A function template cannot be defaulted.
7185 if (isa<FunctionTemplateDecl>(*Con))
7186 continue;
7187
7188 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7189 if (Constructor->isDefaultConstructor())
7190 return Constructor->isDefaulted() ? Constructor : 0;
7191 }
7192 return 0;
7193}
7194
7195void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7196 if (!D) return;
7197 AdjustDeclIfTemplate(D);
7198
7199 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7200 CXXConstructorDecl *CtorDecl
7201 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7202
7203 if (!CtorDecl) return;
7204
7205 // Compute the exception specification for the default constructor.
7206 const FunctionProtoType *CtorTy =
7207 CtorDecl->getType()->castAs<FunctionProtoType>();
7208 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7209 ImplicitExceptionSpecification Spec =
7210 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7211 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7212 assert(EPI.ExceptionSpecType != EST_Delayed);
7213
7214 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7215 }
7216
7217 // If the default constructor is explicitly defaulted, checking the exception
7218 // specification is deferred until now.
7219 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7220 !ClassDecl->isDependentType())
7221 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7222}
7223
Sebastian Redl08905022011-02-05 19:23:19 +00007224void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7225 // We start with an initial pass over the base classes to collect those that
7226 // inherit constructors from. If there are none, we can forgo all further
7227 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007228 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007229 BasesVector BasesToInheritFrom;
7230 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7231 BaseE = ClassDecl->bases_end();
7232 BaseIt != BaseE; ++BaseIt) {
7233 if (BaseIt->getInheritConstructors()) {
7234 QualType Base = BaseIt->getType();
7235 if (Base->isDependentType()) {
7236 // If we inherit constructors from anything that is dependent, just
7237 // abort processing altogether. We'll get another chance for the
7238 // instantiations.
7239 return;
7240 }
7241 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7242 }
7243 }
7244 if (BasesToInheritFrom.empty())
7245 return;
7246
7247 // Now collect the constructors that we already have in the current class.
7248 // Those take precedence over inherited constructors.
7249 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7250 // unless there is a user-declared constructor with the same signature in
7251 // the class where the using-declaration appears.
7252 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7253 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7254 CtorE = ClassDecl->ctor_end();
7255 CtorIt != CtorE; ++CtorIt) {
7256 ExistingConstructors.insert(
7257 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7258 }
7259
7260 Scope *S = getScopeForContext(ClassDecl);
7261 DeclarationName CreatedCtorName =
7262 Context.DeclarationNames.getCXXConstructorName(
7263 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7264
7265 // Now comes the true work.
7266 // First, we keep a map from constructor types to the base that introduced
7267 // them. Needed for finding conflicting constructors. We also keep the
7268 // actually inserted declarations in there, for pretty diagnostics.
7269 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7270 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7271 ConstructorToSourceMap InheritedConstructors;
7272 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7273 BaseE = BasesToInheritFrom.end();
7274 BaseIt != BaseE; ++BaseIt) {
7275 const RecordType *Base = *BaseIt;
7276 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7277 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7278 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7279 CtorE = BaseDecl->ctor_end();
7280 CtorIt != CtorE; ++CtorIt) {
7281 // Find the using declaration for inheriting this base's constructors.
7282 DeclarationName Name =
7283 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7284 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7285 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7286 SourceLocation UsingLoc = UD ? UD->getLocation() :
7287 ClassDecl->getLocation();
7288
7289 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7290 // from the class X named in the using-declaration consists of actual
7291 // constructors and notional constructors that result from the
7292 // transformation of defaulted parameters as follows:
7293 // - all non-template default constructors of X, and
7294 // - for each non-template constructor of X that has at least one
7295 // parameter with a default argument, the set of constructors that
7296 // results from omitting any ellipsis parameter specification and
7297 // successively omitting parameters with a default argument from the
7298 // end of the parameter-type-list.
7299 CXXConstructorDecl *BaseCtor = *CtorIt;
7300 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7301 const FunctionProtoType *BaseCtorType =
7302 BaseCtor->getType()->getAs<FunctionProtoType>();
7303
7304 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7305 maxParams = BaseCtor->getNumParams();
7306 params <= maxParams; ++params) {
7307 // Skip default constructors. They're never inherited.
7308 if (params == 0)
7309 continue;
7310 // Skip copy and move constructors for the same reason.
7311 if (CanBeCopyOrMove && params == 1)
7312 continue;
7313
7314 // Build up a function type for this particular constructor.
7315 // FIXME: The working paper does not consider that the exception spec
7316 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007317 // source. This code doesn't yet, either. When it does, this code will
7318 // need to be delayed until after exception specifications and in-class
7319 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007320 const Type *NewCtorType;
7321 if (params == maxParams)
7322 NewCtorType = BaseCtorType;
7323 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007324 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007325 for (unsigned i = 0; i < params; ++i) {
7326 Args.push_back(BaseCtorType->getArgType(i));
7327 }
7328 FunctionProtoType::ExtProtoInfo ExtInfo =
7329 BaseCtorType->getExtProtoInfo();
7330 ExtInfo.Variadic = false;
7331 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7332 Args.data(), params, ExtInfo)
7333 .getTypePtr();
7334 }
7335 const Type *CanonicalNewCtorType =
7336 Context.getCanonicalType(NewCtorType);
7337
7338 // Now that we have the type, first check if the class already has a
7339 // constructor with this signature.
7340 if (ExistingConstructors.count(CanonicalNewCtorType))
7341 continue;
7342
7343 // Then we check if we have already declared an inherited constructor
7344 // with this signature.
7345 std::pair<ConstructorToSourceMap::iterator, bool> result =
7346 InheritedConstructors.insert(std::make_pair(
7347 CanonicalNewCtorType,
7348 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7349 if (!result.second) {
7350 // Already in the map. If it came from a different class, that's an
7351 // error. Not if it's from the same.
7352 CanQualType PreviousBase = result.first->second.first;
7353 if (CanonicalBase != PreviousBase) {
7354 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7355 const CXXConstructorDecl *PrevBaseCtor =
7356 PrevCtor->getInheritedConstructor();
7357 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7358
7359 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7360 Diag(BaseCtor->getLocation(),
7361 diag::note_using_decl_constructor_conflict_current_ctor);
7362 Diag(PrevBaseCtor->getLocation(),
7363 diag::note_using_decl_constructor_conflict_previous_ctor);
7364 Diag(PrevCtor->getLocation(),
7365 diag::note_using_decl_constructor_conflict_previous_using);
7366 }
7367 continue;
7368 }
7369
7370 // OK, we're there, now add the constructor.
7371 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007372 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007373 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7374 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007375 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7376 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007377 /*ImplicitlyDeclared=*/true,
7378 // FIXME: Due to a defect in the standard, we treat inherited
7379 // constructors as constexpr even if that makes them ill-formed.
7380 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007381 NewCtor->setAccess(BaseCtor->getAccess());
7382
7383 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007384 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007385 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007386 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7387 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007388 /*IdentifierInfo=*/0,
7389 BaseCtorType->getArgType(i),
7390 /*TInfo=*/0, SC_None,
7391 SC_None, /*DefaultArg=*/0));
7392 }
David Blaikie9c70e042011-09-21 18:16:56 +00007393 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007394 NewCtor->setInheritedConstructor(BaseCtor);
7395
7396 PushOnScopeChains(NewCtor, S, false);
7397 ClassDecl->addDecl(NewCtor);
7398 result.first->second.second = NewCtor;
7399 }
7400 }
7401 }
7402}
7403
Alexis Huntf91729462011-05-12 22:46:25 +00007404Sema::ImplicitExceptionSpecification
7405Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007406 // C++ [except.spec]p14:
7407 // An implicitly declared special member function (Clause 12) shall have
7408 // an exception-specification.
7409 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007410 if (ClassDecl->isInvalidDecl())
7411 return ExceptSpec;
7412
Douglas Gregorf1203042010-07-01 19:09:28 +00007413 // Direct base-class destructors.
7414 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7415 BEnd = ClassDecl->bases_end();
7416 B != BEnd; ++B) {
7417 if (B->isVirtual()) // Handled below.
7418 continue;
7419
7420 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7421 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007422 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007423 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007424
Douglas Gregorf1203042010-07-01 19:09:28 +00007425 // Virtual base-class destructors.
7426 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7427 BEnd = ClassDecl->vbases_end();
7428 B != BEnd; ++B) {
7429 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7430 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007431 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007432 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007433
Douglas Gregorf1203042010-07-01 19:09:28 +00007434 // Field destructors.
7435 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7436 FEnd = ClassDecl->field_end();
7437 F != FEnd; ++F) {
7438 if (const RecordType *RecordTy
7439 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7440 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007441 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007442 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007443
Alexis Huntf91729462011-05-12 22:46:25 +00007444 return ExceptSpec;
7445}
7446
7447CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7448 // C++ [class.dtor]p2:
7449 // If a class has no user-declared destructor, a destructor is
7450 // declared implicitly. An implicitly-declared destructor is an
7451 // inline public member of its class.
7452
7453 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007454 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007455 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7456
Douglas Gregor7454c562010-07-02 20:37:36 +00007457 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007458 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007459
Douglas Gregorf1203042010-07-01 19:09:28 +00007460 CanQualType ClassType
7461 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007462 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007463 DeclarationName Name
7464 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007465 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007466 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007467 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7468 /*isInline=*/true,
7469 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007470 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007471 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007472 Destructor->setImplicit();
7473 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007474
7475 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007476 ++ASTContext::NumImplicitDestructorsDeclared;
7477
7478 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007479 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007480 PushOnScopeChains(Destructor, S, false);
7481 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007482
7483 // This could be uniqued if it ever proves significant.
7484 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007485
7486 if (ShouldDeleteDestructor(Destructor))
7487 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007488
7489 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007490
Douglas Gregorf1203042010-07-01 19:09:28 +00007491 return Destructor;
7492}
7493
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007494void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007495 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007496 assert((Destructor->isDefaulted() &&
7497 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007498 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007499 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007500 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007501
Douglas Gregor54818f02010-05-12 16:39:35 +00007502 if (Destructor->isInvalidDecl())
7503 return;
7504
Douglas Gregora57478e2010-05-01 15:04:51 +00007505 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007506
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007507 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007508 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7509 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007510
Douglas Gregor54818f02010-05-12 16:39:35 +00007511 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007512 Diag(CurrentLocation, diag::note_member_synthesized_at)
7513 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7514
7515 Destructor->setInvalidDecl();
7516 return;
7517 }
7518
Douglas Gregor73193272010-09-20 16:48:21 +00007519 SourceLocation Loc = Destructor->getLocation();
7520 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007521 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007522 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007523 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007524
7525 if (ASTMutationListener *L = getASTMutationListener()) {
7526 L->CompletedImplicitDefinition(Destructor);
7527 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007528}
7529
Sebastian Redl623ea822011-05-19 05:13:44 +00007530void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7531 CXXDestructorDecl *destructor) {
7532 // C++11 [class.dtor]p3:
7533 // A declaration of a destructor that does not have an exception-
7534 // specification is implicitly considered to have the same exception-
7535 // specification as an implicit declaration.
7536 const FunctionProtoType *dtorType = destructor->getType()->
7537 getAs<FunctionProtoType>();
7538 if (dtorType->hasExceptionSpec())
7539 return;
7540
7541 ImplicitExceptionSpecification exceptSpec =
7542 ComputeDefaultedDtorExceptionSpec(classDecl);
7543
Chandler Carruth9a797572011-09-20 04:55:26 +00007544 // Replace the destructor's type, building off the existing one. Fortunately,
7545 // the only thing of interest in the destructor type is its extended info.
7546 // The return and arguments are fixed.
7547 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007548 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7549 epi.NumExceptions = exceptSpec.size();
7550 epi.Exceptions = exceptSpec.data();
7551 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7552
7553 destructor->setType(ty);
7554
7555 // FIXME: If the destructor has a body that could throw, and the newly created
7556 // spec doesn't allow exceptions, we should emit a warning, because this
7557 // change in behavior can break conforming C++03 programs at runtime.
7558 // However, we don't have a body yet, so it needs to be done somewhere else.
7559}
7560
Sebastian Redl22653ba2011-08-30 19:58:05 +00007561/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007562/// \c To.
7563///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007564/// This routine is used to copy/move the members of a class with an
7565/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007566/// copied are arrays, this routine builds for loops to copy them.
7567///
7568/// \param S The Sema object used for type-checking.
7569///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007570/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007571///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007572/// \param T The type of the expressions being copied/moved. Both expressions
7573/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007574///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007575/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007576///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007577/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007578///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007579/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007580/// Otherwise, it's a non-static member subobject.
7581///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007582/// \param Copying Whether we're copying or moving.
7583///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007584/// \param Depth Internal parameter recording the depth of the recursion.
7585///
7586/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007587static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007588BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007589 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007590 bool CopyingBaseSubobject, bool Copying,
7591 unsigned Depth = 0) {
7592 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007593 // Each subobject is assigned in the manner appropriate to its type:
7594 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007595 // - if the subobject is of class type, as if by a call to operator= with
7596 // the subobject as the object expression and the corresponding
7597 // subobject of x as a single function argument (as if by explicit
7598 // qualification; that is, ignoring any possible virtual overriding
7599 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007600 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7601 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7602
7603 // Look for operator=.
7604 DeclarationName Name
7605 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7606 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7607 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7608
Sebastian Redl22653ba2011-08-30 19:58:05 +00007609 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007610 LookupResult::Filter F = OpLookup.makeFilter();
7611 while (F.hasNext()) {
7612 NamedDecl *D = F.next();
7613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007614 if (Copying ? Method->isCopyAssignmentOperator() :
7615 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007616 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007617
Douglas Gregorb139cd52010-05-01 20:49:11 +00007618 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007619 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007620 F.done();
7621
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007622 // Suppress the protected check (C++ [class.protected]) for each of the
7623 // assignment operators we found. This strange dance is required when
7624 // we're assigning via a base classes's copy-assignment operator. To
7625 // ensure that we're getting the right base class subobject (without
7626 // ambiguities), we need to cast "this" to that subobject type; to
7627 // ensure that we don't go through the virtual call mechanism, we need
7628 // to qualify the operator= name with the base class (see below). However,
7629 // this means that if the base class has a protected copy assignment
7630 // operator, the protected member access check will fail. So, we
7631 // rewrite "protected" access to "public" access in this case, since we
7632 // know by construction that we're calling from a derived class.
7633 if (CopyingBaseSubobject) {
7634 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7635 L != LEnd; ++L) {
7636 if (L.getAccess() == AS_protected)
7637 L.setAccess(AS_public);
7638 }
7639 }
7640
Douglas Gregorb139cd52010-05-01 20:49:11 +00007641 // Create the nested-name-specifier that will be used to qualify the
7642 // reference to operator=; this is required to suppress the virtual
7643 // call mechanism.
7644 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00007645 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregor869ad452011-02-24 17:54:50 +00007646 SS.MakeTrivial(S.Context,
7647 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00007648 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00007649 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007650
7651 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007652 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007653 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00007654 /*TemplateKWLoc=*/SourceLocation(),
7655 /*FirstQualifierInScope=*/0,
7656 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007657 /*TemplateArgs=*/0,
7658 /*SuppressQualifierCheck=*/true);
7659 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007660 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007661
7662 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007663
John McCalldadc5752010-08-24 06:29:42 +00007664 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007665 OpEqualRef.takeAs<Expr>(),
7666 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007667 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007668 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007669
7670 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007671 }
John McCallab8c2732010-03-16 06:11:48 +00007672
Douglas Gregorb139cd52010-05-01 20:49:11 +00007673 // - if the subobject is of scalar type, the built-in assignment
7674 // operator is used.
7675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7676 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007678 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007679 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007680
7681 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007682 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007683
7684 // - if the subobject is an array, each element is assigned, in the
7685 // manner appropriate to the element type;
7686
7687 // Construct a loop over the array bounds, e.g.,
7688 //
7689 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7690 //
7691 // that will copy each of the array elements.
7692 QualType SizeType = S.Context.getSizeType();
7693
7694 // Create the iteration variable.
7695 IdentifierInfo *IterationVarName = 0;
7696 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007697 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007698 llvm::raw_svector_ostream OS(Str);
7699 OS << "__i" << Depth;
7700 IterationVarName = &S.Context.Idents.get(OS.str());
7701 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007702 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007703 IterationVarName, SizeType,
7704 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007705 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007706
7707 // Initialize the iteration variable to zero.
7708 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007709 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007710
7711 // Create a reference to the iteration variable; we'll use this several
7712 // times throughout.
7713 Expr *IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00007714 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007715 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00007716 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7717 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7718
Douglas Gregorb139cd52010-05-01 20:49:11 +00007719 // Create the DeclStmt that holds the iteration variable.
7720 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7721
7722 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007723 llvm::APInt Upper
7724 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007725 Expr *Comparison
Eli Friedman844f9452012-01-23 02:35:22 +00007726 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCall7decc9e2010-11-18 06:31:45 +00007727 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7728 BO_NE, S.Context.BoolTy,
7729 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007730
7731 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007732 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007733 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7734 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007735
7736 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007737 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007738 IterationVarRefRVal,
7739 Loc));
John McCallb268a282010-08-23 23:25:46 +00007740 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007741 IterationVarRefRVal,
7742 Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007743 if (!Copying) // Cast to rvalue
7744 From = CastForMoving(S, From);
7745
7746 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007747 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7748 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007749 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007750 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007751 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007752
7753 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007754 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007755 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007756 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007757 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007758}
7759
Alexis Hunt119f3652011-05-14 05:23:20 +00007760std::pair<Sema::ImplicitExceptionSpecification, bool>
7761Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7762 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007763 if (ClassDecl->isInvalidDecl())
7764 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7765
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007766 // C++ [class.copy]p10:
7767 // If the class definition does not explicitly declare a copy
7768 // assignment operator, one is declared implicitly.
7769 // The implicitly-defined copy assignment operator for a class X
7770 // will have the form
7771 //
7772 // X& X::operator=(const X&)
7773 //
7774 // if
7775 bool HasConstCopyAssignment = true;
7776
7777 // -- each direct base class B of X has a copy assignment operator
7778 // whose parameter is of type const B&, const volatile B& or B,
7779 // and
7780 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7781 BaseEnd = ClassDecl->bases_end();
7782 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007783 // We'll handle this below
7784 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7785 continue;
7786
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007787 assert(!Base->getType()->isDependentType() &&
7788 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007789 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7790 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7791 &HasConstCopyAssignment);
7792 }
7793
Richard Smith0bf8a4922011-10-18 20:49:44 +00007794 // In C++11, the above citation has "or virtual" added
Alexis Hunt491ec602011-06-21 23:42:56 +00007795 if (LangOpts.CPlusPlus0x) {
7796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7797 BaseEnd = ClassDecl->vbases_end();
7798 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7799 assert(!Base->getType()->isDependentType() &&
7800 "Cannot generate implicit members for class with dependent bases.");
7801 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7802 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7803 &HasConstCopyAssignment);
7804 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007805 }
7806
7807 // -- for all the nonstatic data members of X that are of a class
7808 // type M (or array thereof), each such class type has a copy
7809 // assignment operator whose parameter is of type const M&,
7810 // const volatile M& or M.
7811 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7812 FieldEnd = ClassDecl->field_end();
7813 HasConstCopyAssignment && Field != FieldEnd;
7814 ++Field) {
7815 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007816 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7817 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7818 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007819 }
7820 }
7821
7822 // Otherwise, the implicitly declared copy assignment operator will
7823 // have the form
7824 //
7825 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007826
Douglas Gregor68e11362010-07-01 17:48:08 +00007827 // C++ [except.spec]p14:
7828 // An implicitly declared special member function (Clause 12) shall have an
7829 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007830
7831 // It is unspecified whether or not an implicit copy assignment operator
7832 // attempts to deduplicate calls to assignment operators of virtual bases are
7833 // made. As such, this exception specification is effectively unspecified.
7834 // Based on a similar decision made for constness in C++0x, we're erring on
7835 // the side of assuming such calls to be made regardless of whether they
7836 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007837 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007838 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007839 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7840 BaseEnd = ClassDecl->bases_end();
7841 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007842 if (Base->isVirtual())
7843 continue;
7844
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007845 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007846 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007847 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7848 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007849 ExceptSpec.CalledDecl(CopyAssign);
7850 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007851
7852 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7853 BaseEnd = ClassDecl->vbases_end();
7854 Base != BaseEnd; ++Base) {
7855 CXXRecordDecl *BaseClassDecl
7856 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7857 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7858 ArgQuals, false, 0))
7859 ExceptSpec.CalledDecl(CopyAssign);
7860 }
7861
Douglas Gregor68e11362010-07-01 17:48:08 +00007862 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7863 FieldEnd = ClassDecl->field_end();
7864 Field != FieldEnd;
7865 ++Field) {
7866 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007867 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7868 if (CXXMethodDecl *CopyAssign =
7869 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7870 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007871 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007872 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007873
Alexis Hunt119f3652011-05-14 05:23:20 +00007874 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7875}
7876
7877CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7878 // Note: The following rules are largely analoguous to the copy
7879 // constructor rules. Note that virtual bases are not taken into account
7880 // for determining the argument type of the operator. Note also that
7881 // operators taking an object instead of a reference are allowed.
7882
7883 ImplicitExceptionSpecification Spec(Context);
7884 bool Const;
7885 llvm::tie(Spec, Const) =
7886 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7887
7888 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7889 QualType RetType = Context.getLValueReferenceType(ArgType);
7890 if (Const)
7891 ArgType = ArgType.withConst();
7892 ArgType = Context.getLValueReferenceType(ArgType);
7893
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007894 // An implicitly-declared copy assignment operator is an inline public
7895 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007896 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007897 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007898 SourceLocation ClassLoc = ClassDecl->getLocation();
7899 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007900 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007901 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007902 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007903 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007904 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007905 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007906 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007907 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007908 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007909 CopyAssignment->setImplicit();
7910 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007911
7912 // Add the parameter to the operator.
7913 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007914 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007915 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007916 SC_None,
7917 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007918 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007919
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007920 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007921 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007922
Douglas Gregor0be31a22010-07-02 17:43:08 +00007923 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007924 PushOnScopeChains(CopyAssignment, S, false);
7925 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007926
Nico Weber94e746d2012-01-23 03:19:29 +00007927 // C++0x [class.copy]p19:
7928 // .... If the class definition does not explicitly declare a copy
7929 // assignment operator, there is no user-declared move constructor, and
7930 // there is no user-declared move assignment operator, a copy assignment
7931 // operator is implicitly declared as defaulted.
7932 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber323076f2012-01-23 04:01:33 +00007933 !getLangOptions().MicrosoftMode) ||
7934 ClassDecl->hasUserDeclaredMoveAssignment() ||
Alexis Huntd74c85f2011-06-22 01:05:13 +00007935 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007936 CopyAssignment->setDeletedAsWritten();
7937
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007938 AddOverriddenMethods(ClassDecl, CopyAssignment);
7939 return CopyAssignment;
7940}
7941
Douglas Gregorb139cd52010-05-01 20:49:11 +00007942void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7943 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007944 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007945 CopyAssignOperator->isOverloadedOperator() &&
7946 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007947 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007948 "DefineImplicitCopyAssignment called for wrong function");
7949
7950 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7951
7952 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7953 CopyAssignOperator->setInvalidDecl();
7954 return;
7955 }
7956
7957 CopyAssignOperator->setUsed();
7958
7959 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007960 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007961
7962 // C++0x [class.copy]p30:
7963 // The implicitly-defined or explicitly-defaulted copy assignment operator
7964 // for a non-union class X performs memberwise copy assignment of its
7965 // subobjects. The direct base classes of X are assigned first, in the
7966 // order of their declaration in the base-specifier-list, and then the
7967 // immediate non-static data members of X are assigned, in the order in
7968 // which they were declared in the class definition.
7969
7970 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007971 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007972
7973 // The parameter for the "other" object, which we are copying from.
7974 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7975 Qualifiers OtherQuals = Other->getType().getQualifiers();
7976 QualType OtherRefType = Other->getType();
7977 if (const LValueReferenceType *OtherRef
7978 = OtherRefType->getAs<LValueReferenceType>()) {
7979 OtherRefType = OtherRef->getPointeeType();
7980 OtherQuals = OtherRefType.getQualifiers();
7981 }
7982
7983 // Our location for everything implicitly-generated.
7984 SourceLocation Loc = CopyAssignOperator->getLocation();
7985
7986 // Construct a reference to the "other" object. We'll be using this
7987 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007988 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007989 assert(OtherRef && "Reference to parameter cannot fail!");
7990
7991 // Construct the "this" pointer. We'll be using this throughout the generated
7992 // ASTs.
7993 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7994 assert(This && "Reference to this cannot fail!");
7995
7996 // Assign base classes.
7997 bool Invalid = false;
7998 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7999 E = ClassDecl->bases_end(); Base != E; ++Base) {
8000 // Form the assignment:
8001 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8002 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008003 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008004 Invalid = true;
8005 continue;
8006 }
8007
John McCallcf142162010-08-07 06:22:56 +00008008 CXXCastPath BasePath;
8009 BasePath.push_back(Base);
8010
Douglas Gregorb139cd52010-05-01 20:49:11 +00008011 // Construct the "from" expression, which is an implicit cast to the
8012 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00008013 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00008014 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8015 CK_UncheckedDerivedToBase,
8016 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008017
8018 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00008019 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008020
8021 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00008022 To = ImpCastExprToType(To.take(),
8023 Context.getCVRQualifiedType(BaseType,
8024 CopyAssignOperator->getTypeQualifiers()),
8025 CK_UncheckedDerivedToBase,
8026 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008027
8028 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00008029 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00008030 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008031 /*CopyingBaseSubobject=*/true,
8032 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008033 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008034 Diag(CurrentLocation, diag::note_member_synthesized_at)
8035 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8036 CopyAssignOperator->setInvalidDecl();
8037 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008038 }
8039
8040 // Success! Record the copy.
8041 Statements.push_back(Copy.takeAs<Expr>());
8042 }
8043
8044 // \brief Reference to the __builtin_memcpy function.
8045 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008046 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008047 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008048
8049 // Assign non-static members.
8050 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8051 FieldEnd = ClassDecl->field_end();
8052 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008053 if (Field->isUnnamedBitfield())
8054 continue;
8055
Douglas Gregorb139cd52010-05-01 20:49:11 +00008056 // Check for members of reference type; we can't copy those.
8057 if (Field->getType()->isReferenceType()) {
8058 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8059 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8060 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008061 Diag(CurrentLocation, diag::note_member_synthesized_at)
8062 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008063 Invalid = true;
8064 continue;
8065 }
8066
8067 // Check for members of const-qualified, non-class type.
8068 QualType BaseType = Context.getBaseElementType(Field->getType());
8069 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8071 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8072 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008073 Diag(CurrentLocation, diag::note_member_synthesized_at)
8074 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008075 Invalid = true;
8076 continue;
8077 }
John McCall1b1a1db2011-06-17 00:18:42 +00008078
8079 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008080 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8081 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008082
8083 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008084 if (FieldType->isIncompleteArrayType()) {
8085 assert(ClassDecl->hasFlexibleArrayMember() &&
8086 "Incomplete array type is not valid");
8087 continue;
8088 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008089
8090 // Build references to the field in the object we're copying from and to.
8091 CXXScopeSpec SS; // Intentionally empty
8092 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8093 LookupMemberName);
8094 MemberLookup.addDecl(*Field);
8095 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00008096 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00008097 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008098 SS, SourceLocation(), 0,
8099 MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00008100 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00008101 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008102 SS, SourceLocation(), 0,
8103 MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008104 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8105 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8106
8107 // If the field should be copied with __builtin_memcpy rather than via
8108 // explicit assignments, do so. This optimization only applies for arrays
8109 // of scalars and arrays of class type with trivial copy-assignment
8110 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00008111 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00008112 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008113 // Compute the size of the memory buffer to be copied.
8114 QualType SizeType = Context.getSizeType();
8115 llvm::APInt Size(Context.getTypeSize(SizeType),
8116 Context.getTypeSizeInChars(BaseType).getQuantity());
8117 for (const ConstantArrayType *Array
8118 = Context.getAsConstantArrayType(FieldType);
8119 Array;
8120 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00008121 llvm::APInt ArraySize
8122 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008123 Size *= ArraySize;
8124 }
8125
8126 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00008127 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8128 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008129
8130 bool NeedsCollectableMemCpy =
8131 (BaseType->isRecordType() &&
8132 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8133
8134 if (NeedsCollectableMemCpy) {
8135 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008136 // Create a reference to the __builtin_objc_memmove_collectable function.
8137 LookupResult R(*this,
8138 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008139 Loc, LookupOrdinaryName);
8140 LookupName(R, TUScope, true);
8141
8142 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8143 if (!CollectableMemCpy) {
8144 // Something went horribly wrong earlier, and we will have
8145 // complained about it.
8146 Invalid = true;
8147 continue;
8148 }
8149
8150 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8151 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008152 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008153 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8154 }
8155 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008156 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008157 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008158 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8159 LookupOrdinaryName);
8160 LookupName(R, TUScope, true);
8161
8162 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8163 if (!BuiltinMemCpy) {
8164 // Something went horribly wrong earlier, and we will have complained
8165 // about it.
8166 Invalid = true;
8167 continue;
8168 }
8169
8170 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8171 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008172 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008173 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8174 }
8175
John McCall37ad5512010-08-23 06:44:23 +00008176 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008177 CallArgs.push_back(To.takeAs<Expr>());
8178 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008179 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008180 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008181 if (NeedsCollectableMemCpy)
8182 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008183 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008184 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008185 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008186 else
8187 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008188 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008189 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008190 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008191
Douglas Gregorb139cd52010-05-01 20:49:11 +00008192 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8193 Statements.push_back(Call.takeAs<Expr>());
8194 continue;
8195 }
8196
8197 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008198 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008199 To.get(), From.get(),
8200 /*CopyingBaseSubobject=*/false,
8201 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008202 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008203 Diag(CurrentLocation, diag::note_member_synthesized_at)
8204 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8205 CopyAssignOperator->setInvalidDecl();
8206 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008207 }
8208
8209 // Success! Record the copy.
8210 Statements.push_back(Copy.takeAs<Stmt>());
8211 }
8212
8213 if (!Invalid) {
8214 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008215 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008216
John McCalldadc5752010-08-24 06:29:42 +00008217 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008218 if (Return.isInvalid())
8219 Invalid = true;
8220 else {
8221 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008222
8223 if (Trap.hasErrorOccurred()) {
8224 Diag(CurrentLocation, diag::note_member_synthesized_at)
8225 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8226 Invalid = true;
8227 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008228 }
8229 }
8230
8231 if (Invalid) {
8232 CopyAssignOperator->setInvalidDecl();
8233 return;
8234 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008235
8236 StmtResult Body;
8237 {
8238 CompoundScopeRAII CompoundScope(*this);
8239 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8240 /*isStmtExpr=*/false);
8241 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8242 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008243 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008244
8245 if (ASTMutationListener *L = getASTMutationListener()) {
8246 L->CompletedImplicitDefinition(CopyAssignOperator);
8247 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008248}
8249
Sebastian Redl22653ba2011-08-30 19:58:05 +00008250Sema::ImplicitExceptionSpecification
8251Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8252 ImplicitExceptionSpecification ExceptSpec(Context);
8253
8254 if (ClassDecl->isInvalidDecl())
8255 return ExceptSpec;
8256
8257 // C++0x [except.spec]p14:
8258 // An implicitly declared special member function (Clause 12) shall have an
8259 // exception-specification. [...]
8260
8261 // It is unspecified whether or not an implicit move assignment operator
8262 // attempts to deduplicate calls to assignment operators of virtual bases are
8263 // made. As such, this exception specification is effectively unspecified.
8264 // Based on a similar decision made for constness in C++0x, we're erring on
8265 // the side of assuming such calls to be made regardless of whether they
8266 // actually happen.
8267 // Note that a move constructor is not implicitly declared when there are
8268 // virtual bases, but it can still be user-declared and explicitly defaulted.
8269 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8270 BaseEnd = ClassDecl->bases_end();
8271 Base != BaseEnd; ++Base) {
8272 if (Base->isVirtual())
8273 continue;
8274
8275 CXXRecordDecl *BaseClassDecl
8276 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8277 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8278 false, 0))
8279 ExceptSpec.CalledDecl(MoveAssign);
8280 }
8281
8282 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8283 BaseEnd = ClassDecl->vbases_end();
8284 Base != BaseEnd; ++Base) {
8285 CXXRecordDecl *BaseClassDecl
8286 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8287 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8288 false, 0))
8289 ExceptSpec.CalledDecl(MoveAssign);
8290 }
8291
8292 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8293 FieldEnd = ClassDecl->field_end();
8294 Field != FieldEnd;
8295 ++Field) {
8296 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8297 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8298 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8299 false, 0))
8300 ExceptSpec.CalledDecl(MoveAssign);
8301 }
8302 }
8303
8304 return ExceptSpec;
8305}
8306
8307CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8308 // Note: The following rules are largely analoguous to the move
8309 // constructor rules.
8310
8311 ImplicitExceptionSpecification Spec(
8312 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8313
8314 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8315 QualType RetType = Context.getLValueReferenceType(ArgType);
8316 ArgType = Context.getRValueReferenceType(ArgType);
8317
8318 // An implicitly-declared move assignment operator is an inline public
8319 // member of its class.
8320 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8321 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8322 SourceLocation ClassLoc = ClassDecl->getLocation();
8323 DeclarationNameInfo NameInfo(Name, ClassLoc);
8324 CXXMethodDecl *MoveAssignment
8325 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8326 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8327 /*TInfo=*/0, /*isStatic=*/false,
8328 /*StorageClassAsWritten=*/SC_None,
8329 /*isInline=*/true,
8330 /*isConstexpr=*/false,
8331 SourceLocation());
8332 MoveAssignment->setAccess(AS_public);
8333 MoveAssignment->setDefaulted();
8334 MoveAssignment->setImplicit();
8335 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8336
8337 // Add the parameter to the operator.
8338 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8339 ClassLoc, ClassLoc, /*Id=*/0,
8340 ArgType, /*TInfo=*/0,
8341 SC_None,
8342 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008343 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008344
8345 // Note that we have added this copy-assignment operator.
8346 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8347
8348 // C++0x [class.copy]p9:
8349 // If the definition of a class X does not explicitly declare a move
8350 // assignment operator, one will be implicitly declared as defaulted if and
8351 // only if:
8352 // [...]
8353 // - the move assignment operator would not be implicitly defined as
8354 // deleted.
8355 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8356 // Cache this result so that we don't try to generate this over and over
8357 // on every lookup, leaking memory and wasting time.
8358 ClassDecl->setFailedImplicitMoveAssignment();
8359 return 0;
8360 }
8361
8362 if (Scope *S = getScopeForContext(ClassDecl))
8363 PushOnScopeChains(MoveAssignment, S, false);
8364 ClassDecl->addDecl(MoveAssignment);
8365
8366 AddOverriddenMethods(ClassDecl, MoveAssignment);
8367 return MoveAssignment;
8368}
8369
8370void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8371 CXXMethodDecl *MoveAssignOperator) {
8372 assert((MoveAssignOperator->isDefaulted() &&
8373 MoveAssignOperator->isOverloadedOperator() &&
8374 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8375 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8376 "DefineImplicitMoveAssignment called for wrong function");
8377
8378 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8379
8380 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8381 MoveAssignOperator->setInvalidDecl();
8382 return;
8383 }
8384
8385 MoveAssignOperator->setUsed();
8386
8387 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8388 DiagnosticErrorTrap Trap(Diags);
8389
8390 // C++0x [class.copy]p28:
8391 // The implicitly-defined or move assignment operator for a non-union class
8392 // X performs memberwise move assignment of its subobjects. The direct base
8393 // classes of X are assigned first, in the order of their declaration in the
8394 // base-specifier-list, and then the immediate non-static data members of X
8395 // are assigned, in the order in which they were declared in the class
8396 // definition.
8397
8398 // The statements that form the synthesized function body.
8399 ASTOwningVector<Stmt*> Statements(*this);
8400
8401 // The parameter for the "other" object, which we are move from.
8402 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8403 QualType OtherRefType = Other->getType()->
8404 getAs<RValueReferenceType>()->getPointeeType();
8405 assert(OtherRefType.getQualifiers() == 0 &&
8406 "Bad argument type of defaulted move assignment");
8407
8408 // Our location for everything implicitly-generated.
8409 SourceLocation Loc = MoveAssignOperator->getLocation();
8410
8411 // Construct a reference to the "other" object. We'll be using this
8412 // throughout the generated ASTs.
8413 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8414 assert(OtherRef && "Reference to parameter cannot fail!");
8415 // Cast to rvalue.
8416 OtherRef = CastForMoving(*this, OtherRef);
8417
8418 // Construct the "this" pointer. We'll be using this throughout the generated
8419 // ASTs.
8420 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8421 assert(This && "Reference to this cannot fail!");
8422
8423 // Assign base classes.
8424 bool Invalid = false;
8425 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8426 E = ClassDecl->bases_end(); Base != E; ++Base) {
8427 // Form the assignment:
8428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8429 QualType BaseType = Base->getType().getUnqualifiedType();
8430 if (!BaseType->isRecordType()) {
8431 Invalid = true;
8432 continue;
8433 }
8434
8435 CXXCastPath BasePath;
8436 BasePath.push_back(Base);
8437
8438 // Construct the "from" expression, which is an implicit cast to the
8439 // appropriately-qualified base type.
8440 Expr *From = OtherRef;
8441 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008442 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008443
8444 // Dereference "this".
8445 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8446
8447 // Implicitly cast "this" to the appropriately-qualified base type.
8448 To = ImpCastExprToType(To.take(),
8449 Context.getCVRQualifiedType(BaseType,
8450 MoveAssignOperator->getTypeQualifiers()),
8451 CK_UncheckedDerivedToBase,
8452 VK_LValue, &BasePath);
8453
8454 // Build the move.
8455 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8456 To.get(), From,
8457 /*CopyingBaseSubobject=*/true,
8458 /*Copying=*/false);
8459 if (Move.isInvalid()) {
8460 Diag(CurrentLocation, diag::note_member_synthesized_at)
8461 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8462 MoveAssignOperator->setInvalidDecl();
8463 return;
8464 }
8465
8466 // Success! Record the move.
8467 Statements.push_back(Move.takeAs<Expr>());
8468 }
8469
8470 // \brief Reference to the __builtin_memcpy function.
8471 Expr *BuiltinMemCpyRef = 0;
8472 // \brief Reference to the __builtin_objc_memmove_collectable function.
8473 Expr *CollectableMemCpyRef = 0;
8474
8475 // Assign non-static members.
8476 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8477 FieldEnd = ClassDecl->field_end();
8478 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008479 if (Field->isUnnamedBitfield())
8480 continue;
8481
Sebastian Redl22653ba2011-08-30 19:58:05 +00008482 // Check for members of reference type; we can't move those.
8483 if (Field->getType()->isReferenceType()) {
8484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8486 Diag(Field->getLocation(), diag::note_declared_at);
8487 Diag(CurrentLocation, diag::note_member_synthesized_at)
8488 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8489 Invalid = true;
8490 continue;
8491 }
8492
8493 // Check for members of const-qualified, non-class type.
8494 QualType BaseType = Context.getBaseElementType(Field->getType());
8495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8498 Diag(Field->getLocation(), diag::note_declared_at);
8499 Diag(CurrentLocation, diag::note_member_synthesized_at)
8500 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8501 Invalid = true;
8502 continue;
8503 }
8504
8505 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008506 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8507 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00008508
8509 QualType FieldType = Field->getType().getNonReferenceType();
8510 if (FieldType->isIncompleteArrayType()) {
8511 assert(ClassDecl->hasFlexibleArrayMember() &&
8512 "Incomplete array type is not valid");
8513 continue;
8514 }
8515
8516 // Build references to the field in the object we're copying from and to.
8517 CXXScopeSpec SS; // Intentionally empty
8518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8519 LookupMemberName);
8520 MemberLookup.addDecl(*Field);
8521 MemberLookup.resolveKind();
8522 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8523 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008524 SS, SourceLocation(), 0,
8525 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008526 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8527 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008528 SS, SourceLocation(), 0,
8529 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008530 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8531 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8532
8533 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8534 "Member reference with rvalue base must be rvalue except for reference "
8535 "members, which aren't allowed for move assignment.");
8536
8537 // If the field should be copied with __builtin_memcpy rather than via
8538 // explicit assignments, do so. This optimization only applies for arrays
8539 // of scalars and arrays of class type with trivial move-assignment
8540 // operators.
8541 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8542 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8543 // Compute the size of the memory buffer to be copied.
8544 QualType SizeType = Context.getSizeType();
8545 llvm::APInt Size(Context.getTypeSize(SizeType),
8546 Context.getTypeSizeInChars(BaseType).getQuantity());
8547 for (const ConstantArrayType *Array
8548 = Context.getAsConstantArrayType(FieldType);
8549 Array;
8550 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8551 llvm::APInt ArraySize
8552 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8553 Size *= ArraySize;
8554 }
8555
Douglas Gregor528499b2011-09-01 02:09:07 +00008556 // Take the address of the field references for "from" and "to". We
8557 // directly construct UnaryOperators here because semantic analysis
8558 // does not permit us to take the address of an xvalue.
8559 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8560 Context.getPointerType(From.get()->getType()),
8561 VK_RValue, OK_Ordinary, Loc);
8562 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8563 Context.getPointerType(To.get()->getType()),
8564 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008565
8566 bool NeedsCollectableMemCpy =
8567 (BaseType->isRecordType() &&
8568 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8569
8570 if (NeedsCollectableMemCpy) {
8571 if (!CollectableMemCpyRef) {
8572 // Create a reference to the __builtin_objc_memmove_collectable function.
8573 LookupResult R(*this,
8574 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8575 Loc, LookupOrdinaryName);
8576 LookupName(R, TUScope, true);
8577
8578 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8579 if (!CollectableMemCpy) {
8580 // Something went horribly wrong earlier, and we will have
8581 // complained about it.
8582 Invalid = true;
8583 continue;
8584 }
8585
8586 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8587 CollectableMemCpy->getType(),
8588 VK_LValue, Loc, 0).take();
8589 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8590 }
8591 }
8592 // Create a reference to the __builtin_memcpy builtin function.
8593 else if (!BuiltinMemCpyRef) {
8594 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8595 LookupOrdinaryName);
8596 LookupName(R, TUScope, true);
8597
8598 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8599 if (!BuiltinMemCpy) {
8600 // Something went horribly wrong earlier, and we will have complained
8601 // about it.
8602 Invalid = true;
8603 continue;
8604 }
8605
8606 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8607 BuiltinMemCpy->getType(),
8608 VK_LValue, Loc, 0).take();
8609 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8610 }
8611
8612 ASTOwningVector<Expr*> CallArgs(*this);
8613 CallArgs.push_back(To.takeAs<Expr>());
8614 CallArgs.push_back(From.takeAs<Expr>());
8615 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8616 ExprResult Call = ExprError();
8617 if (NeedsCollectableMemCpy)
8618 Call = ActOnCallExpr(/*Scope=*/0,
8619 CollectableMemCpyRef,
8620 Loc, move_arg(CallArgs),
8621 Loc);
8622 else
8623 Call = ActOnCallExpr(/*Scope=*/0,
8624 BuiltinMemCpyRef,
8625 Loc, move_arg(CallArgs),
8626 Loc);
8627
8628 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8629 Statements.push_back(Call.takeAs<Expr>());
8630 continue;
8631 }
8632
8633 // Build the move of this field.
8634 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8635 To.get(), From.get(),
8636 /*CopyingBaseSubobject=*/false,
8637 /*Copying=*/false);
8638 if (Move.isInvalid()) {
8639 Diag(CurrentLocation, diag::note_member_synthesized_at)
8640 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8641 MoveAssignOperator->setInvalidDecl();
8642 return;
8643 }
8644
8645 // Success! Record the copy.
8646 Statements.push_back(Move.takeAs<Stmt>());
8647 }
8648
8649 if (!Invalid) {
8650 // Add a "return *this;"
8651 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8652
8653 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8654 if (Return.isInvalid())
8655 Invalid = true;
8656 else {
8657 Statements.push_back(Return.takeAs<Stmt>());
8658
8659 if (Trap.hasErrorOccurred()) {
8660 Diag(CurrentLocation, diag::note_member_synthesized_at)
8661 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8662 Invalid = true;
8663 }
8664 }
8665 }
8666
8667 if (Invalid) {
8668 MoveAssignOperator->setInvalidDecl();
8669 return;
8670 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008671
8672 StmtResult Body;
8673 {
8674 CompoundScopeRAII CompoundScope(*this);
8675 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8676 /*isStmtExpr=*/false);
8677 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8678 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00008679 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8680
8681 if (ASTMutationListener *L = getASTMutationListener()) {
8682 L->CompletedImplicitDefinition(MoveAssignOperator);
8683 }
8684}
8685
Alexis Hunt913820d2011-05-13 06:10:58 +00008686std::pair<Sema::ImplicitExceptionSpecification, bool>
8687Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008688 if (ClassDecl->isInvalidDecl())
8689 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8690
Douglas Gregor54be3392010-07-01 17:57:27 +00008691 // C++ [class.copy]p5:
8692 // The implicitly-declared copy constructor for a class X will
8693 // have the form
8694 //
8695 // X::X(const X&)
8696 //
8697 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008698 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008699 bool HasConstCopyConstructor = true;
8700
8701 // -- each direct or virtual base class B of X has a copy
8702 // constructor whose first parameter is of type const B& or
8703 // const volatile B&, and
8704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8705 BaseEnd = ClassDecl->bases_end();
8706 HasConstCopyConstructor && Base != BaseEnd;
8707 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008708 // Virtual bases are handled below.
8709 if (Base->isVirtual())
8710 continue;
8711
Douglas Gregora6d69502010-07-02 23:41:54 +00008712 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008713 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008714 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8715 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008716 }
8717
8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8719 BaseEnd = ClassDecl->vbases_end();
8720 HasConstCopyConstructor && Base != BaseEnd;
8721 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008722 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008724 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8725 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008726 }
8727
8728 // -- for all the nonstatic data members of X that are of a
8729 // class type M (or array thereof), each such class type
8730 // has a copy constructor whose first parameter is of type
8731 // const M& or const volatile M&.
8732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8733 FieldEnd = ClassDecl->field_end();
8734 HasConstCopyConstructor && Field != FieldEnd;
8735 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008736 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008737 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008738 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8739 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008740 }
8741 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008742 // Otherwise, the implicitly declared copy constructor will have
8743 // the form
8744 //
8745 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008746
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008747 // C++ [except.spec]p14:
8748 // An implicitly declared special member function (Clause 12) shall have an
8749 // exception-specification. [...]
8750 ImplicitExceptionSpecification ExceptSpec(Context);
8751 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8753 BaseEnd = ClassDecl->bases_end();
8754 Base != BaseEnd;
8755 ++Base) {
8756 // Virtual bases are handled below.
8757 if (Base->isVirtual())
8758 continue;
8759
Douglas Gregora6d69502010-07-02 23:41:54 +00008760 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008761 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008762 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008763 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008764 ExceptSpec.CalledDecl(CopyConstructor);
8765 }
8766 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8767 BaseEnd = ClassDecl->vbases_end();
8768 Base != BaseEnd;
8769 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008770 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008771 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008772 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008773 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008774 ExceptSpec.CalledDecl(CopyConstructor);
8775 }
8776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8777 FieldEnd = ClassDecl->field_end();
8778 Field != FieldEnd;
8779 ++Field) {
8780 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008781 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8782 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008783 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008784 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008785 }
8786 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008787
Alexis Hunt913820d2011-05-13 06:10:58 +00008788 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8789}
8790
8791CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8792 CXXRecordDecl *ClassDecl) {
8793 // C++ [class.copy]p4:
8794 // If the class definition does not explicitly declare a copy
8795 // constructor, one is declared implicitly.
8796
8797 ImplicitExceptionSpecification Spec(Context);
8798 bool Const;
8799 llvm::tie(Spec, Const) =
8800 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8801
8802 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8803 QualType ArgType = ClassType;
8804 if (Const)
8805 ArgType = ArgType.withConst();
8806 ArgType = Context.getLValueReferenceType(ArgType);
8807
8808 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8809
Douglas Gregor54be3392010-07-01 17:57:27 +00008810 DeclarationName Name
8811 = Context.DeclarationNames.getCXXConstructorName(
8812 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008813 SourceLocation ClassLoc = ClassDecl->getLocation();
8814 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008815
8816 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008817 // member of its class.
8818 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8819 Context, ClassDecl, ClassLoc, NameInfo,
8820 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8822 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8823 getLangOptions().CPlusPlus0x);
Douglas Gregor54be3392010-07-01 17:57:27 +00008824 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008825 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008826 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008827
Douglas Gregora6d69502010-07-02 23:41:54 +00008828 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008829 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8830
Douglas Gregor54be3392010-07-01 17:57:27 +00008831 // Add the parameter to the constructor.
8832 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008833 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008834 /*IdentifierInfo=*/0,
8835 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008836 SC_None,
8837 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008838 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008839
Douglas Gregor0be31a22010-07-02 17:43:08 +00008840 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008841 PushOnScopeChains(CopyConstructor, S, false);
8842 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008843
Nico Weber94e746d2012-01-23 03:19:29 +00008844 // C++11 [class.copy]p8:
8845 // ... If the class definition does not explicitly declare a copy
8846 // constructor, there is no user-declared move constructor, and there is no
8847 // user-declared move assignment operator, a copy constructor is implicitly
8848 // declared as defaulted.
Alexis Huntd74c85f2011-06-22 01:05:13 +00008849 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weber94e746d2012-01-23 03:19:29 +00008850 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber323076f2012-01-23 04:01:33 +00008851 !getLangOptions().MicrosoftMode) ||
Alexis Hunt1bc6f712011-10-11 04:55:36 +00008852 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008853 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008854
8855 return CopyConstructor;
8856}
8857
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008858void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008859 CXXConstructorDecl *CopyConstructor) {
8860 assert((CopyConstructor->isDefaulted() &&
8861 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008862 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008863 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008864
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008865 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008866 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008867
Douglas Gregora57478e2010-05-01 15:04:51 +00008868 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008869 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008870
Alexis Hunt1d792652011-01-08 20:30:50 +00008871 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008872 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008873 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008874 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008875 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008876 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008877 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregor94f9a482010-05-05 05:51:00 +00008878 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8879 CopyConstructor->getLocation(),
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008880 MultiStmtArg(*this, 0, 0),
Douglas Gregor94f9a482010-05-05 05:51:00 +00008881 /*isStmtExpr=*/false)
8882 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008883 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008884 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008885
8886 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008887 if (ASTMutationListener *L = getASTMutationListener()) {
8888 L->CompletedImplicitDefinition(CopyConstructor);
8889 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008890}
8891
Sebastian Redl22653ba2011-08-30 19:58:05 +00008892Sema::ImplicitExceptionSpecification
8893Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8894 // C++ [except.spec]p14:
8895 // An implicitly declared special member function (Clause 12) shall have an
8896 // exception-specification. [...]
8897 ImplicitExceptionSpecification ExceptSpec(Context);
8898 if (ClassDecl->isInvalidDecl())
8899 return ExceptSpec;
8900
8901 // Direct base-class constructors.
8902 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8903 BEnd = ClassDecl->bases_end();
8904 B != BEnd; ++B) {
8905 if (B->isVirtual()) // Handled below.
8906 continue;
8907
8908 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8909 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8910 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8911 // If this is a deleted function, add it anyway. This might be conformant
8912 // with the standard. This might not. I'm not sure. It might not matter.
8913 if (Constructor)
8914 ExceptSpec.CalledDecl(Constructor);
8915 }
8916 }
8917
8918 // Virtual base-class constructors.
8919 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8920 BEnd = ClassDecl->vbases_end();
8921 B != BEnd; ++B) {
8922 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8923 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8924 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8925 // If this is a deleted function, add it anyway. This might be conformant
8926 // with the standard. This might not. I'm not sure. It might not matter.
8927 if (Constructor)
8928 ExceptSpec.CalledDecl(Constructor);
8929 }
8930 }
8931
8932 // Field constructors.
8933 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8934 FEnd = ClassDecl->field_end();
8935 F != FEnd; ++F) {
Douglas Gregor7db3e952011-11-28 20:03:15 +00008936 if (const RecordType *RecordTy
Sebastian Redl22653ba2011-08-30 19:58:05 +00008937 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8938 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8939 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8940 // If this is a deleted function, add it anyway. This might be conformant
8941 // with the standard. This might not. I'm not sure. It might not matter.
8942 // In particular, the problem is that this function never gets called. It
8943 // might just be ill-formed because this function attempts to refer to
8944 // a deleted function here.
8945 if (Constructor)
8946 ExceptSpec.CalledDecl(Constructor);
8947 }
8948 }
8949
8950 return ExceptSpec;
8951}
8952
8953CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8954 CXXRecordDecl *ClassDecl) {
8955 ImplicitExceptionSpecification Spec(
8956 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8957
8958 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8959 QualType ArgType = Context.getRValueReferenceType(ClassType);
8960
8961 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8962
8963 DeclarationName Name
8964 = Context.DeclarationNames.getCXXConstructorName(
8965 Context.getCanonicalType(ClassType));
8966 SourceLocation ClassLoc = ClassDecl->getLocation();
8967 DeclarationNameInfo NameInfo(Name, ClassLoc);
8968
8969 // C++0x [class.copy]p11:
8970 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008971 // member of its class.
8972 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8973 Context, ClassDecl, ClassLoc, NameInfo,
8974 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8975 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8976 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8977 getLangOptions().CPlusPlus0x);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008978 MoveConstructor->setAccess(AS_public);
8979 MoveConstructor->setDefaulted();
8980 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008981
Sebastian Redl22653ba2011-08-30 19:58:05 +00008982 // Add the parameter to the constructor.
8983 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8984 ClassLoc, ClassLoc,
8985 /*IdentifierInfo=*/0,
8986 ArgType, /*TInfo=*/0,
8987 SC_None,
8988 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008989 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008990
8991 // C++0x [class.copy]p9:
8992 // If the definition of a class X does not explicitly declare a move
8993 // constructor, one will be implicitly declared as defaulted if and only if:
8994 // [...]
8995 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00008996 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00008997 // Cache this result so that we don't try to generate this over and over
8998 // on every lookup, leaking memory and wasting time.
8999 ClassDecl->setFailedImplicitMoveConstructor();
9000 return 0;
9001 }
9002
9003 // Note that we have declared this constructor.
9004 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9005
9006 if (Scope *S = getScopeForContext(ClassDecl))
9007 PushOnScopeChains(MoveConstructor, S, false);
9008 ClassDecl->addDecl(MoveConstructor);
9009
9010 return MoveConstructor;
9011}
9012
9013void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9014 CXXConstructorDecl *MoveConstructor) {
9015 assert((MoveConstructor->isDefaulted() &&
9016 MoveConstructor->isMoveConstructor() &&
9017 !MoveConstructor->doesThisDeclarationHaveABody()) &&
9018 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9019
9020 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9021 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9022
9023 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
9024 DiagnosticErrorTrap Trap(Diags);
9025
9026 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9027 Trap.hasErrorOccurred()) {
9028 Diag(CurrentLocation, diag::note_member_synthesized_at)
9029 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9030 MoveConstructor->setInvalidDecl();
9031 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009032 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009033 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9034 MoveConstructor->getLocation(),
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009035 MultiStmtArg(*this, 0, 0),
Sebastian Redl22653ba2011-08-30 19:58:05 +00009036 /*isStmtExpr=*/false)
9037 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00009038 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009039 }
9040
9041 MoveConstructor->setUsed();
9042
9043 if (ASTMutationListener *L = getASTMutationListener()) {
9044 L->CompletedImplicitDefinition(MoveConstructor);
9045 }
9046}
9047
John McCalldadc5752010-08-24 06:29:42 +00009048ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009049Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00009050 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009051 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009052 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009053 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009054 unsigned ConstructKind,
9055 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00009056 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00009057
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009058 // C++0x [class.copy]p34:
9059 // When certain criteria are met, an implementation is allowed to
9060 // omit the copy/move construction of a class object, even if the
9061 // copy/move constructor and/or destructor for the object have
9062 // side effects. [...]
9063 // - when a temporary class object that has not been bound to a
9064 // reference (12.2) would be copied/moved to a class object
9065 // with the same cv-unqualified type, the copy/move operation
9066 // can be omitted by constructing the temporary object
9067 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00009068 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00009069 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009070 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00009071 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00009072 }
Mike Stump11289f42009-09-09 15:08:12 +00009073
9074 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009075 Elidable, move(ExprArgs), HadMultipleCandidates,
9076 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00009077}
9078
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009079/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9080/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00009081ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009082Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9083 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009084 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009085 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009086 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009087 unsigned ConstructKind,
9088 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00009089 unsigned NumExprs = ExprArgs.size();
9090 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00009091
Nick Lewyckyd4693212011-03-25 01:44:32 +00009092 for (specific_attr_iterator<NonNullAttr>
9093 i = Constructor->specific_attr_begin<NonNullAttr>(),
9094 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9095 const NonNullAttr *NonNull = *i;
9096 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9097 }
9098
Eli Friedmanfa0df832012-02-02 03:46:19 +00009099 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00009100 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009101 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redla9351792012-02-11 23:51:47 +00009102 HadMultipleCandidates, /*FIXME*/false,
9103 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009104 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9105 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009106}
9107
Mike Stump11289f42009-09-09 15:08:12 +00009108bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009109 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009110 MultiExprArg Exprs,
9111 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00009112 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00009113 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00009114 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009115 move(Exprs), HadMultipleCandidates, false,
9116 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009117 if (TempResult.isInvalid())
9118 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009119
Anders Carlsson6eb55572009-08-25 05:12:04 +00009120 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00009121 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009122 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00009123 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00009124 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00009125
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009126 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00009127}
9128
John McCall03c48482010-02-02 09:10:11 +00009129void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00009130 if (VD->isInvalidDecl()) return;
9131
John McCall03c48482010-02-02 09:10:11 +00009132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00009133 if (ClassDecl->isInvalidDecl()) return;
9134 if (ClassDecl->hasTrivialDestructor()) return;
9135 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00009136
Chandler Carruth86d17d32011-03-27 21:26:48 +00009137 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009138 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +00009139 CheckDestructorAccess(VD->getLocation(), Destructor,
9140 PDiag(diag::err_access_dtor_var)
9141 << VD->getDeclName()
9142 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00009143
Chandler Carruth86d17d32011-03-27 21:26:48 +00009144 if (!VD->hasGlobalStorage()) return;
9145
9146 // Emit warning for non-trivial dtor in global scope (a real global,
9147 // class-static, function-static).
9148 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9149
9150 // TODO: this should be re-enabled for static locals by !CXAAtExit
9151 if (!VD->isStaticLocal())
9152 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009153}
9154
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009155/// \brief Given a constructor and the set of arguments provided for the
9156/// constructor, convert the arguments and add any required default arguments
9157/// to form a proper call to this constructor.
9158///
9159/// \returns true if an error occurred, false otherwise.
9160bool
9161Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9162 MultiExprArg ArgsPtr,
9163 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009164 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009165 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9166 unsigned NumArgs = ArgsPtr.size();
9167 Expr **Args = (Expr **)ArgsPtr.get();
9168
9169 const FunctionProtoType *Proto
9170 = Constructor->getType()->getAs<FunctionProtoType>();
9171 assert(Proto && "Constructor without a prototype?");
9172 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009173
9174 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009175 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009176 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009177 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009178 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009179
9180 VariadicCallType CallType =
9181 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009182 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009183 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9184 Proto, 0, Args, NumArgs, AllArgs,
9185 CallType);
Benjamin Kramer8001f742012-02-14 12:06:21 +00009186 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009187 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009188}
9189
Anders Carlssone363c8e2009-12-12 00:32:00 +00009190static inline bool
9191CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9192 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009193 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009194 if (isa<NamespaceDecl>(DC)) {
9195 return SemaRef.Diag(FnDecl->getLocation(),
9196 diag::err_operator_new_delete_declared_in_namespace)
9197 << FnDecl->getDeclName();
9198 }
9199
9200 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009201 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009202 return SemaRef.Diag(FnDecl->getLocation(),
9203 diag::err_operator_new_delete_declared_static)
9204 << FnDecl->getDeclName();
9205 }
9206
Anders Carlsson60659a82009-12-12 02:43:16 +00009207 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009208}
9209
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009210static inline bool
9211CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9212 CanQualType ExpectedResultType,
9213 CanQualType ExpectedFirstParamType,
9214 unsigned DependentParamTypeDiag,
9215 unsigned InvalidParamTypeDiag) {
9216 QualType ResultType =
9217 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9218
9219 // Check that the result type is not dependent.
9220 if (ResultType->isDependentType())
9221 return SemaRef.Diag(FnDecl->getLocation(),
9222 diag::err_operator_new_delete_dependent_result_type)
9223 << FnDecl->getDeclName() << ExpectedResultType;
9224
9225 // Check that the result type is what we expect.
9226 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9227 return SemaRef.Diag(FnDecl->getLocation(),
9228 diag::err_operator_new_delete_invalid_result_type)
9229 << FnDecl->getDeclName() << ExpectedResultType;
9230
9231 // A function template must have at least 2 parameters.
9232 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9233 return SemaRef.Diag(FnDecl->getLocation(),
9234 diag::err_operator_new_delete_template_too_few_parameters)
9235 << FnDecl->getDeclName();
9236
9237 // The function decl must have at least 1 parameter.
9238 if (FnDecl->getNumParams() == 0)
9239 return SemaRef.Diag(FnDecl->getLocation(),
9240 diag::err_operator_new_delete_too_few_parameters)
9241 << FnDecl->getDeclName();
9242
9243 // Check the the first parameter type is not dependent.
9244 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9245 if (FirstParamType->isDependentType())
9246 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9247 << FnDecl->getDeclName() << ExpectedFirstParamType;
9248
9249 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009250 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009251 ExpectedFirstParamType)
9252 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9253 << FnDecl->getDeclName() << ExpectedFirstParamType;
9254
9255 return false;
9256}
9257
Anders Carlsson12308f42009-12-11 23:23:22 +00009258static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009259CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009260 // C++ [basic.stc.dynamic.allocation]p1:
9261 // A program is ill-formed if an allocation function is declared in a
9262 // namespace scope other than global scope or declared static in global
9263 // scope.
9264 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9265 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009266
9267 CanQualType SizeTy =
9268 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9269
9270 // C++ [basic.stc.dynamic.allocation]p1:
9271 // The return type shall be void*. The first parameter shall have type
9272 // std::size_t.
9273 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9274 SizeTy,
9275 diag::err_operator_new_dependent_param_type,
9276 diag::err_operator_new_param_type))
9277 return true;
9278
9279 // C++ [basic.stc.dynamic.allocation]p1:
9280 // The first parameter shall not have an associated default argument.
9281 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009282 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009283 diag::err_operator_new_default_arg)
9284 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9285
9286 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009287}
9288
9289static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009290CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9291 // C++ [basic.stc.dynamic.deallocation]p1:
9292 // A program is ill-formed if deallocation functions are declared in a
9293 // namespace scope other than global scope or declared static in global
9294 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009295 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9296 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009297
9298 // C++ [basic.stc.dynamic.deallocation]p2:
9299 // Each deallocation function shall return void and its first parameter
9300 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009301 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9302 SemaRef.Context.VoidPtrTy,
9303 diag::err_operator_delete_dependent_param_type,
9304 diag::err_operator_delete_param_type))
9305 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009306
Anders Carlsson12308f42009-12-11 23:23:22 +00009307 return false;
9308}
9309
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009310/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9311/// of this overloaded operator is well-formed. If so, returns false;
9312/// otherwise, emits appropriate diagnostics and returns true.
9313bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009314 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009315 "Expected an overloaded operator declaration");
9316
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009317 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9318
Mike Stump11289f42009-09-09 15:08:12 +00009319 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009320 // The allocation and deallocation functions, operator new,
9321 // operator new[], operator delete and operator delete[], are
9322 // described completely in 3.7.3. The attributes and restrictions
9323 // found in the rest of this subclause do not apply to them unless
9324 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009325 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009326 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009327
Anders Carlsson22f443f2009-12-12 00:26:23 +00009328 if (Op == OO_New || Op == OO_Array_New)
9329 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009330
9331 // C++ [over.oper]p6:
9332 // An operator function shall either be a non-static member
9333 // function or be a non-member function and have at least one
9334 // parameter whose type is a class, a reference to a class, an
9335 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009336 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9337 if (MethodDecl->isStatic())
9338 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009339 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009340 } else {
9341 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009342 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9343 ParamEnd = FnDecl->param_end();
9344 Param != ParamEnd; ++Param) {
9345 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009346 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9347 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009348 ClassOrEnumParam = true;
9349 break;
9350 }
9351 }
9352
Douglas Gregord69246b2008-11-17 16:14:12 +00009353 if (!ClassOrEnumParam)
9354 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009355 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009356 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009357 }
9358
9359 // C++ [over.oper]p8:
9360 // An operator function cannot have default arguments (8.3.6),
9361 // except where explicitly stated below.
9362 //
Mike Stump11289f42009-09-09 15:08:12 +00009363 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009364 // (C++ [over.call]p1).
9365 if (Op != OO_Call) {
9366 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9367 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009368 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009369 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009370 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009371 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009372 }
9373 }
9374
Douglas Gregor6cf08062008-11-10 13:38:07 +00009375 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9376 { false, false, false }
9377#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9378 , { Unary, Binary, MemberOnly }
9379#include "clang/Basic/OperatorKinds.def"
9380 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009381
Douglas Gregor6cf08062008-11-10 13:38:07 +00009382 bool CanBeUnaryOperator = OperatorUses[Op][0];
9383 bool CanBeBinaryOperator = OperatorUses[Op][1];
9384 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009385
9386 // C++ [over.oper]p8:
9387 // [...] Operator functions cannot have more or fewer parameters
9388 // than the number required for the corresponding operator, as
9389 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009390 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009391 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009392 if (Op != OO_Call &&
9393 ((NumParams == 1 && !CanBeUnaryOperator) ||
9394 (NumParams == 2 && !CanBeBinaryOperator) ||
9395 (NumParams < 1) || (NumParams > 2))) {
9396 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009397 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009398 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009399 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009400 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009401 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009402 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009403 assert(CanBeBinaryOperator &&
9404 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009405 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009406 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009407
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009408 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009409 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009410 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009411
Douglas Gregord69246b2008-11-17 16:14:12 +00009412 // Overloaded operators other than operator() cannot be variadic.
9413 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009414 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009415 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009416 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009417 }
9418
9419 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009420 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9421 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009422 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009423 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009424 }
9425
9426 // C++ [over.inc]p1:
9427 // The user-defined function called operator++ implements the
9428 // prefix and postfix ++ operator. If this function is a member
9429 // function with no parameters, or a non-member function with one
9430 // parameter of class or enumeration type, it defines the prefix
9431 // increment operator ++ for objects of that type. If the function
9432 // is a member function with one parameter (which shall be of type
9433 // int) or a non-member function with two parameters (the second
9434 // of which shall be of type int), it defines the postfix
9435 // increment operator ++ for objects of that type.
9436 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9437 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9438 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009439 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009440 ParamIsInt = BT->getKind() == BuiltinType::Int;
9441
Chris Lattner2b786902008-11-21 07:50:02 +00009442 if (!ParamIsInt)
9443 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009444 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009445 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009446 }
9447
Douglas Gregord69246b2008-11-17 16:14:12 +00009448 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009449}
Chris Lattner3b024a32008-12-17 07:09:26 +00009450
Alexis Huntc88db062010-01-13 09:01:02 +00009451/// CheckLiteralOperatorDeclaration - Check whether the declaration
9452/// of this literal operator function is well-formed. If so, returns
9453/// false; otherwise, emits appropriate diagnostics and returns true.
9454bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9455 DeclContext *DC = FnDecl->getDeclContext();
9456 Decl::Kind Kind = DC->getDeclKind();
9457 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9458 Kind != Decl::LinkageSpec) {
9459 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9460 << FnDecl->getDeclName();
9461 return true;
9462 }
9463
9464 bool Valid = false;
9465
Alexis Hunt7dd26172010-04-07 23:11:06 +00009466 // template <char...> type operator "" name() is the only valid template
9467 // signature, and the only valid signature with no parameters.
9468 if (FnDecl->param_size() == 0) {
9469 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9470 // Must have only one template parameter
9471 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9472 if (Params->size() == 1) {
9473 NonTypeTemplateParmDecl *PmDecl =
9474 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009475
Alexis Hunt7dd26172010-04-07 23:11:06 +00009476 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009477 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9478 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9479 Valid = true;
9480 }
9481 }
9482 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009483 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009484 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9485
Alexis Huntc88db062010-01-13 09:01:02 +00009486 QualType T = (*Param)->getType();
9487
Alexis Hunt079a6f72010-04-07 22:57:35 +00009488 // unsigned long long int, long double, and any character type are allowed
9489 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009490 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9491 Context.hasSameType(T, Context.LongDoubleTy) ||
9492 Context.hasSameType(T, Context.CharTy) ||
9493 Context.hasSameType(T, Context.WCharTy) ||
9494 Context.hasSameType(T, Context.Char16Ty) ||
9495 Context.hasSameType(T, Context.Char32Ty)) {
9496 if (++Param == FnDecl->param_end())
9497 Valid = true;
9498 goto FinishedParams;
9499 }
9500
Alexis Hunt079a6f72010-04-07 22:57:35 +00009501 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009502 const PointerType *PT = T->getAs<PointerType>();
9503 if (!PT)
9504 goto FinishedParams;
9505 T = PT->getPointeeType();
9506 if (!T.isConstQualified())
9507 goto FinishedParams;
9508 T = T.getUnqualifiedType();
9509
9510 // Move on to the second parameter;
9511 ++Param;
9512
9513 // If there is no second parameter, the first must be a const char *
9514 if (Param == FnDecl->param_end()) {
9515 if (Context.hasSameType(T, Context.CharTy))
9516 Valid = true;
9517 goto FinishedParams;
9518 }
9519
9520 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9521 // are allowed as the first parameter to a two-parameter function
9522 if (!(Context.hasSameType(T, Context.CharTy) ||
9523 Context.hasSameType(T, Context.WCharTy) ||
9524 Context.hasSameType(T, Context.Char16Ty) ||
9525 Context.hasSameType(T, Context.Char32Ty)))
9526 goto FinishedParams;
9527
9528 // The second and final parameter must be an std::size_t
9529 T = (*Param)->getType().getUnqualifiedType();
9530 if (Context.hasSameType(T, Context.getSizeType()) &&
9531 ++Param == FnDecl->param_end())
9532 Valid = true;
9533 }
9534
9535 // FIXME: This diagnostic is absolutely terrible.
9536FinishedParams:
9537 if (!Valid) {
9538 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9539 << FnDecl->getDeclName();
9540 return true;
9541 }
9542
Douglas Gregor86325ad2011-08-30 22:40:35 +00009543 StringRef LiteralName
9544 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9545 if (LiteralName[0] != '_') {
9546 // C++0x [usrlit.suffix]p1:
9547 // Literal suffix identifiers that do not start with an underscore are
9548 // reserved for future standardization.
9549 bool IsHexFloat = true;
9550 if (LiteralName.size() > 1 &&
9551 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9552 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9553 if (!isdigit(LiteralName[I])) {
9554 IsHexFloat = false;
9555 break;
9556 }
9557 }
9558 }
9559
9560 if (IsHexFloat)
9561 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9562 << LiteralName;
9563 else
9564 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9565 }
9566
Alexis Huntc88db062010-01-13 09:01:02 +00009567 return false;
9568}
9569
Douglas Gregor07665a62009-01-05 19:45:36 +00009570/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9571/// linkage specification, including the language and (if present)
9572/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9573/// the location of the language string literal, which is provided
9574/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9575/// the '{' brace. Otherwise, this linkage specification does not
9576/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009577Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9578 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009579 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009580 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009581 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009582 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009583 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009584 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009585 Language = LinkageSpecDecl::lang_cxx;
9586 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009587 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009588 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009589 }
Mike Stump11289f42009-09-09 15:08:12 +00009590
Chris Lattner438e5012008-12-17 07:13:27 +00009591 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009592
Douglas Gregor07665a62009-01-05 19:45:36 +00009593 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009594 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009595 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009596 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009597 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009598}
9599
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009600/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009601/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9602/// valid, it's the position of the closing '}' brace in a linkage
9603/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009604Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009605 Decl *LinkageSpec,
9606 SourceLocation RBraceLoc) {
9607 if (LinkageSpec) {
9608 if (RBraceLoc.isValid()) {
9609 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9610 LSDecl->setRBraceLoc(RBraceLoc);
9611 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009612 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009613 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009614 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009615}
9616
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009617/// \brief Perform semantic analysis for the variable declaration that
9618/// occurs within a C++ catch clause, returning the newly-created
9619/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009620VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009621 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009622 SourceLocation StartLoc,
9623 SourceLocation Loc,
9624 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009625 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009626 QualType ExDeclType = TInfo->getType();
9627
Sebastian Redl54c04d42008-12-22 19:15:10 +00009628 // Arrays and functions decay.
9629 if (ExDeclType->isArrayType())
9630 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9631 else if (ExDeclType->isFunctionType())
9632 ExDeclType = Context.getPointerType(ExDeclType);
9633
9634 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9635 // The exception-declaration shall not denote a pointer or reference to an
9636 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009637 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009638 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009639 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009640 Invalid = true;
9641 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009642
Sebastian Redl54c04d42008-12-22 19:15:10 +00009643 QualType BaseType = ExDeclType;
9644 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009645 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009646 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009647 BaseType = Ptr->getPointeeType();
9648 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009649 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00009650 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009651 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009652 BaseType = Ref->getPointeeType();
9653 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009654 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009655 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009656 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009657 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00009658 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009659
Mike Stump11289f42009-09-09 15:08:12 +00009660 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009661 RequireNonAbstractType(Loc, ExDeclType,
9662 diag::err_abstract_type_in_decl,
9663 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009664 Invalid = true;
9665
John McCall2ca705e2010-07-24 00:37:23 +00009666 // Only the non-fragile NeXT runtime currently supports C++ catches
9667 // of ObjC types, and no runtime supports catching ObjC types by value.
9668 if (!Invalid && getLangOptions().ObjC1) {
9669 QualType T = ExDeclType;
9670 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9671 T = RT->getPointeeType();
9672
9673 if (T->isObjCObjectType()) {
9674 Diag(Loc, diag::err_objc_object_catch);
9675 Invalid = true;
9676 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009677 if (!getLangOptions().ObjCNonFragileABI)
9678 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009679 }
9680 }
9681
Abramo Bagnaradff19302011-03-08 08:55:46 +00009682 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9683 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009684 ExDecl->setExceptionVariable(true);
9685
Douglas Gregor8ca0c642011-12-10 01:22:52 +00009686 // In ARC, infer 'retaining' for variables of retainable type.
9687 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9688 Invalid = true;
9689
Douglas Gregor750734c2011-07-06 18:14:43 +00009690 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009691 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009692 // C++ [except.handle]p16:
9693 // The object declared in an exception-declaration or, if the
9694 // exception-declaration does not specify a name, a temporary (12.2) is
9695 // copy-initialized (8.5) from the exception object. [...]
9696 // The object is destroyed when the handler exits, after the destruction
9697 // of any automatic objects initialized within the handler.
9698 //
9699 // We just pretend to initialize the object with itself, then make sure
9700 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009701 QualType initType = ExDeclType;
9702
9703 InitializedEntity entity =
9704 InitializedEntity::InitializeVariable(ExDecl);
9705 InitializationKind initKind =
9706 InitializationKind::CreateCopy(Loc, SourceLocation());
9707
9708 Expr *opaqueValue =
9709 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9710 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9711 ExprResult result = sequence.Perform(*this, entity, initKind,
9712 MultiExprArg(&opaqueValue, 1));
9713 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009714 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009715 else {
9716 // If the constructor used was non-trivial, set this as the
9717 // "initializer".
9718 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9719 if (!construct->getConstructor()->isTrivial()) {
9720 Expr *init = MaybeCreateExprWithCleanups(construct);
9721 ExDecl->setInit(init);
9722 }
9723
9724 // And make sure it's destructable.
9725 FinalizeVarWithDestructor(ExDecl, recordType);
9726 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009727 }
9728 }
9729
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009730 if (Invalid)
9731 ExDecl->setInvalidDecl();
9732
9733 return ExDecl;
9734}
9735
9736/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9737/// handler.
John McCall48871652010-08-21 09:40:31 +00009738Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009739 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009740 bool Invalid = D.isInvalidType();
9741
9742 // Check for unexpanded parameter packs.
9743 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9744 UPPC_ExceptionType)) {
9745 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9746 D.getIdentifierLoc());
9747 Invalid = true;
9748 }
9749
Sebastian Redl54c04d42008-12-22 19:15:10 +00009750 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009751 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009752 LookupOrdinaryName,
9753 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009754 // The scope should be freshly made just for us. There is just no way
9755 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009756 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009757 if (PrevDecl->isTemplateParameter()) {
9758 // Maybe we will complain about the shadowed template parameter.
9759 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009760 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009761 }
9762 }
9763
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009764 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009765 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9766 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009767 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009768 }
9769
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009770 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009771 D.getSourceRange().getBegin(),
9772 D.getIdentifierLoc(),
9773 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009774 if (Invalid)
9775 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009776
Sebastian Redl54c04d42008-12-22 19:15:10 +00009777 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009778 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009779 PushOnScopeChains(ExDecl, S);
9780 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009781 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009782
Douglas Gregor758a8692009-06-17 21:51:59 +00009783 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009784 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009785}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009786
Abramo Bagnaraea947882011-03-08 16:41:52 +00009787Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009788 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009789 Expr *AssertMessageExpr_,
9790 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009791 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009792
Anders Carlsson54b26982009-03-14 00:33:21 +00009793 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009794 // In a static_assert-declaration, the constant-expression shall be a
9795 // constant expression that can be contextually converted to bool.
9796 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9797 if (Converted.isInvalid())
9798 return 0;
9799
Richard Smith902ca212011-12-14 23:32:26 +00009800 llvm::APSInt Cond;
Richard Smithf4c51d92012-02-04 09:53:13 +00009801 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9802 PDiag(diag::err_static_assert_expression_is_not_constant),
9803 /*AllowFold=*/false).isInvalid())
John McCall48871652010-08-21 09:40:31 +00009804 return 0;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009805
Richard Smith902ca212011-12-14 23:32:26 +00009806 if (!Cond)
Abramo Bagnaraea947882011-03-08 16:41:52 +00009807 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009808 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009809 }
Mike Stump11289f42009-09-09 15:08:12 +00009810
Douglas Gregoref68fee2010-12-15 23:55:21 +00009811 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9812 return 0;
9813
Abramo Bagnaraea947882011-03-08 16:41:52 +00009814 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9815 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009816
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009817 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009818 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009819}
Sebastian Redlf769df52009-03-24 22:27:57 +00009820
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009821/// \brief Perform semantic analysis of the given friend type declaration.
9822///
9823/// \returns A friend declaration that.
Abramo Bagnara254b6302011-10-29 20:52:52 +00009824FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9825 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009826 TypeSourceInfo *TSInfo) {
9827 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9828
9829 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009830 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009831
Richard Smithc8239732011-10-18 21:39:00 +00009832 // C++03 [class.friend]p2:
9833 // An elaborated-type-specifier shall be used in a friend declaration
9834 // for a class.*
9835 //
9836 // * The class-key of the elaborated-type-specifier is required.
9837 if (!ActiveTemplateInstantiations.empty()) {
9838 // Do not complain about the form of friend template types during
9839 // template instantiation; we will already have complained when the
9840 // template was declared.
9841 } else if (!T->isElaboratedTypeSpecifier()) {
9842 // If we evaluated the type to a record type, suggest putting
9843 // a tag in front.
9844 if (const RecordType *RT = T->getAs<RecordType>()) {
9845 RecordDecl *RD = RT->getDecl();
9846
9847 std::string InsertionText = std::string(" ") + RD->getKindName();
9848
9849 Diag(TypeRange.getBegin(),
9850 getLangOptions().CPlusPlus0x ?
9851 diag::warn_cxx98_compat_unelaborated_friend_type :
9852 diag::ext_unelaborated_friend_type)
9853 << (unsigned) RD->getTagKind()
9854 << T
9855 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9856 InsertionText);
9857 } else {
9858 Diag(FriendLoc,
9859 getLangOptions().CPlusPlus0x ?
9860 diag::warn_cxx98_compat_nonclass_type_friend :
9861 diag::ext_nonclass_type_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009862 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009863 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009864 }
Richard Smithc8239732011-10-18 21:39:00 +00009865 } else if (T->getAs<EnumType>()) {
9866 Diag(FriendLoc,
9867 getLangOptions().CPlusPlus0x ?
9868 diag::warn_cxx98_compat_enum_friend :
9869 diag::ext_enum_friend)
9870 << T
9871 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009872 }
9873
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009874 // C++0x [class.friend]p3:
9875 // If the type specifier in a friend declaration designates a (possibly
9876 // cv-qualified) class type, that class is declared as a friend; otherwise,
9877 // the friend declaration is ignored.
9878
9879 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9880 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009881
Abramo Bagnara254b6302011-10-29 20:52:52 +00009882 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009883}
9884
John McCallace48cd2010-10-19 01:40:49 +00009885/// Handle a friend tag declaration where the scope specifier was
9886/// templated.
9887Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9888 unsigned TagSpec, SourceLocation TagLoc,
9889 CXXScopeSpec &SS,
9890 IdentifierInfo *Name, SourceLocation NameLoc,
9891 AttributeList *Attr,
9892 MultiTemplateParamsArg TempParamLists) {
9893 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9894
9895 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009896 bool Invalid = false;
9897
9898 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009899 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009900 TempParamLists.get(),
9901 TempParamLists.size(),
9902 /*friend*/ true,
9903 isExplicitSpecialization,
9904 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009905 if (TemplateParams->size() > 0) {
9906 // This is a declaration of a class template.
9907 if (Invalid)
9908 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009909
Eric Christopher6f228b52011-07-21 05:34:24 +00009910 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9911 SS, Name, NameLoc, Attr,
9912 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009913 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009914 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009915 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009916 } else {
9917 // The "template<>" header is extraneous.
9918 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9919 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9920 isExplicitSpecialization = true;
9921 }
9922 }
9923
9924 if (Invalid) return 0;
9925
John McCallace48cd2010-10-19 01:40:49 +00009926 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009927 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009928 if (TempParamLists.get()[I]->size()) {
9929 isAllExplicitSpecializations = false;
9930 break;
9931 }
9932 }
9933
9934 // FIXME: don't ignore attributes.
9935
9936 // If it's explicit specializations all the way down, just forget
9937 // about the template header and build an appropriate non-templated
9938 // friend. TODO: for source fidelity, remember the headers.
9939 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +00009940 if (SS.isEmpty()) {
9941 bool Owned = false;
9942 bool IsDependent = false;
9943 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9944 Attr, AS_public,
9945 /*ModulePrivateLoc=*/SourceLocation(),
9946 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +00009947 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +00009948 /*ScopedEnumUsesClassTag=*/false,
9949 /*UnderlyingType=*/TypeResult());
9950 }
9951
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009952 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009953 ElaboratedTypeKeyword Keyword
9954 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009955 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009956 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009957 if (T.isNull())
9958 return 0;
9959
9960 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9961 if (isa<DependentNameType>(T)) {
9962 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009963 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009964 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009965 TL.setNameLoc(NameLoc);
9966 } else {
9967 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009968 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009969 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009970 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9971 }
9972
9973 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9974 TSI, FriendLoc);
9975 Friend->setAccess(AS_public);
9976 CurContext->addDecl(Friend);
9977 return Friend;
9978 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +00009979
9980 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9981
9982
John McCallace48cd2010-10-19 01:40:49 +00009983
9984 // Handle the case of a templated-scope friend class. e.g.
9985 // template <class T> class A<T>::B;
9986 // FIXME: we don't support these right now.
9987 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9988 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9989 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9990 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00009991 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009992 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00009993 TL.setNameLoc(NameLoc);
9994
9995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9996 TSI, FriendLoc);
9997 Friend->setAccess(AS_public);
9998 Friend->setUnsupportedFriend(true);
9999 CurContext->addDecl(Friend);
10000 return Friend;
10001}
10002
10003
John McCall11083da2009-09-16 22:47:08 +000010004/// Handle a friend type declaration. This works in tandem with
10005/// ActOnTag.
10006///
10007/// Notes on friend class templates:
10008///
10009/// We generally treat friend class declarations as if they were
10010/// declaring a class. So, for example, the elaborated type specifier
10011/// in a friend declaration is required to obey the restrictions of a
10012/// class-head (i.e. no typedefs in the scope chain), template
10013/// parameters are required to match up with simple template-ids, &c.
10014/// However, unlike when declaring a template specialization, it's
10015/// okay to refer to a template specialization without an empty
10016/// template parameter declaration, e.g.
10017/// friend class A<T>::B<unsigned>;
10018/// We permit this as a special case; if there are any template
10019/// parameters present at all, require proper matching, i.e.
10020/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010021Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010022 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010023 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010024
10025 assert(DS.isFriendSpecified());
10026 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10027
John McCall11083da2009-09-16 22:47:08 +000010028 // Try to convert the decl specifier to a type. This works for
10029 // friend templates because ActOnTag never produces a ClassTemplateDecl
10030 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010031 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010032 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10033 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010034 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010035 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010036
Douglas Gregor6c110f32010-12-16 01:14:37 +000010037 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10038 return 0;
10039
John McCall11083da2009-09-16 22:47:08 +000010040 // This is definitely an error in C++98. It's probably meant to
10041 // be forbidden in C++0x, too, but the specification is just
10042 // poorly written.
10043 //
10044 // The problem is with declarations like the following:
10045 // template <T> friend A<T>::foo;
10046 // where deciding whether a class C is a friend or not now hinges
10047 // on whether there exists an instantiation of A that causes
10048 // 'foo' to equal C. There are restrictions on class-heads
10049 // (which we declare (by fiat) elaborated friend declarations to
10050 // be) that makes this tractable.
10051 //
10052 // FIXME: handle "template <> friend class A<T>;", which
10053 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010054 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010055 Diag(Loc, diag::err_tagless_friend_type_template)
10056 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010057 return 0;
John McCall11083da2009-09-16 22:47:08 +000010058 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010059
John McCallaa74a0c2009-08-28 07:59:38 +000010060 // C++98 [class.friend]p1: A friend of a class is a function
10061 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010062 // This is fixed in DR77, which just barely didn't make the C++03
10063 // deadline. It's also a very silly restriction that seriously
10064 // affects inner classes and which nobody else seems to implement;
10065 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010066 //
10067 // But note that we could warn about it: it's always useless to
10068 // friend one of your own members (it's not, however, worthless to
10069 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010070
John McCall11083da2009-09-16 22:47:08 +000010071 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010072 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010073 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010074 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010075 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010076 TSI,
John McCall11083da2009-09-16 22:47:08 +000010077 DS.getFriendSpecLoc());
10078 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000010079 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010080
10081 if (!D)
John McCall48871652010-08-21 09:40:31 +000010082 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010083
John McCall11083da2009-09-16 22:47:08 +000010084 D->setAccess(AS_public);
10085 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010086
John McCall48871652010-08-21 09:40:31 +000010087 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010088}
10089
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010090Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCallde3fd222010-10-12 23:13:28 +000010091 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010092 const DeclSpec &DS = D.getDeclSpec();
10093
10094 assert(DS.isFriendSpecified());
10095 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10096
10097 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010098 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000010099
10100 // C++ [class.friend]p1
10101 // A friend of a class is a function or class....
10102 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010103 // It *doesn't* see through dependent types, which is correct
10104 // according to [temp.arg.type]p3:
10105 // If a declaration acquires a function type through a
10106 // type dependent on a template-parameter and this causes
10107 // a declaration that does not use the syntactic form of a
10108 // function declarator to have a function type, the program
10109 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010110 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000010111 Diag(Loc, diag::err_unexpected_friend);
10112
10113 // It might be worthwhile to try to recover by creating an
10114 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010115 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010116 }
10117
10118 // C++ [namespace.memdef]p3
10119 // - If a friend declaration in a non-local class first declares a
10120 // class or function, the friend class or function is a member
10121 // of the innermost enclosing namespace.
10122 // - The name of the friend is not found by simple name lookup
10123 // until a matching declaration is provided in that namespace
10124 // scope (either before or after the class declaration granting
10125 // friendship).
10126 // - If a friend function is called, its name may be found by the
10127 // name lookup that considers functions from namespaces and
10128 // classes associated with the types of the function arguments.
10129 // - When looking for a prior declaration of a class or a function
10130 // declared as a friend, scopes outside the innermost enclosing
10131 // namespace scope are not considered.
10132
John McCallde3fd222010-10-12 23:13:28 +000010133 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010134 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10135 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010136 assert(Name);
10137
Douglas Gregor6c110f32010-12-16 01:14:37 +000010138 // Check for unexpanded parameter packs.
10139 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10140 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10141 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10142 return 0;
10143
John McCall07e91c02009-08-06 02:15:43 +000010144 // The context we found the declaration in, or in which we should
10145 // create the declaration.
10146 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010147 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010148 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010149 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010150
John McCallde3fd222010-10-12 23:13:28 +000010151 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010152
John McCallde3fd222010-10-12 23:13:28 +000010153 // There are four cases here.
10154 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010155 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010156 // there as appropriate.
10157 // Recover from invalid scope qualifiers as if they just weren't there.
10158 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010159 // C++0x [namespace.memdef]p3:
10160 // If the name in a friend declaration is neither qualified nor
10161 // a template-id and the declaration is a function or an
10162 // elaborated-type-specifier, the lookup to determine whether
10163 // the entity has been previously declared shall not consider
10164 // any scopes outside the innermost enclosing namespace.
10165 // C++0x [class.friend]p11:
10166 // If a friend declaration appears in a local class and the name
10167 // specified is an unqualified name, a prior declaration is
10168 // looked up without considering scopes that are outside the
10169 // innermost enclosing non-class scope. For a friend function
10170 // declaration, if there is no prior declaration, the program is
10171 // ill-formed.
10172 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010173 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010174
John McCallf7cfb222010-10-13 05:45:15 +000010175 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010176 DC = CurContext;
10177 while (true) {
10178 // Skip class contexts. If someone can cite chapter and verse
10179 // for this behavior, that would be nice --- it's what GCC and
10180 // EDG do, and it seems like a reasonable intent, but the spec
10181 // really only says that checks for unqualified existing
10182 // declarations should stop at the nearest enclosing namespace,
10183 // not that they should only consider the nearest enclosing
10184 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010185 while (DC->isRecord())
10186 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010187
John McCall1f82f242009-11-18 22:49:29 +000010188 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010189
10190 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010191 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010192 break;
John McCallf7cfb222010-10-13 05:45:15 +000010193
John McCallf4776592010-10-14 22:22:28 +000010194 if (isTemplateId) {
10195 if (isa<TranslationUnitDecl>(DC)) break;
10196 } else {
10197 if (DC->isFileContext()) break;
10198 }
John McCall07e91c02009-08-06 02:15:43 +000010199 DC = DC->getParent();
10200 }
10201
10202 // C++ [class.friend]p1: A friend of a class is a function or
10203 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010204 // C++11 changes this for both friend types and functions.
John McCall93343b92009-08-06 20:49:32 +000010205 // Most C++ 98 compilers do seem to give an error here, so
10206 // we do, too.
Richard Smith0bf8a4922011-10-18 20:49:44 +000010207 if (!Previous.empty() && DC->Equals(CurContext))
10208 Diag(DS.getFriendSpecLoc(),
10209 getLangOptions().CPlusPlus0x ?
10210 diag::warn_cxx98_compat_friend_is_member :
10211 diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010212
John McCallccbc0322010-10-13 06:22:15 +000010213 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregordd847ba2011-11-03 16:37:14 +000010214
Douglas Gregor16e65612011-10-10 01:11:59 +000010215 // C++ [class.friend]p6:
10216 // A function can be defined in a friend declaration of a class if and
10217 // only if the class is a non-local class (9.8), the function name is
10218 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010219 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010220 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10221 }
10222
John McCallde3fd222010-10-12 23:13:28 +000010223 // - There's a non-dependent scope specifier, in which case we
10224 // compute it and do a previous lookup there for a function
10225 // or function template.
10226 } else if (!SS.getScopeRep()->isDependent()) {
10227 DC = computeDeclContext(SS);
10228 if (!DC) return 0;
10229
10230 if (RequireCompleteDeclContext(SS, DC)) return 0;
10231
10232 LookupQualifiedName(Previous, DC);
10233
10234 // Ignore things found implicitly in the wrong scope.
10235 // TODO: better diagnostics for this case. Suggesting the right
10236 // qualified scope would be nice...
10237 LookupResult::Filter F = Previous.makeFilter();
10238 while (F.hasNext()) {
10239 NamedDecl *D = F.next();
10240 if (!DC->InEnclosingNamespaceSetOf(
10241 D->getDeclContext()->getRedeclContext()))
10242 F.erase();
10243 }
10244 F.done();
10245
10246 if (Previous.empty()) {
10247 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010248 Diag(Loc, diag::err_qualified_friend_not_found)
10249 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000010250 return 0;
10251 }
10252
10253 // C++ [class.friend]p1: A friend of a class is a function or
10254 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010255 if (DC->Equals(CurContext))
10256 Diag(DS.getFriendSpecLoc(),
10257 getLangOptions().CPlusPlus0x ?
10258 diag::warn_cxx98_compat_friend_is_member :
10259 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010260
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010261 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010262 // C++ [class.friend]p6:
10263 // A function can be defined in a friend declaration of a class if and
10264 // only if the class is a non-local class (9.8), the function name is
10265 // unqualified, and the function has namespace scope.
10266 SemaDiagnosticBuilder DB
10267 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10268
10269 DB << SS.getScopeRep();
10270 if (DC->isFileContext())
10271 DB << FixItHint::CreateRemoval(SS.getRange());
10272 SS.clear();
10273 }
John McCallde3fd222010-10-12 23:13:28 +000010274
10275 // - There's a scope specifier that does not match any template
10276 // parameter lists, in which case we use some arbitrary context,
10277 // create a method or method template, and wait for instantiation.
10278 // - There's a scope specifier that does match some template
10279 // parameter lists, which we don't handle right now.
10280 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010281 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010282 // C++ [class.friend]p6:
10283 // A function can be defined in a friend declaration of a class if and
10284 // only if the class is a non-local class (9.8), the function name is
10285 // unqualified, and the function has namespace scope.
10286 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10287 << SS.getScopeRep();
10288 }
10289
John McCallde3fd222010-10-12 23:13:28 +000010290 DC = CurContext;
10291 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010292 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010293
John McCallf7cfb222010-10-13 05:45:15 +000010294 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010295 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010296 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10297 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10298 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010299 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010300 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10301 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010302 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010303 }
John McCall07e91c02009-08-06 02:15:43 +000010304 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010305
Douglas Gregordd847ba2011-11-03 16:37:14 +000010306 // FIXME: This is an egregious hack to cope with cases where the scope stack
10307 // does not contain the declaration context, i.e., in an out-of-line
10308 // definition of a class.
10309 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10310 if (!DCScope) {
10311 FakeDCScope.setEntity(DC);
10312 DCScope = &FakeDCScope;
10313 }
10314
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010315 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010316 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10317 move(TemplateParams), AddToScope);
John McCall48871652010-08-21 09:40:31 +000010318 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010319
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010320 assert(ND->getDeclContext() == DC);
10321 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010322
John McCall759e32b2009-08-31 22:39:49 +000010323 // Add the function declaration to the appropriate lookup tables,
10324 // adjusting the redeclarations list as necessary. We don't
10325 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010326 //
John McCall759e32b2009-08-31 22:39:49 +000010327 // Also update the scope-based lookup if the target context's
10328 // lookup context is in lexical scope.
10329 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010330 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010331 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010332 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010333 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010334 }
John McCallaa74a0c2009-08-28 07:59:38 +000010335
10336 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010337 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010338 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010339 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010340 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010341
John McCallde3fd222010-10-12 23:13:28 +000010342 if (ND->isInvalidDecl())
10343 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010344 else {
10345 FunctionDecl *FD;
10346 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10347 FD = FTD->getTemplatedDecl();
10348 else
10349 FD = cast<FunctionDecl>(ND);
10350
10351 // Mark templated-scope function declarations as unsupported.
10352 if (FD->getNumTemplateParameterLists())
10353 FrD->setUnsupportedFriend(true);
10354 }
John McCallde3fd222010-10-12 23:13:28 +000010355
John McCall48871652010-08-21 09:40:31 +000010356 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010357}
10358
John McCall48871652010-08-21 09:40:31 +000010359void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10360 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010361
Sebastian Redlf769df52009-03-24 22:27:57 +000010362 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10363 if (!Fn) {
10364 Diag(DelLoc, diag::err_deleted_non_function);
10365 return;
10366 }
Douglas Gregorec9fd132012-01-14 16:38:05 +000010367 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redlf769df52009-03-24 22:27:57 +000010368 Diag(DelLoc, diag::err_deleted_decl_not_first);
10369 Diag(Prev->getLocation(), diag::note_previous_declaration);
10370 // If the declaration wasn't the first, we delete the function anyway for
10371 // recovery.
10372 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010373 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010374}
Sebastian Redl4c018662009-04-27 21:33:24 +000010375
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010376void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10377 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10378
10379 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010380 if (MD->getParent()->isDependentType()) {
10381 MD->setDefaulted();
10382 MD->setExplicitlyDefaulted();
10383 return;
10384 }
10385
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010386 CXXSpecialMember Member = getSpecialMember(MD);
10387 if (Member == CXXInvalid) {
10388 Diag(DefaultLoc, diag::err_default_special_members);
10389 return;
10390 }
10391
10392 MD->setDefaulted();
10393 MD->setExplicitlyDefaulted();
10394
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010395 // If this definition appears within the record, do the checking when
10396 // the record is complete.
10397 const FunctionDecl *Primary = MD;
10398 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10399 // Find the uninstantiated declaration that actually had the '= default'
10400 // on it.
10401 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10402
10403 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010404 return;
10405
10406 switch (Member) {
10407 case CXXDefaultConstructor: {
10408 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10409 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010410 if (!CD->isInvalidDecl())
10411 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10412 break;
10413 }
10414
10415 case CXXCopyConstructor: {
10416 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10417 CheckExplicitlyDefaultedCopyConstructor(CD);
10418 if (!CD->isInvalidDecl())
10419 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010420 break;
10421 }
Alexis Huntf91729462011-05-12 22:46:25 +000010422
Alexis Huntc9a55732011-05-14 05:23:28 +000010423 case CXXCopyAssignment: {
10424 CheckExplicitlyDefaultedCopyAssignment(MD);
10425 if (!MD->isInvalidDecl())
10426 DefineImplicitCopyAssignment(DefaultLoc, MD);
10427 break;
10428 }
10429
Alexis Huntf91729462011-05-12 22:46:25 +000010430 case CXXDestructor: {
10431 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10432 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010433 if (!DD->isInvalidDecl())
10434 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010435 break;
10436 }
10437
Sebastian Redl22653ba2011-08-30 19:58:05 +000010438 case CXXMoveConstructor: {
10439 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10440 CheckExplicitlyDefaultedMoveConstructor(CD);
10441 if (!CD->isInvalidDecl())
10442 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010443 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010444 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010445
Sebastian Redl22653ba2011-08-30 19:58:05 +000010446 case CXXMoveAssignment: {
10447 CheckExplicitlyDefaultedMoveAssignment(MD);
10448 if (!MD->isInvalidDecl())
10449 DefineImplicitMoveAssignment(DefaultLoc, MD);
10450 break;
10451 }
10452
10453 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010454 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010455 }
10456 } else {
10457 Diag(DefaultLoc, diag::err_default_special_members);
10458 }
10459}
10460
Sebastian Redl4c018662009-04-27 21:33:24 +000010461static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010462 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010463 Stmt *SubStmt = *CI;
10464 if (!SubStmt)
10465 continue;
10466 if (isa<ReturnStmt>(SubStmt))
10467 Self.Diag(SubStmt->getSourceRange().getBegin(),
10468 diag::err_return_in_constructor_handler);
10469 if (!isa<Expr>(SubStmt))
10470 SearchForReturnInStmt(Self, SubStmt);
10471 }
10472}
10473
10474void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10475 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10476 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10477 SearchForReturnInStmt(*this, Handler);
10478 }
10479}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010480
Mike Stump11289f42009-09-09 15:08:12 +000010481bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010482 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010483 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10484 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010485
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010486 if (Context.hasSameType(NewTy, OldTy) ||
10487 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010488 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010489
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010490 // Check if the return types are covariant
10491 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010492
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010493 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010494 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10495 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010496 NewClassTy = NewPT->getPointeeType();
10497 OldClassTy = OldPT->getPointeeType();
10498 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010499 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10500 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10501 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10502 NewClassTy = NewRT->getPointeeType();
10503 OldClassTy = OldRT->getPointeeType();
10504 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010505 }
10506 }
Mike Stump11289f42009-09-09 15:08:12 +000010507
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010508 // The return types aren't either both pointers or references to a class type.
10509 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010510 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010511 diag::err_different_return_type_for_overriding_virtual_function)
10512 << New->getDeclName() << NewTy << OldTy;
10513 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010514
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010515 return true;
10516 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010517
Anders Carlssone60365b2009-12-31 18:34:24 +000010518 // C++ [class.virtual]p6:
10519 // If the return type of D::f differs from the return type of B::f, the
10520 // class type in the return type of D::f shall be complete at the point of
10521 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010522 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10523 if (!RT->isBeingDefined() &&
10524 RequireCompleteType(New->getLocation(), NewClassTy,
10525 PDiag(diag::err_covariant_return_incomplete)
10526 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010527 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010528 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010529
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010530 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010531 // Check if the new class derives from the old class.
10532 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10533 Diag(New->getLocation(),
10534 diag::err_covariant_return_not_derived)
10535 << New->getDeclName() << NewTy << OldTy;
10536 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10537 return true;
10538 }
Mike Stump11289f42009-09-09 15:08:12 +000010539
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010540 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010541 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010542 diag::err_covariant_return_inaccessible_base,
10543 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10544 // FIXME: Should this point to the return type?
10545 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010546 // FIXME: this note won't trigger for delayed access control
10547 // diagnostics, and it's impossible to get an undelayed error
10548 // here from access control during the original parse because
10549 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010550 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10551 return true;
10552 }
10553 }
Mike Stump11289f42009-09-09 15:08:12 +000010554
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010555 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010556 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010557 Diag(New->getLocation(),
10558 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010559 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010560 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10561 return true;
10562 };
Mike Stump11289f42009-09-09 15:08:12 +000010563
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010564
10565 // The new class type must have the same or less qualifiers as the old type.
10566 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10567 Diag(New->getLocation(),
10568 diag::err_covariant_return_type_class_type_more_qualified)
10569 << New->getDeclName() << NewTy << OldTy;
10570 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10571 return true;
10572 };
Mike Stump11289f42009-09-09 15:08:12 +000010573
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010574 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010575}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010576
Douglas Gregor21920e372009-12-01 17:24:26 +000010577/// \brief Mark the given method pure.
10578///
10579/// \param Method the method to be marked pure.
10580///
10581/// \param InitRange the source range that covers the "0" initializer.
10582bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010583 SourceLocation EndLoc = InitRange.getEnd();
10584 if (EndLoc.isValid())
10585 Method->setRangeEnd(EndLoc);
10586
Douglas Gregor21920e372009-12-01 17:24:26 +000010587 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10588 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010589 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010590 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010591
10592 if (!Method->isInvalidDecl())
10593 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10594 << Method->getDeclName() << InitRange;
10595 return true;
10596}
10597
John McCall1f4ee7b2009-12-19 09:28:58 +000010598/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10599/// an initializer for the out-of-line declaration 'Dcl'. The scope
10600/// is a fresh scope pushed for just this purpose.
10601///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010602/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10603/// static data member of class X, names should be looked up in the scope of
10604/// class X.
John McCall48871652010-08-21 09:40:31 +000010605void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010606 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010607 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010608
John McCall1f4ee7b2009-12-19 09:28:58 +000010609 // We should only get called for declarations with scope specifiers, like:
10610 // int foo::bar;
10611 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010612 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010613}
10614
10615/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010616/// initializer for the out-of-line declaration 'D'.
10617void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010618 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010619 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010620
John McCall1f4ee7b2009-12-19 09:28:58 +000010621 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010622 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010623}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010624
10625/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10626/// C++ if/switch/while/for statement.
10627/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010628DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010629 // C++ 6.4p2:
10630 // The declarator shall not specify a function or an array.
10631 // The type-specifier-seq shall not contain typedef and shall not declare a
10632 // new class or enumeration.
10633 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10634 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010635
10636 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010637 if (!Dcl)
10638 return true;
10639
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010640 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10641 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010642 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010643 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010644 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010645
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010646 return Dcl;
10647}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010648
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010649void Sema::LoadExternalVTableUses() {
10650 if (!ExternalSource)
10651 return;
10652
10653 SmallVector<ExternalVTableUse, 4> VTables;
10654 ExternalSource->ReadUsedVTables(VTables);
10655 SmallVector<VTableUse, 4> NewUses;
10656 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10657 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10658 = VTablesUsed.find(VTables[I].Record);
10659 // Even if a definition wasn't required before, it may be required now.
10660 if (Pos != VTablesUsed.end()) {
10661 if (!Pos->second && VTables[I].DefinitionRequired)
10662 Pos->second = true;
10663 continue;
10664 }
10665
10666 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10667 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10668 }
10669
10670 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10671}
10672
Douglas Gregor88d292c2010-05-13 16:44:06 +000010673void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10674 bool DefinitionRequired) {
10675 // Ignore any vtable uses in unevaluated operands or for classes that do
10676 // not have a vtable.
10677 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10678 CurContext->isDependentContext() ||
Eli Friedman02b58512012-01-21 04:44:06 +000010679 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010680 return;
10681
Douglas Gregor88d292c2010-05-13 16:44:06 +000010682 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010683 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010684 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10685 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10686 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10687 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010688 // If we already had an entry, check to see if we are promoting this vtable
10689 // to required a definition. If so, we need to reappend to the VTableUses
10690 // list, since we may have already processed the first entry.
10691 if (DefinitionRequired && !Pos.first->second) {
10692 Pos.first->second = true;
10693 } else {
10694 // Otherwise, we can early exit.
10695 return;
10696 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010697 }
10698
10699 // Local classes need to have their virtual members marked
10700 // immediately. For all other classes, we mark their virtual members
10701 // at the end of the translation unit.
10702 if (Class->isLocalClass())
10703 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010704 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010705 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010706}
10707
Douglas Gregor88d292c2010-05-13 16:44:06 +000010708bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010709 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010710 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010711 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010712
Douglas Gregor88d292c2010-05-13 16:44:06 +000010713 // Note: The VTableUses vector could grow as a result of marking
10714 // the members of a class as "used", so we check the size each
10715 // time through the loop and prefer indices (with are stable) to
10716 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010717 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010718 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010719 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010720 if (!Class)
10721 continue;
10722
10723 SourceLocation Loc = VTableUses[I].second;
10724
10725 // If this class has a key function, but that key function is
10726 // defined in another translation unit, we don't need to emit the
10727 // vtable even though we're using it.
10728 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010729 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010730 switch (KeyFunction->getTemplateSpecializationKind()) {
10731 case TSK_Undeclared:
10732 case TSK_ExplicitSpecialization:
10733 case TSK_ExplicitInstantiationDeclaration:
10734 // The key function is in another translation unit.
10735 continue;
10736
10737 case TSK_ExplicitInstantiationDefinition:
10738 case TSK_ImplicitInstantiation:
10739 // We will be instantiating the key function.
10740 break;
10741 }
10742 } else if (!KeyFunction) {
10743 // If we have a class with no key function that is the subject
10744 // of an explicit instantiation declaration, suppress the
10745 // vtable; it will live with the explicit instantiation
10746 // definition.
10747 bool IsExplicitInstantiationDeclaration
10748 = Class->getTemplateSpecializationKind()
10749 == TSK_ExplicitInstantiationDeclaration;
10750 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10751 REnd = Class->redecls_end();
10752 R != REnd; ++R) {
10753 TemplateSpecializationKind TSK
10754 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10755 if (TSK == TSK_ExplicitInstantiationDeclaration)
10756 IsExplicitInstantiationDeclaration = true;
10757 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10758 IsExplicitInstantiationDeclaration = false;
10759 break;
10760 }
10761 }
10762
10763 if (IsExplicitInstantiationDeclaration)
10764 continue;
10765 }
10766
10767 // Mark all of the virtual members of this class as referenced, so
10768 // that we can build a vtable. Then, tell the AST consumer that a
10769 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010770 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010771 MarkVirtualMembersReferenced(Loc, Class);
10772 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10773 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10774
10775 // Optionally warn if we're emitting a weak vtable.
10776 if (Class->getLinkage() == ExternalLinkage &&
10777 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010778 const FunctionDecl *KeyFunctionDef = 0;
10779 if (!KeyFunction ||
10780 (KeyFunction->hasBody(KeyFunctionDef) &&
10781 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000010782 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10783 TSK_ExplicitInstantiationDefinition
10784 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10785 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010786 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010787 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010788 VTableUses.clear();
10789
Douglas Gregor97509692011-04-22 22:25:37 +000010790 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010791}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010792
Rafael Espindola5b334082010-03-26 00:36:59 +000010793void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10794 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010795 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10796 e = RD->method_end(); i != e; ++i) {
10797 CXXMethodDecl *MD = *i;
10798
10799 // C++ [basic.def.odr]p2:
10800 // [...] A virtual member function is used if it is not pure. [...]
10801 if (MD->isVirtual() && !MD->isPure())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010802 MarkFunctionReferenced(Loc, MD);
Anders Carlsson82fccd02009-12-07 08:24:59 +000010803 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010804
10805 // Only classes that have virtual bases need a VTT.
10806 if (RD->getNumVBases() == 0)
10807 return;
10808
10809 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10810 e = RD->bases_end(); i != e; ++i) {
10811 const CXXRecordDecl *Base =
10812 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010813 if (Base->getNumVBases() == 0)
10814 continue;
10815 MarkVirtualMembersReferenced(Loc, Base);
10816 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010817}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010818
10819/// SetIvarInitializers - This routine builds initialization ASTs for the
10820/// Objective-C implementation whose ivars need be initialized.
10821void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10822 if (!getLangOptions().CPlusPlus)
10823 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010824 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010825 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010826 CollectIvarsToConstructOrDestruct(OID, ivars);
10827 if (ivars.empty())
10828 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010829 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010830 for (unsigned i = 0; i < ivars.size(); i++) {
10831 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010832 if (Field->isInvalidDecl())
10833 continue;
10834
Alexis Hunt1d792652011-01-08 20:30:50 +000010835 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010836 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10837 InitializationKind InitKind =
10838 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10839
10840 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010841 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010842 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010843 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010844 // Note, MemberInit could actually come back empty if no initialization
10845 // is required (e.g., because it would call a trivial default constructor)
10846 if (!MemberInit.get() || MemberInit.isInvalid())
10847 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010848
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010849 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010850 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10851 SourceLocation(),
10852 MemberInit.takeAs<Expr>(),
10853 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010854 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010855
10856 // Be sure that the destructor is accessible and is marked as referenced.
10857 if (const RecordType *RecordTy
10858 = Context.getBaseElementType(Field->getType())
10859 ->getAs<RecordType>()) {
10860 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010861 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010862 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000010863 CheckDestructorAccess(Field->getLocation(), Destructor,
10864 PDiag(diag::err_access_dtor_ivar)
10865 << Context.getBaseElementType(Field->getType()));
10866 }
10867 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010868 }
10869 ObjCImplementation->setIvarInitializers(Context,
10870 AllToInit.data(), AllToInit.size());
10871 }
10872}
Alexis Hunt6118d662011-05-04 05:57:24 +000010873
Alexis Hunt27a761d2011-05-04 23:29:54 +000010874static
10875void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10876 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10877 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10878 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10879 Sema &S) {
10880 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10881 CE = Current.end();
10882 if (Ctor->isInvalidDecl())
10883 return;
10884
10885 const FunctionDecl *FNTarget = 0;
10886 CXXConstructorDecl *Target;
10887
10888 // We ignore the result here since if we don't have a body, Target will be
10889 // null below.
10890 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10891 Target
10892= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10893
10894 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10895 // Avoid dereferencing a null pointer here.
10896 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10897
10898 if (!Current.insert(Canonical))
10899 return;
10900
10901 // We know that beyond here, we aren't chaining into a cycle.
10902 if (!Target || !Target->isDelegatingConstructor() ||
10903 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10904 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10905 Valid.insert(*CI);
10906 Current.clear();
10907 // We've hit a cycle.
10908 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10909 Current.count(TCanonical)) {
10910 // If we haven't diagnosed this cycle yet, do so now.
10911 if (!Invalid.count(TCanonical)) {
10912 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010913 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010914 << Ctor;
10915
10916 // Don't add a note for a function delegating directo to itself.
10917 if (TCanonical != Canonical)
10918 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10919
10920 CXXConstructorDecl *C = Target;
10921 while (C->getCanonicalDecl() != Canonical) {
10922 (void)C->getTargetConstructor()->hasBody(FNTarget);
10923 assert(FNTarget && "Ctor cycle through bodiless function");
10924
10925 C
10926 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10927 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10928 }
10929 }
10930
10931 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10932 Invalid.insert(*CI);
10933 Current.clear();
10934 } else {
10935 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10936 }
10937}
10938
10939
Alexis Hunt6118d662011-05-04 05:57:24 +000010940void Sema::CheckDelegatingCtorCycles() {
10941 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10942
Alexis Hunt27a761d2011-05-04 23:29:54 +000010943 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10944 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010945
Douglas Gregorbae31202011-07-27 21:57:17 +000010946 for (DelegatingCtorDeclsType::iterator
10947 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010948 E = DelegatingCtorDecls.end();
10949 I != E; ++I) {
10950 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010951 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010952
10953 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10954 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010955}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010956
10957/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10958Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10959 // Implicitly declared functions (e.g. copy constructors) are
10960 // __host__ __device__
10961 if (D->isImplicit())
10962 return CFT_HostDevice;
10963
10964 if (D->hasAttr<CUDAGlobalAttr>())
10965 return CFT_Global;
10966
10967 if (D->hasAttr<CUDADeviceAttr>()) {
10968 if (D->hasAttr<CUDAHostAttr>())
10969 return CFT_HostDevice;
10970 else
10971 return CFT_Device;
10972 }
10973
10974 return CFT_Host;
10975}
10976
10977bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10978 CUDAFunctionTarget CalleeTarget) {
10979 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10980 // Callable from the device only."
10981 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10982 return true;
10983
10984 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10985 // Callable from the host only."
10986 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10987 // Callable from the host only."
10988 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10989 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10990 return true;
10991
10992 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10993 return true;
10994
10995 return false;
10996}